Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W-C6: auth clients reports the operation-snapshot state, the re-pin fix and revoked clients
garrytan5155cc026625
diff --git a/TODOS.md b/TODOS.mdindex da9a86f27d..0f8c919047 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,10 @@# TODOS+## Contributor audit fix wave follow-ups (filed 2026-10-05)++- [ ] **P2 — List the operations an unbounded OAuth client gained after an upgrade.**+ **What:** `gbrain auth clients` marks a client with no operation snapshot `operations: "all"` with `includes_future_operations: true` (#6008 visibility), but it cannot say which operations became reachable since the client's last regrant: the server knows only today's operation set. **Why:** an operator reviewing an unbounded client after an upgrade sees "all", not "these five are new". **Fix:** a versioned operation inventory (operation name → first release that shipped it, generated at build time from `operations.ts`), plus the release each client was last granted under, so `auth clients` and doctor can list operations added since then; reuse the legacy-token `--refresh-operations` preview shape. **Effort:** M. **Priority:** P2.+## Test, eval and CI fix wave follow-ups (filed 2026-10-04, GBRA-47)Context: `.github/nightly-known-red.tsv` rows point here; nightly-watch keeps their incidents open until the row is deleted. Scale-tier evidence: per-batch `vectors` lines and the phase watchdog in `scripts/scale/`.diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 06be4438f4..8089d0c0cc 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type.-- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant; it is the takes-holders alias of `rescope-token`), `gbrain auth rescope-token <name>|--id <uuid>` (the legacy-token twin of `rescope-client`, logic in `src/core/grants/legacy-token.ts`: `--sources`/`--takes-holders`/`--operations` take a list or `none` = explicit empty list, omitted flags preserve, `--reset-default` restores the `auth create` defaults, `--refresh-operations` previews and widens only by `--add`/`--all-new`; pinned by `test/auth-rescope-token.serial.test.ts`), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.+- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant; it is the takes-holders alias of `rescope-token`), `gbrain auth rescope-token <name>|--id <uuid>` (the legacy-token twin of `rescope-client`, logic in `src/core/grants/legacy-token.ts`: `--sources`/`--takes-holders`/`--operations` take a list or `none` = explicit empty list, omitted flags preserve, `--reset-default` restores the `auth create` defaults, `--refresh-operations` previews and widens only by `--add`/`--all-new`; pinned by `test/auth-rescope-token.serial.test.ts`), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.mdindex dc0f834d6f..fe0b44e4ab 100644--- a/docs/guides/hosted-harness-access.md+++ b/docs/guides/hosted-harness-access.md@@ -119,7 +119,7 @@ are one principal. See [shared brain skills](shared-brain-skills.md).A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.-New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. Explicitly regrant to include them: `gbrain auth rescope-client <client_id> --allowed-operations …` for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens. `gbrain auth rescope --client <client_id> --operations all` stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.+New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. Explicitly regrant to include them: `gbrain auth rescope-client <client_id> --allowed-operations …` for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens. `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 0944e42e34..2ccd312e73 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -315,6 +315,18 @@ from `gbrain auth list`. The older commands stay as aliases:`--allowed-operations`, `--surface`, `--profile`, ...), which also pass through`auth rescope --client`, and `gbrain auth permissions <name>set-takes-holders <list>` is `auth rescope --token <name> --takes-holders <list>`.+For a client, `--allowed-operations all` and `--operations all` are aliases:+both store no operation snapshot and clear the profile.++`gbrain auth clients` (text and `--json`) reports each client's operation+snapshot in one of four states: `operations: "all"` with+`includes_future_operations: true` when no snapshot is stored (scopes, surface+and source limits still apply), `[]` (deny-all), an explicit list, or+`"unavailable"` on a brain whose schema predates operation snapshots. A live+client with no snapshot carries a `fix` that re-pins it:+`gbrain auth rescope --client <client_id> --operations <op,...>` or+`--profile <profile>`. A revoked client is marked `revoked` with its+`revoked_at` time and gets no fix.### One grant shapediff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 17f9e89190..ca2eb8d1a7 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -30,7 +30,8 @@ import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';import { readClientGrant, rescopeClientGrant, resolveGrantProfile, type GrantPatch } from '../core/grants/service.ts';import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type RescopeGrantArgs } from '../core/grants/cli.ts';-import { GrantError, grantFromClient } from '../core/grants/model.ts';+import { GRANT_PROFILES, GrantError, grantFromClient } from '../core/grants/model.ts';+import { cliRenderContext, renderAction, type RenderedAction } from '../core/agent-output.ts';import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';function hashToken(token: string): string {@@ -927,6 +928,64 @@ export interface ClientRow {surface_set_by: string | null;source_id: string | null;federated_read: string[] | null;+ /** The operation snapshot: NULL = none stored; absent = the brain predates the column. */+ allowed_operations?: string[] | null;+ /** Soft-revoke stamp (`auth` lifecycle revoke); absent on schemas without it. */+ deleted_at?: string | Date | null;+}++/** The operation-snapshot axis of one client, as `auth clients` reports it. */+export interface ClientOperationsView {+ /** 'all' = no snapshot (SQL NULL); [] = deny-all; a list = pinned; 'unavailable' = old schema. */+ operations: 'all' | string[] | 'unavailable';+ operations_state: 'all' | 'none' | 'list' | 'unavailable';+ /** true only for 'all': operations later upgrades add are reachable without a regrant. */+ includes_future_operations: boolean | null;+ revoked: boolean;+ /** The re-pin command for a live client with no snapshot. */+ fix?: RenderedAction;+}++/**+ * Four distinct operation states (#6008 visibility): SQL NULL is `all` on the+ * operation-snapshot axis only (scopes, surface and source limits still+ * apply); an empty array refuses every operation; a list is pinned; a schema+ * without the column is `unavailable`, never guessed.+ */+export function clientOperationsView(row: ClientRow): ClientOperationsView {+ const revoked = row.deleted_at != null;+ const ops = row.allowed_operations;+ if (ops === undefined) return { operations: 'unavailable', operations_state: 'unavailable', includes_future_operations: null, revoked };+ if (ops === null) {+ const view: ClientOperationsView = { operations: 'all', operations_state: 'all', includes_future_operations: true, revoked };+ if (revoked) return view;+ view.fix = renderAction({+ argv: ['gbrain', 'auth', 'rescope', '--client', row.client_id, '--operations', '<OPERATIONS>'],+ inputs: [{ name: 'OPERATIONS', how: `Ask the user which operations this client should keep (comma-separated, e.g. search,get_page,remember), or pin a profile instead: gbrain auth rescope --client ${row.client_id} --profile <profile> (${GRANT_PROFILES.join(', ')}).` }],+ consent: [], actor: 'agent', requires_exclusive: false,+ why: 'This client has no operation snapshot, so it reaches every operation its scopes and surface allow, including operations later upgrades add. A pinned list or profile keeps new operations from arriving without a regrant.',+ verify: { argv: ['gbrain', 'auth', 'clients', '--json'] },+ }, cliRenderContext());+ return view;+ }+ return { operations: ops, operations_state: ops.length === 0 ? 'none' : 'list', includes_future_operations: false, revoked };+}++/** Text lines for the operation axis (and revocation) of one client. */+export function clientOperationsLines(row: ClientRow): string[] {+ const view = clientOperationsView(row);+ const lines: string[] = [];+ if (view.revoked) lines.push(` revoked: ${row.deleted_at instanceof Date ? row.deleted_at.toISOString() : String(row.deleted_at)} (credentials no longer work)`);+ if (view.operations_state === 'unavailable') lines.push(' operations: unavailable (this brain predates per-client operation snapshots)');+ else if (view.operations_state === 'none') lines.push(' operations: none (deny-all snapshot)');+ else if (view.operations_state === 'list') {+ const ops = view.operations as string[];+ lines.push(` operations: ${ops.length} pinned (${ops.slice(0, 8).join(', ')}${ops.length > 8 ? ', ...' : ''})`);+ } else {+ lines.push(' operations: all (no snapshot; includes operations later upgrades add; scopes, surface and source limits still apply)');+ if (view.fix) lines.push(` re-pin: gbrain auth rescope --client ${row.client_id} --operations <op,...> (or --profile <profile>)`);+ }+ return lines;}/**@@ -944,8 +1003,17 @@ export async function listClientRows(engine: BrainEngine): Promise<ClientRow[]>// 42703 by code; the column list covers message-only (code-less) variants.const isSchemaShapeError = (e: unknown): boolean =>isUndefinedTableError(e) ||- ['surface', 'surface_set_by', 'source_id', 'federated_read']+ ['allowed_operations', 'deleted_at', 'surface', 'surface_set_by', 'source_id', 'federated_read'].some(col => isUndefinedColumnError(e, col));+ try {+ return await engine.executeRaw<ClientRow>(+ `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at+ FROM oauth_clients ORDER BY client_name, client_id`,+ );+ } catch (e) {+ // Brain predates the operation-snapshot columns: operations read `unavailable`.+ if (!isSchemaShapeError(e)) throw e;+ }try {return await engine.executeRaw<ClientRow>(`SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read@@ -1005,6 +1073,8 @@ async function clientsCmd(args: string[]) {surface_set_by: c.surface_set_by,source_id: c.source_id,federated_read: c.federated_read,+ ...clientOperationsView(c),+ revoked_at: c.deleted_at ?? null,usage: usageByToken.get(c.client_id) ?? null,})),// Legacy bearer tokens seen in the window (no oauth_clients row).@@ -1027,6 +1097,7 @@ async function clientsCmd(args: string[]) {: '<server/config resolution>';console.log(` scopes: ${c.scope ?? '<none>'} surface: ${surfaceStr}`);console.log(` write source: ${c.source_id ?? '<none>'} federated reads: ${(c.federated_read ?? []).join(', ') || '<none>'}`);+ for (const line of clientOperationsLines(c)) console.log(line);if (parsed.usage) {if (u) {const auto = u.likely_automation ? ' [automation-shaped: >90% context_pack/delta]' : '';@@ -1181,7 +1252,9 @@ Usage:so server/config resolution applies again). Alwaysbounded by the server's --surface ceiling.gbrain auth clients [--usage] [--days N] [--json] List OAuth clients with scopes, write source, federated- reads + tool surface. --usage+ reads, tool surface + operation snapshot ('all' = no+ snapshot, includes future operations; re-pin with+ auth rescope --client <id> --operations|--profile). --usagejoins per-client op-call counts, top ops, and last-seenfrom mcp_request_log (default 30d window; HTTP clientsonly — stdio use is not logged). Automation-shapeddiff --git a/test/auth-clients-operations.test.ts b/test/auth-clients-operations.test.tsnew file mode 100644index 0000000000..d595edc523--- /dev/null+++ b/test/auth-clients-operations.test.ts@@ -0,0 +1,98 @@+/**+ * `gbrain auth clients` operation-snapshot visibility (#6008). Authoring gate:+ * (1) protects the four distinct operation states the listing reports (SQL+ * NULL = `all` with includes_future_operations and a re-pin fix, [] =+ * deny-all, an explicit list, `unavailable` on a schema without the column)+ * and the revoked marker; (2) fails when a NULL snapshot reads like a pinned+ * grant or an old schema is guessed; (3) the existing listClientRows test+ * covers only scope/surface/source columns; (4) no production seam. Both+ * engines: PGLite here, PostgreSQL through+ * test/e2e/auth-clients-operations-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { clientOperationsLines, clientOperationsView, listClientRows } from '../src/commands/auth.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const CLIENTS: Array<[id: string, ops: string[] | null, revoked: boolean]> = [+ ['c-ops-all', null, false],+ ['c-ops-none', [], false],+ ['c-ops-list', ['search', 'get_page'], false],+ ['c-ops-revoked', null, true],+];++for (const kind of testBackends()) {+ describe(`auth clients operation states (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (kind === 'postgres') {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ } else {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ }+ for (const [id, ops, revoked] of CLIENTS) {+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, allowed_operations, deleted_at)+ VALUES ($1, $1, 'read', 'default', ARRAY['default'], $2::text[], ${revoked ? 'now()' : 'NULL'})`,+ [id, ops],+ );+ }+ }, 120_000);+ afterAll(async () => { await close?.(); });++ const byId = async () => new Map((await listClientRows(engine)).map(r => [r.client_id, r]));++ test('SQL NULL is `all` with includes_future_operations and a re-pin fix', async () => {+ const row = (await byId()).get('c-ops-all')!;+ expect(row.allowed_operations).toBeNull();+ const view = clientOperationsView(row);+ expect(view).toMatchObject({ operations: 'all', operations_state: 'all', includes_future_operations: true, revoked: false });+ expect(view.fix?.argv?.slice(0, 7)).toEqual(['gbrain', 'auth', 'rescope', '--client', 'c-ops-all', '--operations', '<OPERATIONS>']);+ expect(view.fix?.inputs?.[0]?.how).toContain('--profile');+ expect(view.fix?.next).toBe('run');+ const lines = clientOperationsLines(row).join('\n');+ expect(lines).toContain('operations: all');+ expect(lines).toContain('re-pin: gbrain auth rescope --client c-ops-all --operations');+ });++ test('an empty array is deny-all, not `all`', async () => {+ const row = (await byId()).get('c-ops-none')!;+ expect(clientOperationsView(row)).toEqual({ operations: [], operations_state: 'none', includes_future_operations: false, revoked: false });+ expect(clientOperationsLines(row).join('\n')).toContain('operations: none (deny-all snapshot)');+ });++ test('an explicit list is pinned and reports no future operations', async () => {+ const row = (await byId()).get('c-ops-list')!;+ expect(clientOperationsView(row)).toEqual({ operations: ['search', 'get_page'], operations_state: 'list', includes_future_operations: false, revoked: false });+ expect(clientOperationsLines(row).join('\n')).toContain('operations: 2 pinned (search, get_page)');+ });++ test('a revoked client is marked revoked and gets no re-pin fix', async () => {+ const row = (await byId()).get('c-ops-revoked')!;+ const view = clientOperationsView(row);+ expect(view).toMatchObject({ operations: 'all', revoked: true });+ expect(view.fix).toBeUndefined();+ const lines = clientOperationsLines(row).join('\n');+ expect(lines).toContain('revoked:');+ expect(lines).not.toContain('re-pin');+ });++ test('a schema without the snapshot columns reports `unavailable` (old-schema fallback)', async () => {+ // Last test of the suite: the engine is a throwaway brain (in-memory PGLite / an isolated Postgres database).+ await engine.executeRaw('ALTER TABLE oauth_clients DROP COLUMN allowed_operations');+ const rows = await listClientRows(engine);+ const row = rows.find(r => r.client_id === 'c-ops-list')!;+ expect(row.allowed_operations).toBeUndefined();+ expect(clientOperationsView(row)).toEqual({ operations: 'unavailable', operations_state: 'unavailable', includes_future_operations: null, revoked: false });+ expect(clientOperationsLines(row).join('\n')).toContain('operations: unavailable');+ expect(row.scope).toBe('read');+ });+ });+}diff --git a/test/e2e/auth-clients-operations-postgres.test.ts b/test/e2e/auth-clients-operations-postgres.test.tsnew file mode 100644index 0000000000..8e5cf0f780--- /dev/null+++ b/test/e2e/auth-clients-operations-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../auth-clients-operations.test.ts'));diff --git a/test/e2e/client-grants.test.ts b/test/e2e/client-grants.test.tsindex d2e2e859a3..cedde87d31 100644--- a/test/e2e/client-grants.test.ts+++ b/test/e2e/client-grants.test.ts@@ -123,6 +123,14 @@ suite('client capability grants — Postgres and admin HTTP', () => {expect(after.scopes).toEqual(before.scopes);const [row] = await engine.executeRaw('SELECT allowed_operations, grant_profile FROM oauth_clients WHERE client_id = $1', [created.clientId]);expect(row.allowed_operations).toBeNull(); expect(row.grant_profile).toBeNull();+ // W-C6: the listing marks the unbounded grant and names the re-pin command.+ const env = keylessBrainEnv(process.env, home, { DATABASE_URL: databaseUrl, GBRAIN_DATABASE_URL: databaseUrl, GBRAIN_BRAIN_ID: undefined, GBRAIN_MCP_URL: undefined });+ const listing = Bun.spawn(['bun', '--no-env-file', 'run', resolve('src/cli.ts'), 'auth', 'clients', '--json'], { cwd: home, env: env as Record<string, string>, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, exitCode] = await Promise.all([new Response(listing.stdout).text(), listing.exited]);+ expect(exitCode).toBe(0);+ const listed = (JSON.parse(stdout) as any).clients.find((c: any) => c.client_id === created.clientId);+ expect(listed).toMatchObject({ operations: 'all', operations_state: 'all', includes_future_operations: true, revoked: false });+ expect(listed.fix.argv.slice(0, 6)).toEqual(['gbrain', 'auth', 'rescope', '--client', created.clientId, '--operations']);});test('admin credential delivery can be recovered without another grant or secret rotation', async () => {