Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(grants): authorization reads unified token grant columns; bulk legacy conversion
garrytaneb71eb73fee1
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 6177b5ac8f..dac019a188 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -24,7 +24,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `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: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`.-- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.serial.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. F3: `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror, falling back to the JSONB-only shape on a brain whose schema predates the columns; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).+- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.serial.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes --no-autopilot-install`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar once no `.txt` of its session remains, after a 10-minute grace. Pinned by `test/session-seat-capture.serial.test.ts`.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.- `src/core/transcripts/pasted-content.ts` — #5812, the ONE Claude Code paste detector (`<pasted_content id="…">…</pasted_content id="…">`, tag shape from a real 2.1.287 transcript; depends on that harness format). `stripPastedContent` removes closed blocks and an unclosed tail only when the opening tag has the exact harness shape, scanning with `indexOf` (no lazy regex); `stripPastedContentFromCorpus` strips inside each `[user]` block of the `toCorpusText` rendering, never across the flattened corpus, so an unclosed paste ends with its turn. Consumers: the writeback gate (banked text), `isGenuineUserText` in the parser (classification only; turn, corpus, segment and ingest text keep the paste), and `corpusTextForExtraction` (`corpus-segments.ts`: a `.wb-` file is one turn, other corpus files per block) used by the sweep, the checkpoint harvest and dream `extract_atoms`. `synthesize` keeps pastes. Tests: `test/transcripts-pasted-content.test.ts`, `test/facts/writeback-gate.test.ts`, `test/extract-atoms-pasted-content.test.ts`.diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex c500619ad1..3f4e9ce2fc 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/env-trust.ts` — Trust boundary for environment variables Bun auto-loaded from the cwd `.env` family. `CWD_DOTENV_FILES` (the eight names Bun auto-loads across NODE_ENV values), `splitDotenvLines` (Bun's line grammar: `\n`, `\r\n` AND a bare `\r` terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), `dotenvValuesForKey(key, dir)` (value set across all assignments; the #427 `DATABASE_URL` value-match guard in config.ts, which re-exports both), `cwdDotenvAssignsKey(key, dir | assignments)` (KEY-PRESENCE predicate; an empty assignment counts) and `parseCwdDotenv(dir)` → `DotenvAssignment[]` (one read the two preflight consumers share). The assignment RHS is matched as `([^\r\n]*)`, never `.*$`. Protection is one predicate, `isCwdDotenvProtectedKey(key)`: `CWD_DOTENV_PROTECTED_KEYS` (code-loading / exec-target / root- and endpoint-redirect incl. `GBRAIN_DATABASE_URL` (key-presence; the #427 config.ts VALUE guard is separate and covers only bare `DATABASE_URL`), `GBRAIN_DIRECT_DATABASE_URL`, `GBRAIN_REMOTE_MCP_URL`, `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_OAUTH_RELAY_URL` / posture-widening `GBRAIN_*`, plus the re-run marker `GBRAIN_CWD_ENV_QUARANTINED`; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS `CWD_DOTENV_PROTECTED_PREFIXES` (`LD_`, `DYLD_`, `GIT_`, `BUN_`, `NPM_CONFIG_`, `npm_config_`, `BASH_FUNC_`) and `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS` (NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/ksh `ENV` deliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified. `quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })` iterates the keys the cwd .env files ASSIGN, deletes each protected one present in `env`, prints ONE stderr line (`formatQuarantineWarning`, composed from the exported `CWD_DOTENV_REMEDIATION` that guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicit `env` see Bun's startup snapshot, which is why `cli-preflight.ts` re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by `test/env-trust.test.ts`; the GBRAIN list is guarded against rot by the structural `test/env-trust-protected-keys.test.ts` (every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose name matches `_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix or `GBRAIN_ALLOW_` prefix must be on the list or carry a `cwd-dotenv-ok: <why>` annotation).-- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unmigrated `source_grant IS NULL` rows read through lane F's JSONB parsers; unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens may hold `none`; clients refuse it with `client_sources_none_unsupported`) and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`). `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy`) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).+- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens may hold `none`; clients refuse it with `client_sources_none_unsupported`) and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v201 (`lane_e_legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v201) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).- `src/core/grants/lifecycle.ts` + `src/commands/serve-http-clients.ts` — owner-authenticated client inspection, setup, export and lifecycle endpoints. Token invalidation/revoke/delete lock the OAuth client row, require reviewed revisions and explicit application, and commit an audit record atomically. Deletion records a tombstone while preserving request history and spending reservations/settlement; missing clients become terminal delegated denials while transient lookup failures remain retryable.- `src/commands/serve-http-api-keys.ts` — owner-dashboard legacy API keys (`/admin/api/api-keys`). Mint validates the request (`parseApiKeyMintRequest`: name 1-128 printable characters, registered scopes, active source ids, holder grammar) and goes through `mintLegacyToken`, so keys are born on the unified grant columns; omitted fields take the `gbrain auth create` defaults (scopes `read,write`, never `admin` unless listed; no source grant; holders `['world']`), reported in `defaults_applied` beside the effective grant. Refusals are `invalid_params` agent envelopes with `why` and a `fix`; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders through `grantFromTokenRow`; revoke takes the row id (`revokeLegacyTokenById`) and refuses a name. Pinned by `test/serve-http-api-keys.test.ts`.@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.-- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).+- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and reads the token's source, operation and takes-holder grant through `resolveTokenGrant` (`src/core/grants/legacy-token.ts`, shared with the legacy HTTP transport so the two transports cannot drift; a legacy-shape row converts to the grant columns on that read; `[]` takes-holders preserved as explicit deny-all, NULL → the `/mcp` dispatch site's fail-closed `['world']`). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).- `src/core/remote-body.ts` — linear protected-body sanitizer over the existing Facts parser/renderer. Processes every protected fence, retains only world Facts, removes all Takes and drops malformed protected sections. Chunk creation sanitizes full bodies before splitting. Page/history responses apply it whenever trust is not explicitly local, independently of page-visibility opt-outs and holder grants.diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex acd31d9b7c..39b151290d 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -314,37 +314,44 @@ from `gbrain auth list`. The older commands stay as aliases:`auth rescope --client`, and `gbrain auth permissions <name>set-takes-holders <list>` is `auth rescope --token <name> --takes-holders <list>`.-### One grant shape and the lazy migration+### One grant shapeTokens store their grant in the same columns as OAuth clients(`access_tokens.source_grant`, `source_id`, `federated_read`,`allowed_operations`, `takes_holders`, `grant_revision`). `source_grant` is-`default`, `scalar`, `federated` or `none`; NULL means the token still uses the-older `permissions` JSON shape. Those tokens keep working unchanged and are not-re-issued: the next `auth rescope` edit, every `auth create` and every harness-rotation write the columns, bump `grant_revision`, and rewrite `permissions` as-a mirror (other keys preserved) so older gbrain binaries enforce the same-grant. To migrate every remaining token at once, without changing any grant:+`default`, `scalar`, `federated` or `none`. Authorization reads these columns.+Every grant write also rewrites `permissions` as a mirror (other keys+preserved) so older gbrain binaries enforce the same grant; the mirror is kept+until the end date `gbrain doctor` reports (`details.mirror_window_ends`).++The schema migration that ships with this release converts every active+token still on the older `permissions`-only shape (`source_grant` NULL) in one+pass without changing any grant, and prints how many it converted. A token+an older binary creates afterwards converts on its first request (on a+read-only database role it is authorized with the identical grant and+converts later). To convert any remaining tokens now:```bashgbrain auth rescope --migrate-legacy --dry-run # listgbrain auth rescope --migrate-legacy```-A token whose `permissions` value is not a JSON object is skipped: the HTTP-paths read it as no grant while publication denies it, so there is no faithful-column form. Ask the user which grant it should hold, then run-`gbrain auth rescope --id <id>` with explicit `--sources`, `--takes-holders`-and `--operations` (or `--reset-default sources,takes-holders,operations`).-`gbrain doctor` reports the count as `legacy_token_grant_shape`-(`details.legacy_shape_count`, `details.malformed`).+A token whose `permissions` value is not a JSON object has no faithful+grant, so it is never converted and every request it makes is refused.+`gbrain doctor` warns `legacy_token_grant_shape` with the count+(`details.legacy_shape_count`, `details.convertible_count`) and, per malformed+token, the command that gives it the `auth create` default grant+(`details.malformed: [{name, id, argv}]`). Ask the user which grant it should+hold first, then run that command or `gbrain auth rescope --id <id>` with+explicit `--sources`, `--takes-holders` and `--operations`.### Grant driftIf an older gbrain binary edits a migrated token's `permissions` JSON (for-example its `auth rescope-token`), the JSON and the columns disagree. Each-axis that disagrees (`sources`, `takes-holders`, `operations`) denies every-request until resolved, and grant edits on that token refuse. `gbrain doctor`+example its `auth rescope-token`), the JSON and the columns disagree. While+the mirror is kept, each axis that disagrees (`sources`, `takes-holders`,+`operations`) denies every request until resolved, and grant edits on that+token refuse; the columns are never widened from the JSON. `gbrain doctor`warns `legacy_token_grant_drift` (`details.drift: [{name, id, axes}]`). Ask theuser which grant is intended, then run one of:diff --git a/src/commands/doctor/checks/legacy-token-grants.ts b/src/commands/doctor/checks/legacy-token-grants.tsindex 99f64d1793..9a0416f8ed 100644--- a/src/commands/doctor/checks/legacy-token-grants.ts+++ b/src/commands/doctor/checks/legacy-token-grants.ts@@ -1,10 +1,12 @@/*** F3 legacy token grants (O-CEO-8, O-DX-9).*- * `legacy_token_grant_shape` (informational, status ok): active tokens still- * on the JSONB-only grant shape. They keep working; the next grant edit- * migrates each one, or `gbrain auth rescope --migrate-legacy` writes the- * columns for all of them without changing any grant.+ * `legacy_token_grant_shape` (warn when non-zero): active tokens still on+ * the JSONB-only grant shape. Schema migration v201 converts every+ * well-formed one; an older binary's `auth create` can add more, which+ * convert on their next authorization read or with+ * `gbrain auth rescope --migrate-legacy`. A malformed one denies every axis+ * until the user picks its grant. Reports the grant-mirror window end date.** `legacy_token_grant_drift` (warn): migrated tokens whose `permissions`* mirror disagrees with the grant columns (an older gbrain edited the JSONB).@@ -16,7 +18,7 @@* check's `fix` asks the user before narrowing the first one.*/import type { Action } from '../../../core/agent-output.ts';-import { grantFromTokenRow, type LegacyGrantAxis } from '../../../core/grants/model.ts';+import { GRANT_MIRROR_WINDOW_ENDS, grantFromTokenRow, type LegacyGrantAxis } from '../../../core/grants/model.ts';import type { Check } from '../../doctor.ts';import { doctorVerify } from '../check-fix.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -38,17 +40,28 @@ async function runLegacyTokenGrants(ctx: DoctorContext): Promise<Check[]> {if (grant.shape === 'legacy_permissions') legacy.push({ ...entry, malformed: grant.permissionsMalformed });if (grant.drift.length) drift.push({ ...entry, axes: grant.drift });}- const malformed = legacy.filter(t => t.malformed);+ const malformed = legacy.filter(t => t.malformed).map(({ name, id }) => ({ name, id,+ argv: ['gbrain', 'auth', 'rescope', '--id', id, '--reset-default', 'sources,takes-holders,operations'] }));+ const convertible = legacy.length - malformed.length;+ const shapeFix: Action | undefined = convertible > 0+ ? { argv: ['gbrain', 'auth', 'rescope', '--migrate-legacy'], consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS,+ verify: doctorVerify('legacy_token_grant_shape'), why: 'Writes the unified grant columns for every legacy-shape token without changing any grant.' }+ : malformed[0] && { argv: malformed[0].argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, docs: DOCS,+ verify: doctorVerify('legacy_token_grant_shape'),+ why: 'A token whose permissions value is not a JSON object has no faithful grant, so it denies every request until it is given one.',+ user_message: `${malformed.length} API key(s) (first: ${malformed[0].name}) have unreadable permissions and are refused everywhere. `+ + 'Give each the default grant (no source grant, holders world, every operation its scopes allow), or name the sources, holders and operations it should hold?' };checks.push({name: 'legacy_token_grant_shape',- status: 'ok',- message: legacy.length === 0+ status: legacy.length ? 'warn' : 'ok',+ message: (legacy.length === 0? 'Every active legacy token uses the unified grant columns.'- : `${legacy.length} active legacy token(s) still use the permissions-JSON grant shape; they keep working. `- + 'Write the unified columns without changing any grant: gbrain auth rescope --migrate-legacy (preview with --dry-run; no user decision needed).'- + (malformed.length ? ` ${malformed.length} have malformed permissions and will be skipped; ask the user which grant each should hold, then run gbrain auth rescope --id <id> with explicit --sources/--takes-holders/--operations (ids in details.malformed).` : '')- + ` See ${DOCS}.`,- details: { legacy_shape_count: legacy.length, malformed: malformed.map(({ name, id }) => ({ name, id })), docs: DOCS },+ : (convertible ? `${convertible} active legacy token(s) still use the permissions-JSON grant shape (an older gbrain created them); each converts on its next request, or now with gbrain auth rescope --migrate-legacy (no grant changes, no user decision needed). ` : '')+ + (malformed.length ? `${malformed.length} have malformed permissions and deny every request; ask the user which grant each should hold, then run the command in details.malformed (or gbrain auth rescope --id <id> with explicit --sources/--takes-holders/--operations). ` : '')+ + `See ${DOCS}.`)+ + ` The permissions mirror for older gbrain binaries is kept until ${GRANT_MIRROR_WINDOW_ENDS}.`,+ details: { legacy_shape_count: legacy.length, convertible_count: convertible, malformed, mirror_window_ends: GRANT_MIRROR_WINDOW_ENDS, docs: DOCS },+ ...(shapeFix ? { fix: shapeFix } : {}),});checks.push({name: 'legacy_token_grant_drift',@@ -58,8 +71,8 @@ async function runLegacyTokenGrants(ctx: DoctorContext): Promise<Check[]> {: `${drift.length} legacy token(s) have grant drift: an older gbrain edited the permissions JSON after migration, so the drifted axes deny every request (fail-closed). `+ 'Ask the user which grant is intended, then for each token run gbrain auth rescope --token <name> --adopt-permissions (keep the JSON edit) or --adopt-columns (restore the columns): '+ drift.slice(0, 5).map(t => `${t.name} (${t.axes.join(', ')}): gbrain auth rescope --token ${t.name} --adopt-permissions|--adopt-columns`).join('; ')- + `${drift.length > 5 ? `; and ${drift.length - 5} more in details.drift` : ''}. See ${DOCS}.`,- details: { drift, docs: DOCS },+ + `${drift.length > 5 ? `; and ${drift.length - 5} more in details.drift` : ''}. Drift is enforced while the mirror is kept (until ${GRANT_MIRROR_WINDOW_ENDS}). See ${DOCS}.`,+ details: { drift, mirror_window_ends: GRANT_MIRROR_WINDOW_ENDS, docs: DOCS },});const first = nullScope[0];const fix: Action | undefined = first && {diff --git a/src/core/grants/access-token-schema.ts b/src/core/grants/access-token-schema.tsindex 2ee074d34e..ca86f65d13 100644--- a/src/core/grants/access-token-schema.ts+++ b/src/core/grants/access-token-schema.ts@@ -1,9 +1,9 @@/*** F3 (O-CEO-8, O-ENG-7): legacy bearer tokens get the OAuth client grant* columns. `source_grant` names the source state explicitly; NULL means the- * row still uses the `permissions` JSONB shape and is read through the lane F- * parsers until its next write (`auth rescope`, `auth create`, rotation, or- * `auth rescope --migrate-legacy`). No foreign key on `source_id`: the client+ * row still uses the `permissions` JSONB shape: migration v201 converts every+ * such active row, and one an older binary adds converts on its next HTTP+ * read (`resolveTokenGrant`), grant write, or `auth rescope --migrate-legacy`. No foreign key on `source_id`: the client* FK is ON DELETE RESTRICT, and tokens must not start blocking source removal.** Migration-only, like `permissions` (v038): the schema blob's access_tokensdiff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.tsindex 6cabbaf834..d49466c84a 100644--- a/src/core/grants/legacy-token.ts+++ b/src/core/grants/legacy-token.ts@@ -18,14 +18,15 @@* `source_id`, `federated_read`, `allowed_operations`, `takes_holders`), bumps* `grant_revision`, and rewrites `permissions` as a mirror with every other key* preserved, so older binaries enforce the same grant. Rows still on the- * JSONB-only shape migrate lazily on their first write, or in bulk with- * `--migrate-legacy`. A drifted row (JSONB edited by an older binary) refuses- * grant edits until `--adopt-permissions` or `--adopt-columns` resolves it.+ * JSONB-only shape convert in bulk (migration v201, `--migrate-legacy`), on+ * their first HTTP read (`resolveTokenGrant`) or on their first write. A+ * drifted row (JSONB edited by an older binary) refuses grant edits until+ * `--adopt-permissions` or `--adopt-columns` resolves it.*/import type { BrainEngine } from '../engine.ts';import { assertAllowedScopes, operationScopesAllowed } from '../scope.ts';import { isValidSourceId } from '../source-id.ts';-import { executeRawJsonb } from '../sql-query.ts';+import { executeRawJsonb, type SqlQuery } from '../sql-query.ts';import { TOKEN_ID_RE } from '../token-mint.ts';import { isUndefinedColumnError } from '../utils.ts';import {@@ -324,6 +325,36 @@ export async function migrateLegacyTokens(engine: BrainEngine, opts: { dryRun: b}}+/**+ * The authorization read of an active token row on the HTTP auth paths. A+ * unified row is read from its columns. A row still on the legacy shape+ * (created by an older binary after the bulk migration, or on a brain whose+ * migration has not run) is converted on this read: one guarded UPDATE writes+ * the columns `migrateLegacyTokens` would write and leaves `permissions` as+ * the mirror it already is. The guard (`source_grant IS NULL`) makes+ * concurrent first reads a no-op for the loser, and a failed write (a+ * read-only role, a lost race, a schema without the columns) falls back to+ * the same grant computed in memory. A malformed row is never converted; it+ * stays deny-all.+ */+export async function resolveTokenGrant(sql: SqlQuery, row: Record<string, unknown>): Promise<PrincipalGrant> {+ const grant = grantFromTokenRow(row);+ if (grant.shape !== 'legacy_permissions' || grant.permissionsMalformed || !('source_grant' in row)) return grant;+ const [kind, write, reads, ops, holders] = tokenGrantColumnValues(grant);+ try {+ const [converted] = await sql`+ UPDATE access_tokens SET source_grant = ${kind}, source_id = ${write}, federated_read = ${reads}::text[],+ allowed_operations = ${ops}::text[], takes_holders = ${holders}::text[], grant_revision = grant_revision + 1+ WHERE id = ${String(row.id)}::uuid AND source_grant IS NULL+ RETURNING *+ `;+ if (converted) return grantFromTokenRow(converted);+ } catch {+ // Read-only role or transient failure: authorize with the identical in-memory conversion.+ }+ return grant;+}+/** A bare `auth rescope <name>`: a token name, an OAuth client id, or a client name. Both kinds matching refuses. */export async function resolveRescopeTarget(engine: BrainEngine, name: string): Promise<{ kind: 'token' } | { kind: 'client'; clientId: string }> {const tokens = await engine.executeRaw<{ id: string }>('SELECT id FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);diff --git a/src/core/grants/model.ts b/src/core/grants/model.tsindex 21e17c5340..01a233a4f4 100644--- a/src/core/grants/model.ts+++ b/src/core/grants/model.ts@@ -162,12 +162,23 @@ export interface PrincipalGrant {*/drift: LegacyGrantAxis[];/**- * Legacy rows only: `permissions` is present but not a JSON object. The HTTP- * auth paths read it as no grant; publication and job admission deny it.+ * Legacy rows only: `permissions` is present but not a JSON object. It has+ * no column equivalent, so every axis of the grant is deny-all until an+ * operator gives the token an explicit grant (`auth rescope --id`).*/permissionsMalformed: boolean;}+/**+ * Tokens keep a `permissions` JSONB mirror of their grant columns so gbrain+ * binaries older than the unified grant shape enforce the same grant. Until+ * this date (30 days after the release that converted every legacy grant in+ * bulk) the mirror is written on every grant write and drift between it and+ * the columns denies the drifted axis; doctor reports the date. Authorization+ * reads the columns; the mirror is only compared, never granted from.+ */+export const GRANT_MIRROR_WINDOW_ENDS = '2026-11-04';+type TokenGrantAxes = Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>;/** The grant a `permissions` JSONB value carries, read with lane F's parsers. */@@ -226,9 +237,12 @@ function sameAxis(axis: LegacyGrantAxis, a: TokenGrantAxes, b: TokenGrantAxes):/*** The effective grant of an `access_tokens` row (SELECT * keeps this working- * on brains that predate the columns). `source_grant IS NULL` rows are read- * through lane F's JSONB parsers unchanged; unified rows read the columns,- * and any axis whose JSONB mirror disagrees evaluates deny-all.+ * on brains that predate the columns). Unified rows read the columns, and any+ * axis whose JSONB mirror disagrees evaluates deny-all. A `source_grant IS+ * NULL` row has not been converted yet (the bulk migration converts every+ * active one; an older binary's `auth create` can still add one): it reads as+ * the conversion `migrateLegacyTokens` would write, and a malformed+ * `permissions` value denies every axis.*/export function grantFromTokenRow(row: Record<string, unknown>): PrincipalGrant {const base = {@@ -237,7 +251,10 @@ export function grantFromTokenRow(row: Record<string, unknown>): PrincipalGrantrevision: Number(row.grant_revision ?? 0),};const { malformed, ...legacy } = tokenGrantFromPermissions(row.permissions);- if (row.source_grant == null) return { ...base, ...legacy, shape: 'legacy_permissions', drift: [], permissionsMalformed: malformed };+ if (row.source_grant == null) {+ const axes: TokenGrantAxes = malformed ? { sources: { kind: 'none' }, allowedOperations: [], takesHolders: [] } : legacy;+ return { ...base, ...axes, shape: 'legacy_permissions', drift: [], permissionsMalformed: malformed };+ }const columns = tokenGrantFromColumns(row);const drift = LEGACY_GRANT_AXES.filter(axis => malformed || !sameAxis(axis, columns, legacy));return {diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex 673fb3c004..64a0bdc121 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -37,10 +37,11 @@ import {dcrScopeViolation,} from './scope.ts';import type { AuthInfo as CoreAuthInfo } from './operations.ts';-import { authSourcesFromGrant, grantFromRow, grantFromTokenRow, normalizeGrantBrain, intersectGrantedScopes, type GrantPatch } from './grants/model.ts';+import { authSourcesFromGrant, grantFromRow, normalizeGrantBrain, intersectGrantedScopes, type GrantPatch } from './grants/model.ts';import { assertValidSlugPrefixes, pgArray } from './grants/encoding.ts';import { rescopeOAuthClient, type RescopeClientOptions, type RescopeClientResult } from './grants/rescope.ts';import { grantValidationContext, validateClientGrant, insertClientGrant, assertGrantPatch } from './grants/service.ts';+import { resolveTokenGrant } from './grants/legacy-token.ts';/*** A slug-prefix write binding is only meaningful if every entry actually@@ -913,13 +914,14 @@ export class GBrainOAuthProvider implements OAuthServerProvider {AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`.catch(() => { /* fire-and-forget */ });const name = legacyRows[0].name as string;- // F3: one grant shape (grants/model.ts), shared with the legacy HTTP- // transport so the two cannot drift. Unmigrated rows read through lane- // F's JSONB parsers; unified rows read the columns, fail-closed on drift.- // Scopes: NULL (every token minted before #4043) is grandfathered full- // access; an array is honored as-is, including [] as deny. Takes holders- // null → the /mcp dispatch site defaults to the fail-closed ['world'].- const grant = grantFromTokenRow(legacyRows[0]);+ // One grant shape (grants/model.ts), shared with the legacy HTTP+ // transport so the two cannot drift. Unified rows read the columns,+ // fail-closed on drift; a row still on the legacy shape is converted on+ // this read (resolveTokenGrant). Scopes: NULL (every token minted before+ // #4043) is grandfathered full access; an array is honored as-is,+ // including [] as deny. Takes holders null → the /mcp dispatch site+ // defaults to the fail-closed ['world'].+ const grant = await resolveTokenGrant(this.sql, legacyRows[0]);return {token,clientId: name,diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 16ef4d9ecc..a98ead8498 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -201,6 +201,7 @@ import { v197 } from './v197-managed-guard-null-source-fallback.ts';import { v198 } from './v198-publication-failure-detail.ts';import { v199 } from './v199-chronicle-page-state.ts';import { v200 } from './v200-sync-hold-page-index.ts';+import { v201 } from './v201-lane-e-legacy-token-grant-conversion.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -400,4 +401,5 @@ export const MIGRATIONS: Migration[] = [v198,v199,v200,+ v201,];diff --git a/src/core/schema-migrations/v201-lane-e-legacy-token-grant-conversion.ts b/src/core/schema-migrations/v201-lane-e-legacy-token-grant-conversion.tsnew file mode 100644index 0000000000..5ffb0ffa86--- /dev/null+++ b/src/core/schema-migrations/v201-lane-e-legacy-token-grant-conversion.ts@@ -0,0 +1,30 @@+import { migrateLegacyTokens } from '../grants/legacy-token.ts';+import { migrationNotice } from './helpers.ts';+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Converts every active legacy bearer token still on the JSONB-only grant+// shape (`source_grant IS NULL`) to the unified grant columns in one+// transaction, through the same `migrateLegacyTokens` that+// `gbrain auth rescope --migrate-legacy` runs: no effective grant changes and+// `permissions` stays as the mirror older binaries read. A malformed+// `permissions` value has no faithful column form, so it stays on the legacy+// shape and denies every axis; doctor `legacy_token_grant_shape` lists it.+// Handler-only and rerun-safe (a second run finds no unconverted rows).+export const v201: Migration = {+ version: 201,+ name: 'lane_e_legacy_token_grant_conversion',+ idempotent: true,+ sql: '',+ handler: async engine => {+ const result = await migrateLegacyTokens(engine, { dryRun: false });+ if (result.migrated.length === 0 && result.skipped.length === 0) return;+ migrationNotice(` v201: converted ${result.migrated.length} legacy token grant(s) to the unified grant columns; no grant changed.`+ + (result.skipped.length+ ? ` ${result.skipped.length} token(s) with malformed permissions stay denied; run gbrain doctor --only legacy_token_grant_shape --json for each fix.`+ : '')+ + '\n');+ },+};diff --git a/src/core/token-mint.ts b/src/core/token-mint.tsindex bf133e9266..d1b1f4de08 100644--- a/src/core/token-mint.ts+++ b/src/core/token-mint.ts@@ -18,7 +18,8 @@import type { BrainEngine } from './engine.ts';import { ALLOWED_SCOPES_LIST, assertAllowedScopes } from './scope.ts';-import { executeRawJsonb, type SqlQuery } from './sql-query.ts';+import type { SqlQuery } from './sql-query.ts';+import { opError } from './ops/contract.ts';import { generateToken, hashToken, isUndefinedColumnError } from './utils.ts';import { permissionsMirror, tokenGrantColumnValues, tokenGrantFromPermissions, TOKEN_GRANT_COLUMNS, type GrantSources, type PrincipalGrant } from './grants/model.ts';@@ -88,49 +89,37 @@ export async function mintLegacyToken(}/**- * F3: insert a token born on the unified grant shape: the grant columns at- * revision 1 plus the `permissions` JSONB mirror older binaries read. On a- * brain whose schema predates the columns the same grant is written as the- * JSONB-only legacy shape (read identically, migrated on its next write), so- * minting never depends on migration order. Scopes bind as a Postgres array- * literal through a TEXT param + ::text[] (values are allowlisted); omitted- * scopes stay NULL (grandfathered full access). JSONB goes through- * executeRawJsonb per the repo invariant. Not for use inside a transaction:- * the fallback retries after a failed statement.+ * Insert a token born on the unified grant shape: the grant columns at+ * revision 1 plus the `permissions` JSONB mirror older binaries read+ * (`GRANT_MIRROR_WINDOW_ENDS`). A brain whose schema predates the columns+ * refuses with `migrations_pending` instead of writing a JSONB-only grant.+ * Scopes bind as a Postgres array literal through a TEXT param + ::text[]+ * (values are allowlisted); omitted scopes stay NULL (grandfathered full+ * access). The JSONB object binds as a raw object, exactly as executeRawJsonb+ * binds it (no double-encode).*/export async function insertUnifiedToken(engine: BrainEngine, opts: {name: string; tokenHash: string; scopes?: string[];grant: Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>;}): Promise<Array<{ id: string }>> {const scopes = opts.scopes === undefined ? null : `{${opts.scopes.join(',')}}`;- const permissions = permissionsMirror(opts.grant, {});try {- try {- // The JSONB object binds at $4 as a raw object, exactly as executeRawJsonb- // binds it (no double-encode); the scalar grant columns follow it.- return await engine.executeRaw<{ id: string }>(- `INSERT INTO access_tokens (name, token_hash, scopes, permissions, ${TOKEN_GRANT_COLUMNS.join(', ')}, grant_revision)- VALUES ($1, $2, $3::text[], $4::jsonb, $5, $6, $7::text[], $8::text[], $9::text[], 1)- RETURNING id`,- [opts.name, opts.tokenHash, scopes, permissions, ...tokenGrantColumnValues(opts.grant)],- );- } catch (e) {- if (!['source_grant', 'grant_revision', ...TOKEN_GRANT_COLUMNS].some(column => isUndefinedColumnError(e, column))) throw e;- return await executeRawJsonb<{ id: string }>(- engine,- 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id',- [opts.name, opts.tokenHash, scopes],- [permissions],- );- }+ return await engine.executeRaw<{ id: string }>(+ `INSERT INTO access_tokens (name, token_hash, scopes, permissions, ${TOKEN_GRANT_COLUMNS.join(', ')}, grant_revision)+ VALUES ($1, $2, $3::text[], $4::jsonb, $5, $6, $7::text[], $8::text[], $9::text[], 1)+ RETURNING id`,+ [opts.name, opts.tokenHash, scopes, permissionsMirror(opts.grant, {}), ...tokenGrantColumnValues(opts.grant)],+ );} catch (e) {- // isUndefinedColumnError also matches message-shaped variants — some+ // isUndefinedColumnError also matches message-shaped variants: some// driver-wrapped errors drop the SQLSTATE code.- if (isUndefinedColumnError(e, 'scopes') || isUndefinedColumnError(e, 'permissions')) {- throw new Error(- 'this brain is missing token columns (undefined column on access_tokens) — ' +- 'run `gbrain apply-migrations` and retry.',- );+ if (['scopes', 'permissions', 'grant_revision', ...TOKEN_GRANT_COLUMNS].some(column => isUndefinedColumnError(e, column))) {+ throw opError('migrations_pending',+ 'This brain is missing the access-token grant columns, so it cannot mint a token.',+ 'Apply the pending schema migrations on the brain host, then mint the token again.',+ { why: 'Tokens are born on the unified grant columns; a brain whose schema predates them has not run its migrations.',+ fix: { argv: ['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'], consent: [], actor: 'agent', requires_exclusive: true,+ why: 'Applies the pending schema migrations, including the token grant columns; no user decision needed.', verify: { argv: ['gbrain', 'doctor', '--json'] } } });}throw e;}diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 7946bd7b99..36bbeeaf8e 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -52,7 +52,8 @@ import { degradedLastError, isEngineDegraded } from '../core/degraded-marker.ts'import { classifyPgAccessError } from '../core/pg-access-classify.ts';import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';import { redactUrlsInText } from '../core/url-redact.ts';-import { authSourcesFromGrant, grantFromTokenRow } from '../core/grants/model.ts';+import { authSourcesFromGrant } from '../core/grants/model.ts';+import { resolveTokenGrant } from '../core/grants/legacy-token.ts';export { parseLegacyTokenScope } from '../core/legacy-token-scope.ts';const DEFAULT_BODY_CAP = 1024 * 1024; // 1 MiB@@ -271,10 +272,11 @@ export async function startHttpTransport(opts: HttpTransportOptions) {WHERE id IN (SELECT id FROM access_tokens WHERE id = ${rowId}AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`.catch(() => { /* fire-and-forget */ });- // F3: one grant shape (grants/model.ts) shared with the OAuth provider- // behind `serve --http`, so the two transports cannot drift. Takes- // holders fail safe to ['world']; #1336 honors the stored source grant.- const grant = grantFromTokenRow(row);+ // One grant shape (grants/model.ts) shared with the OAuth provider+ // behind `serve --http`, so the two transports cannot drift; a row still+ // on the legacy shape is converted on this read. Takes holders fail safe+ // to ['world']; #1336 honors the stored source grant.+ const grant = await resolveTokenGrant(sql, row);const allowList = grant.takesHolders ?? ['world'];const { sourceId, allowedSources, hasSourceGrant } = authSourcesFromGrant(grant);const auth: AuthInfo = {diff --git a/test/access-token-grants.test.ts b/test/access-token-grants.test.tsindex b7b58d612c..746244e884 100644--- a/test/access-token-grants.test.ts+++ b/test/access-token-grants.test.ts@@ -4,8 +4,9 @@* columns, with a JSONB mirror and fail-closed drift.** Protects (spec 4.5): a pre-F3 token authenticates identically on both HTTP- * paths (2); the unified reader equals lane F's parsers for any stored JSONB,- * before and after migration (3); `--sources none` after lazy migration denies+ * paths and its first read converts the row to the columns (2); the unified+ * reader equals lane F's parsers for any well-formed stored JSONB, before and+ * after migration, and a malformed one denies every axis (3); `--sources none` after lazy migration denies* reads, writes and publication (4); a rescope writes the columns, bumps the* revision and leaves the JSONB lane F would have written (5); an older* binary's JSONB edit makes that axis deny until an adopt flag resolves it (6);@@ -84,7 +85,7 @@ function grantFields(row: Record<string, unknown>) {}describe('2. a pre-F3 token authenticates identically on both HTTP paths', () => {- test('oauth-provider fallback and the legacy HTTP transport derive the same grant; reads never migrate', async () => {+ test('oauth-provider fallback and the legacy HTTP transport derive the same grant; the first read converts the row', async () => {const t = await legacyToken({ takes_holders: ['world', 'brain'], source_id: ['default', 'other'], allowed_operations: ['get_page', 'search', 'query'] });const oauth = await provider().verifyAccessToken(t.token) as unknown as AuthInfo;expect(oauth).toMatchObject({ scopes: ['read', 'write'], sourceId: 'default', allowedSources: ['default', 'other'], hasSourceGrant: true,@@ -100,7 +101,13 @@ describe('2. a pre-F3 token authenticates identically on both HTTP paths', () =>const pick = (c: Record<string, unknown>) => ({ scopes: c.scopes, source_id: c.source_id, federated_read: c.federated_read, allowed_operations: c.allowed_operations });expect(pick(http)).toEqual(pick(describeAuthCapabilities(oauth)));} finally { server.stop?.(true); }- expect((await rowOf(t.id)).source_grant).toBeNull();+ const row = await rowOf(t.id);+ expect(row).toMatchObject({ source_grant: 'federated', source_id: 'default', federated_read: ['default', 'other'],+ allowed_operations: ['get_page', 'search', 'query'], takes_holders: ['world', 'brain'], grant_revision: 1 });+ expect(grantFromTokenRow(row)).toMatchObject({ shape: 'unified', drift: [] });+ const again = await provider().verifyAccessToken(t.token) as unknown as AuthInfo;+ expect({ ...again, expiresAt: 0 }).toEqual({ ...oauth, expiresAt: 0 });+ expect((await rowOf(t.id)).grant_revision).toBe(1);}, 60_000);});@@ -119,12 +126,17 @@ describe('3. equivalence: the unified reader equals lane F for any stored JSONB,const doubleEncoded = values.filter((_, i) => i % 7 === 0).map(v => JSON.stringify(v));const garbage = ['{not json', '[1,2]', '"world"'];- test('legacy rows: authSourcesFromGrant(grantFromTokenRow(row)) equals parseLegacyTokenScope for every value', () => {+ test('legacy rows: authSourcesFromGrant(grantFromTokenRow(row)) equals parseLegacyTokenScope for every value; malformed rows deny every axis', () => {for (const raw of [...values, ...doubleEncoded, ...garbage, [1], 42, null]) {const row = { id: randomUUID(), permissions: raw, scopes: null };const g = grantFromTokenRow(row);- expect({ raw, sources: authSourcesFromGrant(g) }).toEqual({ raw, sources: laneFSources(raw) });const permissions = coerceLegacyPermissions(raw);+ if (raw != null && permissions === undefined) {+ expect({ raw, malformed: g.permissionsMalformed, sources: authSourcesFromGrant(g), ops: g.allowedOperations, takes: g.takesHolders })+ .toEqual({ raw, malformed: true, sources: { sourceId: NO_SOURCES, allowedSources: [], hasSourceGrant: true }, ops: [], takes: [] });+ continue;+ }+ expect({ raw, sources: authSourcesFromGrant(g) }).toEqual({ raw, sources: laneFSources(raw) });expect({ raw, ops: g.allowedOperations, takes: g.takesHolders }).toEqual({ raw,ops: parseLegacyOperationGrant(permissions?.allowed_operations) ?? null, takes: parseTakesHoldersAllowList(permissions?.takes_holders) ?? null });}@@ -150,7 +162,7 @@ describe('3. equivalence: the unified reader equals lane F for any stored JSONB,}, 120_000);});-describe('4. O-ENG-7 after lazy migration: --sources none denies reads, writes and publication', () => {+describe('4. O-ENG-7 after on-read conversion: --sources none denies reads, writes and publication', () => {test('a pre-F3 token rescoped to none keeps scopes and operations and is denied everywhere', async () => {const t = await legacyToken({ takes_holders: ['world'], allowed_operations: ['get_page', 'search', 'query', 'put_page'] });const before = await provider().verifyAccessToken(t.token) as unknown as AuthInfo;@@ -162,8 +174,9 @@ describe('4. O-ENG-7 after lazy migration: --sources none denies reads, writes asourceIncarnation: source.incarnation, slug: 'notes/f3', requestId: randomUUID(), callerIntent: {}, intent: {} });await authorizeStoredRequest(engine, admitted);+ expect((await rowOf(t.id)).source_grant).toBe('default');const result = await rescope(t.name, '--sources', 'none');- expect(result).toMatchObject({ migrated: true, written: true, shape: 'legacy_permissions' });+ expect(result).toMatchObject({ migrated: false, written: true, shape: 'unified' });const row = await rowOf(t.id);expect(row).toMatchObject({ source_grant: 'none', source_id: null, federated_read: [], allowed_operations: ['get_page', 'search', 'query', 'put_page'], scopes: ['read', 'write'] });await expect(authorizeStoredRequest(engine, admitted)).rejects.toMatchObject({ code: 'permission_denied' });diff --git a/test/e2e/access-token-grants.test.ts b/test/e2e/access-token-grants.test.tsindex 8d912faab0..602043201a 100644--- a/test/e2e/access-token-grants.test.ts+++ b/test/e2e/access-token-grants.test.ts@@ -16,6 +16,7 @@ import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';import { executeRawJsonb, sqlQueryForEngine } from '../../src/core/sql-query.ts';import { NO_SOURCES } from '../../src/core/source-id.ts';import { generateToken, hashToken } from '../../src/core/utils.ts';+import { runMigrations } from '../../src/core/migrate.ts';const d = hasDatabase() ? describe : describe.skip;@@ -31,6 +32,36 @@ const row = async (id: string) => (await getEngine().executeRaw<Record<string, u"SELECT *, jsonb_typeof(permissions) AS kind FROM access_tokens WHERE id = $1::uuid", [id]))[0];d('F3 token grant columns on Postgres', () => {+ test('the bulk grant migration converts legacy tokens with unchanged AuthInfo; concurrent first reads of a later one convert once', async () => {+ const engine = getEngine();+ const strip = (a: unknown) => ({ ...(a as Record<string, unknown>), expiresAt: 0 });+ const legacy = [];+ for (const permissions of [{ takes_holders: ['world', 'q"x'], source_id: ['other-f3', 'default'] }, { source_id: [], allowed_operations: [] }, { takes_holders: ['world'] }]) {+ const token = generateToken('gbrain_');+ const [inserted] = await executeRawJsonb<{ id: string }>(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id',+ [`lane-e-${randomUUID().slice(0, 8)}`, hashToken(token), '{read,write}'], [permissions]);+ legacy.push({ id: inserted.id, token, before: grantFromTokenRow(await row(inserted.id)) });+ }+ await engine.setConfig('version', '200');+ await runMigrations(engine);+ for (const t of legacy) {+ const after = await row(t.id);+ expect(after.source_grant).not.toBeNull();+ expect(after.kind).toBe('object');+ const { shape: _a, revision: _b, ...axes } = grantFromTokenRow(after);+ const { shape: _c, revision: _d, ...beforeAxes } = t.before;+ expect(axes).toEqual(beforeAxes);+ }++ const token = generateToken('gbrain_');+ const [late] = await executeRawJsonb<{ id: string }>(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id',+ [`lane-e-late-${randomUUID().slice(0, 8)}`, hashToken(token), '{read}'], [{ takes_holders: ['world'], source_id: 'other-f3' }]);+ const reads = await Promise.all(Array.from({ length: 8 }, () => provider().verifyAccessToken(token)));+ for (const r of reads) expect(strip(r)).toEqual(strip(reads[0]));+ expect(reads[0]).toMatchObject({ sourceId: 'other-f3', hasSourceGrant: true, scopes: ['read'] });+ expect(await row(late.id)).toMatchObject({ source_grant: 'scalar', source_id: 'other-f3', grant_revision: 1, kind: 'object' });+ });+test('mint and rescope write text[] columns with quoting intact and an object mirror', async () => {const engine = getEngine();const name = `f3-e2e-${randomUUID().slice(0, 8)}`;@@ -51,10 +82,13 @@ d('F3 token grant columns on Postgres', () => {const token = generateToken('gbrain_');const [inserted] = await executeRawJsonb<{ id: string }>(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id',[name, hashToken(token), '{read,write}'], [{ takes_holders: ['world', 'brain'], source_id: 'other-f3', allowed_operations: ['search', 'search'], note: 'kept' }]);- const before = await provider().verifyAccessToken(token);const preview = await migrateLegacyTokens(engine, { dryRun: true });expect(preview.migrated.map(m => m.id)).toContain(inserted.id);expect((await row(inserted.id)).source_grant).toBeNull();+ const readOnly = sqlQueryForEngine(engine);+ const before = await new GBrainOAuthProvider({ sql: (strings, ...values) => /^\s*UPDATE/i.test(strings[0]!) ? Promise.reject(new Error('read-only')) : readOnly(strings, ...values) })+ .verifyAccessToken(token);+ expect((await row(inserted.id)).source_grant).toBeNull();await migrateLegacyTokens(engine, { dryRun: false });const migrated = await row(inserted.id);expect(migrated).toMatchObject({ kind: 'object', source_grant: 'scalar', source_id: 'other-f3', federated_read: null, allowed_operations: ['search'], takes_holders: ['world', 'brain'] });diff --git a/test/e2e/serve-http-api-keys.test.ts b/test/e2e/serve-http-api-keys.test.tsnew file mode 100644index 0000000000..1153877d3e--- /dev/null+++ b/test/e2e/serve-http-api-keys.test.ts@@ -0,0 +1,60 @@+/**+ * Dashboard API keys on real Postgres: the scoped mint binds scopes and the+ * grant columns as text[] through postgres.js, the permissions mirror is a+ * JSONB object (double-encode class), the minted key authenticates with+ * exactly its grant, and revoke by id leaves a same-name sibling active.+ * PGLite coverage: test/serve-http-api-keys.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import express from 'express';+import type { Server } from 'node:http';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { mountAdminApiKeys } from '../../src/commands/serve-http-api-keys.ts';+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';++const d = hasDatabase() ? describe : describe.skip;+let server: Server | undefined;+let base = '';++beforeAll(async () => {+ if (!hasDatabase()) return;+ const engine = await setupDB();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('team-e2e','team-e2e') ON CONFLICT DO NOTHING");+ const app = express();+ mountAdminApiKeys(app, (_req, _res, next) => next(), engine);+ server = app.listen(0, '127.0.0.1');+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+});+afterAll(async () => {+ if (server) { server.closeAllConnections(); await new Promise<void>(r => server!.close(() => r())); }+ if (hasDatabase()) await teardownDB();+});++const post = async (path: string, body: unknown) => {+ const res = await fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ return { status: res.status, body: await res.json() as any };+};++d('dashboard API keys on Postgres', () => {+ test('scoped mint lands on text[] columns with an object mirror and authenticates with exactly its grant', async () => {+ const engine = getEngine();+ const { status, body } = await post('/admin/api/api-keys', { name: 'dash-e2e', sources: ['team-e2e'], takes_holders: ['world', 'people/alice-example'] });+ expect(status).toBe(200);+ expect(body).toMatchObject({ scopes_applied: ['read', 'write'], defaults_applied: ['scopes'] });+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT *, jsonb_typeof(permissions) AS kind FROM access_tokens WHERE id = $1::uuid', [body.id]);+ expect(row).toMatchObject({ kind: 'object', scopes: ['read', 'write'], source_grant: 'federated', source_id: 'team-e2e', federated_read: ['team-e2e'],+ takes_holders: ['world', 'people/alice-example'], grant_revision: 1 });+ const auth = await new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine) }).verifyAccessToken(body.token) as unknown as Record<string, unknown>;+ expect(auth).toMatchObject({ scopes: ['read', 'write'], sourceId: 'team-e2e', allowedSources: ['team-e2e'], takesHoldersAllowList: ['world', 'people/alice-example'] });+ });++ test('revoke by id leaves the same-name sibling active', async () => {+ const engine = getEngine();+ const a = (await post('/admin/api/api-keys', { name: 'dash-e2e-twin', scopes: ['read'] })).body;+ const b = (await post('/admin/api/api-keys', { name: 'dash-e2e-twin', scopes: ['read'] })).body;+ expect((await post('/admin/api/api-keys/revoke', { id: a.id })).body).toEqual({ id: a.id, revoked: true });+ const rows = await engine.executeRaw<{ id: string; revoked: boolean }>('SELECT id, revoked_at IS NOT NULL AS revoked FROM access_tokens WHERE id = ANY($1::uuid[])', [[a.id, b.id]]);+ expect(Object.fromEntries(rows.map(r => [r.id, r.revoked]))).toEqual({ [a.id]: true, [b.id]: false });+ });+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 51c163a8b8..ced7a2221d 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -507,7 +507,7 @@},{"category": "meta",- "message": "Version 200 (latest: 200)",+ "message": "Version 201 (latest: 201)","name": "schema_version","status": "ok"},@@ -1097,11 +1097,13 @@{"category": "ops","details": {+ "convertible_count": 0,"docs": "docs/mcp/ADMIN.md#legacy-token-grants","legacy_shape_count": 0,- "malformed": []+ "malformed": [],+ "mirror_window_ends": "2026-11-04"},- "message": "Every active legacy token uses the unified grant columns.",+ "message": "Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.","name": "legacy_token_grant_shape","status": "ok"},@@ -1109,7 +1111,8 @@"category": "ops","details": {"docs": "docs/mcp/ADMIN.md#legacy-token-grants",- "drift": []+ "drift": [],+ "mirror_window_ends": "2026-11-04"},"message": "No legacy token grant has drifted from its permissions mirror.","name": "legacy_token_grant_drift",@@ -1118,7 +1121,7 @@{"category": "ops","details": {- "docs": "docs/mcp/ADMIN.md#legacy-token-grants",+ "docs": "docs/mcp/ADMIN.md#tokens-without-scopes","null_scope_count": 0,"tokens": []},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 38e1bf0ad0..2c8c7f875d 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -510,7 +510,7 @@},{"category": "meta",- "message": "Version 200 (latest: 200)",+ "message": "Version 201 (latest: 201)","name": "schema_version","status": "ok"},@@ -1185,11 +1185,13 @@{"category": "ops","details": {+ "convertible_count": 0,"docs": "docs/mcp/ADMIN.md#legacy-token-grants","legacy_shape_count": 0,- "malformed": []+ "malformed": [],+ "mirror_window_ends": "2026-11-04"},- "message": "Every active legacy token uses the unified grant columns.",+ "message": "Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.","name": "legacy_token_grant_shape","status": "ok"},@@ -1197,7 +1199,8 @@"category": "ops","details": {"docs": "docs/mcp/ADMIN.md#legacy-token-grants",- "drift": []+ "drift": [],+ "mirror_window_ends": "2026-11-04"},"message": "No legacy token grant has drifted from its permissions mirror.","name": "legacy_token_grant_drift",@@ -1206,7 +1209,7 @@{"category": "ops","details": {- "docs": "docs/mcp/ADMIN.md#legacy-token-grants",+ "docs": "docs/mcp/ADMIN.md#tokens-without-scopes","null_scope_count": 0,"tokens": []},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 190c942fa0..412243d008 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 195,+ "count": 196,"gaps": [17,18,@@ -19,6 +19,7 @@"getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26","migrateConnectorCheckpoints": "e0403022a56559556c82a9fa1e90d928f36e1d09c7db570e1d788a87d2dc9521",+ "migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c","migrationNotice": "9a6607b26a9719ef1833571b137bc8ebfcd1e16d545e89ff8728cf3ccbcbb409","quietMigrationNotices": "4045c32034a8f46204dd5d89e185ff5c35e8073f560f14caa8b127f8a695957c","readExistingEmbeddingShape": "16d92d7cd52d8ebd7e89982f02e1bbdd8e8d08a6712a4ce57fbcf0952b7a6ca5",@@ -28,7 +29,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 200,+ "latest": 201,"records": [{"handler": {@@ -2968,6 +2969,27 @@"transaction": "absent","verify": "absent","version": 200+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "migrateLegacyTokens",+ "migrationNotice",+ "quietMigrationNotices"+ ],+ "sha256": "9e006bf39cb44a27f8d4ad4323fd76873961d0b8669b835257a8764fb1543e28"+ },+ "idempotent": true,+ "name": "lane_e_legacy_token_grant_conversion",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 201}],"versions": [@@ -3165,7 +3187,8 @@197,198,199,- 200+ 200,+ 201]},"normalizer": "migrations-record-v1"diff --git a/test/legacy-token-grant-conversion.test.ts b/test/legacy-token-grant-conversion.test.tsnew file mode 100644index 0000000000..17d41e140a--- /dev/null+++ b/test/legacy-token-grant-conversion.test.ts@@ -0,0 +1,154 @@+/**+ * Lane E grants end state: authorization reads the unified grant columns.+ *+ * Protects: the schema migration converts every well-formed legacy token in+ * bulk with the same effective grant (AuthInfo) before and after, leaves a+ * malformed one denied and listed by doctor, and a rerun changes nothing; a+ * token an older binary creates after the migration converts on its first+ * HTTP read; concurrent first reads convert exactly once; a read-only+ * database still authorizes with the identical grant; a malformed token is+ * denied on the HTTP path; minting never writes a JSONB-only grant; doctor+ * reports the grant-mirror window end date.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine, executeRawJsonb, type SqlQuery } from '../src/core/sql-query.ts';+import { GRANT_MIRROR_WINDOW_ENDS, grantFromTokenRow } from '../src/core/grants/model.ts';+import { generateToken, hashToken } from '../src/core/utils.ts';+import { runMigrations } from '../src/core/migrate.ts';+import { NO_SOURCES } from '../src/core/source-id.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { legacyTokenGrantsEntry } from '../src/commands/doctor/checks/legacy-token-grants.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other','other') ON CONFLICT DO NOTHING");+}, 120_000);++afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+});++const provider = (sql: SqlQuery = sqlQueryForEngine(engine)) => new GBrainOAuthProvider({ sql, transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+const rowOf = async (id: string) => (await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id = $1::uuid', [id]))[0];+const verify = async (token: string, sql?: SqlQuery) => ({ ...(await provider(sql).verifyAccessToken(token) as unknown as AuthInfo), expiresAt: 0 });++/** A token exactly as an older binary writes it: JSONB grant only, no grant columns. */+async function olderBinaryToken(permissions: unknown, scopes: string | null = '{read,write}') {+ const name = `legacy-${randomUUID().slice(0, 8)}`;+ const token = generateToken('gbrain_');+ const [row] = typeof permissions === 'string'+ ? await engine.executeRaw<{ id: string }>('INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], to_jsonb($4::text)) RETURNING id', [name, hashToken(token), scopes, permissions])+ : await executeRawJsonb<{ id: string }>(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id', [name, hashToken(token), scopes], [permissions]);+ return { id: row.id, name, token };+}++async function doctor() {+ const checks = await legacyTokenGrantsEntry.run({ engine } as unknown as DoctorContext);+ if (!Array.isArray(checks)) throw new Error('doctor entry stopped');+ return Object.fromEntries(checks.map(c => [c.name, c]));+}++const WELL_FORMED: unknown[] = [+ { takes_holders: ['world'] },+ { takes_holders: ['world', 'brain'], source_id: ['other', 'default'], allowed_operations: ['get_page', 'search'] },+ { source_id: 'other' },+ { source_id: [], takes_holders: [], allowed_operations: [] },+ { source_id: ['default'], note: 'kept' },+ JSON.stringify({ takes_holders: ['world'], allowed_operations: ['search'] }),+];++describe('schema migration converts legacy grants in bulk', () => {+ test('every well-formed token converts with an unchanged effective grant; malformed stays denied; a rerun is a no-op', async () => {+ const tokens = [];+ for (const p of WELL_FORMED) tokens.push(await olderBinaryToken(p));+ tokens.push(await olderBinaryToken({ takes_holders: ['world'] }, null));+ const malformed = await olderBinaryToken('{not json');+ const before = new Map<string, unknown>();+ for (const t of tokens) before.set(t.id, grantFromTokenRow(await rowOf(t.id)));+ expect((await doctor()).legacy_token_grant_shape.details?.convertible_count).toBe(tokens.length);++ await engine.setConfig('version', '200');+ const applied = await runMigrations(engine);+ expect(applied.applied).toBeGreaterThan(0);++ for (const t of tokens) {+ const row = await rowOf(t.id);+ const after = grantFromTokenRow(row);+ expect({ id: t.id, shape: after.shape, drift: after.drift }).toEqual({ id: t.id, shape: 'unified', drift: [] });+ const { shape: _a, revision: _b, ...afterAxes } = after;+ const { shape: _c, revision: _d, ...beforeAxes } = before.get(t.id) as typeof after;+ expect(afterAxes).toEqual(beforeAxes);+ }+ expect((await rowOf(malformed.id)).source_grant).toBeNull();+ const shape = (await doctor()).legacy_token_grant_shape;+ expect(shape.details).toMatchObject({ convertible_count: 0, legacy_shape_count: 1, mirror_window_ends: GRANT_MIRROR_WINDOW_ENDS });+ expect(shape.status).toBe('warn');+ expect(shape.details?.malformed).toContainEqual({ name: malformed.name, id: malformed.id,+ argv: ['gbrain', 'auth', 'rescope', '--id', malformed.id, '--reset-default', 'sources,takes-holders,operations'] });+ expect(shape.fix).toMatchObject({ consent: ['credentials'], argv: ['gbrain', 'auth', 'rescope', '--id', malformed.id, '--reset-default', 'sources,takes-holders,operations'] });++ const revisions = await Promise.all(tokens.map(async t => (await rowOf(t.id)).grant_revision));+ await engine.setConfig('version', '200');+ await runMigrations(engine);+ expect(await Promise.all(tokens.map(async t => (await rowOf(t.id)).grant_revision))).toEqual(revisions);+ await engine.executeRaw('UPDATE access_tokens SET revoked_at = now() WHERE id = $1::uuid', [malformed.id]);+ }, 120_000);+});++describe('on-read conversion fallback', () => {+ test('a token an older binary creates after the migration converts on its first HTTP read, with the same grant', async () => {+ const t = await olderBinaryToken({ takes_holders: ['world', 'brain'], source_id: ['other'] });+ const inMemory = grantFromTokenRow(await rowOf(t.id));+ const auth = await verify(t.token);+ expect(auth).toMatchObject({ sourceId: 'other', allowedSources: ['other'], hasSourceGrant: true, takesHoldersAllowList: ['world', 'brain'] });+ const row = await rowOf(t.id);+ expect(row).toMatchObject({ source_grant: 'federated', source_id: 'other', federated_read: ['other'], takes_holders: ['world', 'brain'], grant_revision: 1 });+ expect(grantFromTokenRow(row)).toMatchObject({ shape: 'unified', drift: [], sources: inMemory.sources, takesHolders: inMemory.takesHolders });+ expect((await doctor()).legacy_token_grant_shape.details?.convertible_count).toBe(0);+ });++ test('concurrent first reads convert the row exactly once', async () => {+ const t = await olderBinaryToken({ takes_holders: ['world'], allowed_operations: ['search'] });+ const results = await Promise.all(Array.from({ length: 6 }, () => verify(t.token)));+ for (const r of results) expect(r).toEqual(results[0]);+ expect(await rowOf(t.id)).toMatchObject({ source_grant: 'default', allowed_operations: ['search'], grant_revision: 1 });+ });++ test('a read-only database still authorizes with the identical grant and leaves the row unconverted', async () => {+ const t = await olderBinaryToken({ takes_holders: ['world'], source_id: ['other', 'default'] });+ const live = sqlQueryForEngine(engine);+ const readOnly: SqlQuery = (strings, ...values) => /^\s*UPDATE/i.test(strings[0]!)+ ? Promise.reject(Object.assign(new Error('cannot execute UPDATE in a read-only transaction'), { code: '25006' }))+ : live(strings, ...values);+ const auth = await verify(t.token, readOnly);+ expect(auth).toMatchObject({ sourceId: 'other', allowedSources: ['other', 'default'], hasSourceGrant: true, takesHoldersAllowList: ['world'] });+ expect((await rowOf(t.id)).source_grant).toBeNull();+ expect(await verify(t.token)).toEqual(auth);+ expect((await rowOf(t.id)).source_grant).toBe('federated');+ });++ test('a malformed token is denied on the HTTP path and never converted', async () => {+ const t = await olderBinaryToken('[1,2]');+ const auth = await verify(t.token);+ expect(auth).toMatchObject({ sourceId: NO_SOURCES, allowedSources: [], hasSourceGrant: true, allowedOperations: [], takesHoldersAllowList: [] });+ expect((await rowOf(t.id)).source_grant).toBeNull();+ });+});++describe('doctor reports the mirror window', () => {+ test('legacy_token_grant_drift and legacy_token_grant_shape name the end date', async () => {+ const checks = await doctor();+ expect(checks.legacy_token_grant_drift.details?.mirror_window_ends).toBe(GRANT_MIRROR_WINDOW_ENDS);+ expect(checks.legacy_token_grant_shape.message).toContain(GRANT_MIRROR_WINDOW_ENDS);+ });+});diff --git a/test/token-mint.test.ts b/test/token-mint.test.tsindex c1a0fafc9c..b2178fc046 100644--- a/test/token-mint.test.ts+++ b/test/token-mint.test.ts@@ -11,6 +11,7 @@ import { sqlQueryForEngine, type SqlQuery } from '../src/core/sql-query.ts';import { mintLegacyToken, revokeLegacyTokenById } from '../src/core/token-mint.ts';import { normalizeTokenScopes } from '../src/core/legacy-token-scope.ts';import { hashToken } from '../src/core/utils.ts';+import { ACCESS_TOKEN_GRANT_SCHEMA_SQL } from '../src/core/grants/access-token-schema.ts';let engine: PGLiteEngine;let sql: SqlQuery;@@ -20,8 +21,12 @@ beforeAll(async () => {await engine.connect({});sql = sqlQueryForEngine(engine);// Just the table under test — the migration v4 shape (scopes TEXT[] is- // original schema) + the v38 permissions column.- await engine.executeRaw(`+ // original schema) + the v38 permissions column + the F3 grant columns.+ await engine.executeRaw(PRE_GRANT_COLUMNS_TABLE);+ for (const statement of ACCESS_TOKEN_GRANT_SCHEMA_SQL.split(";").map(s => s.trim()).filter(Boolean)) await engine.executeRaw(statement);+}, 60_000);++const PRE_GRANT_COLUMNS_TABLE = `CREATE TABLE IF NOT EXISTS access_tokens (id UUID PRIMARY KEY DEFAULT gen_random_uuid(),name TEXT NOT NULL,@@ -32,8 +37,7 @@ beforeAll(async () => {last_used_at TIMESTAMPTZ,revoked_at TIMESTAMPTZ)- `);-}, 60_000);+ `;afterAll(async () => {if (engine) await engine.disconnect();@@ -118,6 +122,22 @@ describe('mintLegacyToken', () => {});});+describe('mintLegacyToken on a brain without the grant columns', () => {+ test('refuses with migrations_pending and a filled fix instead of writing a JSONB-only grant', async () => {+ const bare = new PGLiteEngine();+ await bare.connect({});+ try {+ await bare.executeRaw(PRE_GRANT_COLUMNS_TABLE);+ const refusal = await mintLegacyToken(bare, { name: 'pre-columns', takesHolders: ['world'], scopes: ['read'] }).catch(e => e);+ expect(refusal).toMatchObject({ code: 'migrations_pending', fix: { argv: ['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'], actor: 'agent' } });+ expect(refusal.why).toBeTruthy();+ expect(await bare.executeRaw('SELECT 1 FROM access_tokens')).toHaveLength(0);+ } finally {+ await bare.disconnect();+ }+ }, 60_000);+});+describe('revokeLegacyTokenById [C7]', () => {test('revokes exactly one of two same-name rows; re-revoke reports already-done', async () => {const a = await mintLegacyToken(engine, { name: 'twin', takesHolders: ['world'], scopes: ['read', 'write'] });