Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge lane E (keys/grants) into capy/foundations-2

garrytan4069c02594b6
diff --cc TODOS.md
index 6abe7f4ab4,8f9eee6f22..63c7cea3cc
--- a/TODOS.md
+++ b/TODOS.md
@@@ -108,20 -89,18 +108,20 @@@ Spec: `docs/designs/AGENT_OPERATOR_WAVE
**What:** proven on PGLite, Postgres and PgBouncer fixtures only. **Fix:** run the preview and apply on a managed brain with real history and record the filled and unrecorded counts. **Effort:** S. **Priority:** P2 (Foundations 2).
- [ ] **P2 — `--json` refusals from CLI-only ops print to stderr only.**
**What:** `gbrain attribution --json` (and other CLI ops through the shared framework) write refusals to stderr, not as a JSON object on stdout. **Effort:** S. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — PGLite `sources refresh` while `gbrain serve` owns the database.**
- **What:** the refresh needs the writer lock; with a resident serve on PGLite it waits or refuses. **Fix:** delegate the refresh over the local persistence IPC socket. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P3 — The consumer's idle probe ignores the refresh effect fence.**
- **What:** the resident consumer's idle tick does not consult an active refresh's fence before probing. Harmless today (the probe writes nothing). **Effort:** S. **Priority:** P3 (Foundations 2).
+- [x] **P2 — PGLite `sources refresh` while `gbrain serve` owns the database.** **Completed: Foundations 2** — the refresh runs inside the resident owner through the `writer_refresh` administration operation (`src/commands/sources-refresh-delegate.ts`).
+- [x] **P3 — The consumer's idle probe ignores the refresh effect fence.** **Completed: Foundations 2** — the idle probe applies `refreshFenceClear` to effects like the claims do.
- - [ ] **P2 — Drop the JSONB grant authority for legacy tokens.**
- **What:** migrated tokens still mirror `permissions` JSON for older binaries, and admin-dashboard-created tokens are still born on the JSONB shape. **Fix:** after one release window, read only the unified columns and have the dashboard mint through `insertUnifiedToken`. **Effort:** M. **Priority:** P2 (Foundations 2).
- - [ ] **P2 — `--sources none` for OAuth clients.**
- **What:** refused for clients in F3 (no behavior change); needs per-client takes holders. **Effort:** M. **Priority:** P2 (Foundations 2).
+ - [x] **P2 — Drop the JSONB grant authority for legacy tokens.** **Completed: Foundations 2** — the dashboard mints through `mintLegacyToken`, migration v201 converts every legacy grant, the HTTP auth paths read the columns (a later legacy row converts on its first read), and minting no longer writes a JSONB-only grant.
+ - [ ] **P2 — Remove the `permissions` grant mirror after its window.**
+ **What:** tokens still write the `permissions` JSONB mirror and enforce drift until `GRANT_MIRROR_WINDOW_ENDS` (2026-11-04, `src/core/grants/model.ts`) so older binaries keep working. **Fix:** after that date stop writing the mirror, drop the drift comparison and `legacy_token_grant_drift`, and keep `migrateLegacyTokens` only for brains that skipped v201. **Effort:** M. **Priority:** P2.
+ - [x] **P2 — `--sources none` for OAuth clients.** **Completed: Foundations 2** — `auth rescope --client <id> --sources none` and `--takes-holders a,b|none` (migration v202).
-- [ ] **P2 — Seat follow-ups (#4618).**
- **What:** Codex hooks' trust hash changes when a seat is added; the harness Codex note should say so; OpenClaw's heartbeat does not report a seat write failure; a pattern page's `seat` is never removed when its sessions age out. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — Large-brain ceilings in the 50k nightly.**
- **What:** the progress-aware sync deadline, 20k-file `sources add`, the loud embed budget stop and the serve boot window are pinned by unit and CLI tests, not yet asserted by the 50k scale-tier run; delegated syncs (serve-owned) are not yet progress-aware. **Effort:** M. **Priority:** P2 (Foundations 2).
+- [x] **P2 — Seat follow-ups (#4618).** **Completed: Foundations 2** — the OpenClaw context-engine heartbeat reports seat reasons (write failure, conflict, invalid label) with their hints, and a pattern page drops a seat its reflections no longer share. The Codex trust-hash item closed with no code: the Codex SessionEnd command never carries a seat (`buildCodexSessionEndCommand` takes only the gbrain binary; `--seat` prints a note to set `GBRAIN_SEAT` instead), so adding a seat cannot change its trust hash.
+- [x] **P2 — Large-brain ceilings in the scale tier.** **Completed: Foundations 2** — every scale run asserts the F4d ceilings through the real CLI (`scripts/scale/f4d.ts`: progress-aware sync deadline, loud embed budget stop and serve boot window at every tier, the 20,000-file `sources add` at 20k and up), so the 50k tier carries them once `trend.ts` unlocks it; delegated syncs keep the progress-aware deadline.
+- [ ] **P2 — MCP search on Postgres slows sharply between 10k and 20k pages.**
+ **What:** the scale tier's MCP-path search p50 on Postgres is 615 ms at 20k pages (69.5 ms at 10k) and the source-scoped grant search 1,169 ms, while PGLite at 20k answers in 27 and 19 ms. Interactive ceilings are defined only up to 10k, so this is report-only. **Fix:** read the captured plans in the 20k Postgres report (`scale-report-postgres-20000`) for the statement that grows, and add a 20k ceiling once fixed. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — `embed --stale` takes far longer than its time budget to stop.**
+ **What:** with `GBRAIN_EMBED_TIME_BUDGET_MS=1500` the scale tier's budget-stop check exits 11 correctly but after about 61 s on a 20k brain (2.6 s on an empty one), so the budget does not bound wall time. **Fix:** profile what runs before the first batch and after the stop (stale counting, the remaining-count query) and keep it inside the budget. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `findOrphans` recomputes the full orphan set per call.**
+ **What:** `find_orphans` pages its rows in TypeScript after computing every orphan, so each page of a large result costs a full scan (the scale verifier reads `total_orphans` and one maximal page instead of paging). **Fix:** page in SQL with `ORDER BY source_id, slug LIMIT/OFFSET` and a separate count. **Effort:** S. **Priority:** P3.
- [ ] **P3 — Keyword search scoped to one source: 18.2 to 22.1 ms at 10k PGLite pages.**
**What:** the five-run ranges overlap (17.4-19.4 vs 18.7-25.0 ms), so this may be noise; the scale tier's calibrated budget will show a trend. **Effort:** S. **Priority:** P3 (Foundations 2).
- [ ] **P3 — Enforce the scale tier's ceilings and calibrated budgets.**
diff --cc docs/architecture/key-files/security.md
index 71b319c786,aa5974fa89..d05c86b151
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@@ -7,9 -7,10 +7,10 @@@ Current behavior and load-bearing invar
- `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 and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v202 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` 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/` — 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 and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v202 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v201 (`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`.
- `src/core/guarded-http.ts` + `src/core/ssrf-validate.ts` — DNS answer classification, validated-address connections with original TLS/HTTP hostname and port, shared deadline/redirect policy, header-only probes, and bounded gzip/deflate/Brotli decoding. Ambient proxies fail closed with restart guidance. Consumers: URL reachability, remote images, and HTTP integration checks. Real TLS fixtures run on Bun 1.4.0 and 1.4.2.
diff --cc scripts/e2e-test-map.ts
index 722f3dd6f3,ee0f91ed9e..c5fd6eec39
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@@ -128,7 -128,14 +128,14 @@@ export const E2E_TEST_MAP: Record<strin
// F3: unified token grant columns, lazy migration, drift and the born-unified mint on Postgres.
"src/core/grants/model.ts": ["test/e2e/access-token-grants.test.ts"],
"src/core/grants/access-token-schema.ts": ["test/e2e/access-token-grants.test.ts"],
- "src/core/token-mint.ts": ["test/e2e/access-token-grants.test.ts", "test/e2e/auth-rescope-token.test.ts"],
+ "src/core/token-mint.ts": ["test/e2e/access-token-grants.test.ts", "test/e2e/auth-rescope-token.test.ts", "test/e2e/serve-http-api-keys.test.ts"],
+ // Lane E: dashboard API keys, the bulk legacy grant conversion and the OAuth client grant axes on Postgres.
+ "src/commands/serve-http-api-keys.ts": ["test/e2e/serve-http-api-keys.test.ts"],
+ "src/core/grants/oauth-client-axes-schema.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
+ "src/core/grants/cli.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
+ "src/core/grants/service.ts": ["test/e2e/oauth-client-grant-axes.test.ts", "test/e2e/client-grants.test.ts"],
- "src/core/schema-migrations/v201-lane-e-legacy-token-grant-conversion.ts": ["test/e2e/access-token-grants.test.ts"],
- "src/core/schema-migrations/v202-lane-e-oauth-client-grant-axes.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
++ "src/core/schema-migrations/v201-legacy-token-grant-conversion.ts": ["test/e2e/access-token-grants.test.ts"],
++ "src/core/schema-migrations/v202-oauth-client-grant-axes.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
"src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/withdrawal-bounded-safety-postgres.test.ts", "test/e2e/withdrawal-crash-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts", "test/e2e/fact-withdrawal-scope-postgres.test.ts"],
"src/commands/mcp*.ts": ["test/e2e/harness-access.test.ts"],
// OpenRouter subagent-loop families: the family allowlist + recipe feed the
diff --cc src/core/cli-flag-registry.generated.ts
index 9989dfa055,c4c013f420..a4519ef1b6
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -76,9 -76,9 +76,9 @@@ export const CLI_FLAG_REGISTRY: Record<
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
- 'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
- 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],
+ 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-migrate', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],
'models': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status', '--to'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
diff --cc src/core/schema-migrations/registry.generated.ts
index 16ef4d9ecc,2261bc5f58..d39f28ec02
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -201,6 -201,8 +201,8 @@@ import { v197 } from './v197-managed-gu
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';
-import { v202 } from './v202-lane-e-oauth-client-grant-axes.ts';
++import { v201 } from './v201-legacy-token-grant-conversion.ts';
++import { v202 } from './v202-oauth-client-grant-axes.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
diff --cc src/core/schema-migrations/v201-legacy-token-grant-conversion.ts
index 0000000000,bc4681f0ce..0f67bb7e50
mode 000000,100644..100644
--- a/src/core/schema-migrations/v201-legacy-token-grant-conversion.ts
+++ b/src/core/schema-migrations/v201-legacy-token-grant-conversion.ts
@@@ -1,0 -1,30 +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',
++ name: '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; gbrain doctor (legacy_token_grant_shape) lists each one with its fix.`
+ : '')
+ + '\n');
+ },
+ };
diff --cc src/core/schema-migrations/v202-oauth-client-grant-axes.ts
index 0000000000,e0110e6e07..e652c0f1ce
mode 000000,100644..100644
--- a/src/core/schema-migrations/v202-oauth-client-grant-axes.ts
+++ b/src/core/schema-migrations/v202-oauth-client-grant-axes.ts
@@@ -1,0 -1,16 +1,16 @@@
+ import { OAUTH_CLIENT_GRANT_AXES_SQL } from '../grants/oauth-client-axes-schema.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.
+ //
+ // OAuth clients gain the explicit no-source grant (`source_grant = 'none'`)
+ // and a per-client takes-holder allow-list (fragment
+ // src/core/grants/oauth-client-axes-schema.ts). Additive and metadata-only:
+ // every existing client keeps NULL in both, which is its current grant.
+ export const v202: Migration = {
+ version: 202,
- name: 'lane_e_oauth_client_grant_axes',
++ name: 'oauth_client_grant_axes',
+ idempotent: true,
+ sql: OAUTH_CLIENT_GRANT_AXES_SQL,
+ };
diff --cc test/fixtures/goldens/migrations/records.json
index 190c942fa0,a6e808fe47..083ae70c64
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@@ -2968,6 -2969,40 +2969,40 @@@
"transaction": "absent",
"verify": "absent",
"version": 200
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "migrateLegacyTokens",
+ "migrationNotice",
+ "quietMigrationNotices"
+ ],
+ "sha256": "78b88e6a006553fb8cfb8f292589033de56a1a221bad085d9ae56c2d6ecf1b80"
+ },
+ "idempotent": true,
- "name": "lane_e_legacy_token_grant_conversion",
++ "name": "legacy_token_grant_conversion",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 201
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
- "name": "lane_e_oauth_client_grant_axes",
++ "name": "oauth_client_grant_axes",
+ "sql": {
+ "length": 179,
+ "sha256": "3bc9490443e69f225bf65df711dbe889a52300ae2b1d5ab977206456c6ed22c8"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 202
}
],
"versions": [