Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(auth): gbrain auth rescope for tokens and clients, lazy grant migration (F3)

garrytan6540b45891af
diff --git a/src/cli.ts b/src/cli.ts
index 8aa3e2f47e..661cee389d 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -3124,7 +3124,7 @@ ADMIN
[--install] [--json] Print the paste-ready command, or --install to run it
auth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clients
auth --help Full subcommand list (register-client,
- rescope-client, rescope-token, revoke-client, permissions, ...)
+ rescope, rescope-client, rescope-token, revoke-client, ...)
watch [--json] Push-based context: pipe conversation turns in,
volunteered brain pages stream out (#2095)
call <tool> '<json>' Raw tool invocation
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 6477c0b015..68ea876fdb 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -25,12 +25,13 @@ import { createEngine } from '../core/engine-factory.ts';
import type { BrainEngine } from '../core/engine.ts';
import { assertAllowedScopes } from '../core/scope.ts';
import { generateToken, isUndefinedColumnError, isUndefinedTableError } from '../core/utils.ts';
-import { TOKEN_ID_RE } from '../core/token-mint.ts';
+import { TOKEN_ID_RE, insertUnifiedToken } from '../core/token-mint.ts';
import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
-import { sqlQueryForEngine, executeRawJsonb, type SqlQuery } from '../core/sql-query.ts';
+import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';
import { readClientGrant, rescopeClientGrant, resolveGrantProfile, type GrantPatch } from '../core/grants/service.ts';
-import { parseRescopeGrantArgs } from '../core/grants/cli.ts';
-import { parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken } from '../core/grants/legacy-token.ts';
+import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type RescopeGrantArgs } from '../core/grants/cli.ts';
+import { GrantError, grantFromClient } from '../core/grants/model.ts';
+import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
@@ -93,34 +94,14 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
const takesHolders = opts.takesHolders && opts.takesHolders.length > 0
? opts.takesHolders
: ['world'];
- const permissions = { takes_holders: takesHolders };
- // JSONB write: pass the object via executeRawJsonb with an explicit
- // ::jsonb cast in the SQL string. Both engines round-trip the object
- // through the wire-protocol type oid without the v0.12.0 double-encode
- // bug class (verified by test/e2e/auth-permissions.test.ts:67 on
- // Postgres and test/sql-query.test.ts on PGLite).
- //
- // Scopes (when given) land in the original-schema scopes TEXT[] column
- // via an array literal through a TEXT param — values are allowlisted,
- // so the literal needs no quoting and runs identically on both engines.
- // Omitted → NULL → the historical grandfathered full-access grant.
- if (opts.scopes !== undefined) {
- await executeRawJsonb(
- engine,
- `INSERT INTO access_tokens (name, token_hash, permissions, scopes)
- VALUES ($1, $2, $4::jsonb, $3::text[])`,
- [name, hash, `{${opts.scopes.join(',')}}`],
- [permissions],
- );
- } else {
- await executeRawJsonb(
- engine,
- `INSERT INTO access_tokens (name, token_hash, permissions)
- VALUES ($1, $2, $3::jsonb)`,
- [name, hash],
- [permissions],
- );
- }
+ // F3: the token is born on the unified grant shape (columns + the
+ // permissions JSONB mirror older binaries read). Scopes land in the
+ // original-schema scopes TEXT[] column; omitted → NULL → the historical
+ // grandfathered full-access grant.
+ await insertUnifiedToken(engine, {
+ name, tokenHash: hash, ...(opts.scopes !== undefined ? { scopes: opts.scopes } : {}),
+ grant: { sources: { kind: 'default' }, takesHolders, allowedOperations: null },
+ });
const scopeLine = opts.scopes !== undefined
? `scopes=${JSON.stringify(opts.scopes)}`
: 'scopes=full access (grandfathered — pass --scopes read,write to narrow)';
@@ -128,7 +109,7 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
console.log(` ${token}\n`);
console.log('Save this token — it will not be shown again.');
console.log(`Revoke with: gbrain auth revoke "${name}" (or gbrain auth revoke --id <id> from auth list)`);
- console.log(`Update visibility: gbrain auth permissions "${name}" set-takes-holders world,garry`);
+ console.log(`Change its grants: gbrain auth rescope --token "${name}" --takes-holders world,garry (or --sources, --operations)`);
});
} catch (e: any) {
if (e.code === '23505') {
@@ -140,48 +121,13 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
}
}
+/** `auth permissions <name> set-takes-holders <list>`: alias of `auth rescope --token <name> --takes-holders <list>`. */
async function permissions(name: string, action: string, value: string | undefined) {
if (!name || action !== 'set-takes-holders' || !value) {
- console.error('Usage: auth permissions <name> set-takes-holders world,garry,brain');
- process.exit(1);
- }
- try {
- await withConfiguredSql(async (sql, engine) => {
- const list = value.split(',').map(s => s.trim()).filter(Boolean);
- if (list.length === 0) {
- console.error('takes-holders list cannot be empty (use "world" for default-deny on private)');
- process.exit(1);
- }
- const perms = { takes_holders: list };
- // JSONB UPDATE via executeRawJsonb — same pattern as create() above.
- // MERGE, never whole-object replace: `SET permissions = $2::jsonb`
- // would silently DELETE every other grant key (source_id federation,
- // and any future key) on a routine takes-holders edit — the grant-wipe
- // class the #4043 review caught.
- // The jsonb_typeof guard repairs rows carrying historical double-encode
- // damage (a jsonb string/array scalar): `scalar || object` would produce
- // a jsonb ARRAY and silently strand every grant, so a damaged left
- // operand is reset to '{}' on edit — the old whole-replace semantics for
- // damaged rows, merge semantics for healthy object rows.
- const result = await executeRawJsonb(
- engine,
- `UPDATE access_tokens
- SET permissions = (CASE WHEN jsonb_typeof(permissions) = 'object' THEN permissions ELSE '{}'::jsonb END) || $2::jsonb
- WHERE name = $1
- RETURNING id`,
- [name],
- [perms],
- );
- if (result.length === 0) {
- console.error(`Token "${name}" not found.`);
- process.exit(1);
- }
- console.log(`Updated "${name}": takes_holders = ${JSON.stringify(list)}`);
- });
- } catch (e: any) {
- console.error('Error:', e.message);
+ console.error('Usage: auth permissions <name> set-takes-holders world,garry,brain (alias of: gbrain auth rescope --token <name> --takes-holders <list>)');
process.exit(1);
}
+ await runRescope(['--token', name, '--takes-holders', value]);
}
/** Render a token row's scope grant honestly (#4043: NULL = grandfathered).
@@ -831,72 +777,115 @@ export function parseRescopeSurfaceValue(value: string): 'verbs' | 'starter' | '
}
async function rescopeClient(clientId: string, args: string[]) {
- if (!clientId) { console.error('Usage: auth rescope-client <client_id> [--profile PROFILE] [grant flags] [--repair] [--dry-run] [--json]'); process.exit(1); }
- try {
- const parsed = parseRescopeGrantArgs(args);
- await withConfiguredSql(async (_sql, engine) => {
- const existing = await readClientGrant(engine, clientId);
- const profile = parsed.profile ? resolveGrantProfile({
- profile: parsed.profile, existing, sourceId: parsed.patch.sourceId ?? existing.sourceId ?? 'default',
- boundTools: parsed.patch.boundTools ?? undefined,
- federatedRead: parsed.patch.federatedRead,
- boundSlugPrefixes: parsed.patch.boundSlugPrefixes,
- delegatedSlugPrefixes: parsed.patch.delegatedSlugPrefixes ?? undefined,
- delegatedNamespace: parsed.patch.delegatedNamespace,
- }) : {};
- const result = await rescopeClientGrant(engine, clientId, { ...profile, ...parsed.patch }, {
- actor: 'operator:cli', expectedRevision: parsed.expectedRevision ?? existing.revision,
- repair: parsed.repair, dryRun: parsed.dryRun,
- });
- if (parsed.json) { console.log(JSON.stringify(result, null, 2)); return; }
- console.log(`OAuth client ${parsed.dryRun ? 'grant preview' : 'rescoped'}: ${result.after.clientName} (${clientId})`);
- console.log(` Revision: ${result.before.revision} -> ${result.after.revision}`);
- console.log(` Scopes: ${result.after.scopes.join(' ') || '<none>'}`);
- console.log(` Write source: ${result.after.sourceId}`);
- console.log(` Federated reads: ${result.after.federatedRead.join(', ')}`);
- console.log(` Tool surface: ${result.after.surface ?? '<server default>'}`);
- console.log(` Delegated spending: ${result.after.budgetUsdPerDay === null ? 'unlimited' : '$' + result.after.budgetUsdPerDay + '/day'}`);
- console.log('Restrictions apply on the next request. Added scopes require a new access token; the client secret is unchanged.');
- });
- } catch (error) {
- console.error('Error:', error instanceof Error ? error.message : String(error));
- process.exit(1);
- }
+ if (!clientId) { console.error('Usage: auth rescope-client <client_id> [--profile PROFILE] [grant flags] [--repair] [--dry-run] [--json] (alias of: gbrain auth rescope --client <client_id>)'); process.exit(1); }
+ await runRescope(['--client', clientId, ...args], parseRescopeGrantArgs);
}
-/** `gbrain auth rescope-token`: the legacy-token twin of rescope-client (src/core/grants/legacy-token.ts). */
+/** `gbrain auth rescope-token`: alias of `gbrain auth rescope --token` (src/core/grants/legacy-token.ts). */
async function rescopeToken(args: string[]) {
+ await runRescope(args, undefined, true);
+}
+
+/**
+ * F3 `gbrain auth rescope`: one grant editor for legacy tokens and OAuth
+ * clients (src/core/grants/cli.ts splits the target). Refusals print the
+ * reason and the next command; with --json they also print a JSON error on
+ * stdout so an agent never has to read stderr.
+ */
+async function runRescope(args: string[], clientParser?: (args: string[]) => RescopeGrantArgs, tokenArgs = false) {
+ const json = args.includes('--json');
try {
- const parsed = parseRescopeTokenArgs(args);
+ const command = tokenArgs ? { kind: 'token' as const, args } : splitRescopeTarget(args);
await withConfiguredSql(async (_sql, engine) => {
- const result = await rescopeLegacyToken(engine, parsed);
- if (parsed.json) { console.log(JSON.stringify(result, null, 2)); return; }
- const verb = !result.changed ? 'grants' : result.dryRun ? 'grant preview' : 'rescoped';
- console.log(`Legacy token ${verb}: ${result.name} (${result.id})`);
- const rows: Array<[string, keyof typeof result.before]> = [['Sources', 'sources'], ['Takes holders', 'takesHolders'], ['Operations', 'operations']];
- for (const [label, key] of rows) {
- const before = renderLegacyGrantAxis(result.before[key]);
- const after = renderLegacyGrantAxis(result.after[key]);
- console.log(` ${label}: ${before === after ? after : `${before} -> ${after}`}`);
+ if (command.kind === 'migrate-legacy') return printMigrateLegacy(await migrateLegacyTokens(engine, { dryRun: command.dryRun }), command.json);
+ const target = command.kind === 'bare' ? await resolveRescopeTarget(engine, command.name) : command.kind === 'client' ? command : { kind: 'token' as const };
+ if (target.kind === 'client') {
+ const clientId = target.clientId;
+ return rescopeClientWith(engine, clientId, clientParser ? clientParser(command.args) : parseClientRescopeArgs(clientId, command.args));
}
- if (result.refresh) {
- const { available, added, unregistered } = result.refresh;
- console.log(` New operations available: ${available.length ? available.join(', ') : 'none'}`);
- if (unregistered.length) console.log(` Granted but no longer registered: ${unregistered.join(', ')}`);
- if (added.length) console.log(` Added: ${added.join(', ')}`);
- else if (available.length) {
- const add = available.length <= 8 ? `--add ${available.join(',')}` : '--add <op,...>';
- console.log(` Nothing widened. Grant them with: gbrain auth rescope-token ${result.name} --refresh-operations ${add} (or --all-new)`);
- }
- }
- if (result.changed && !result.dryRun) console.log('Grants apply on the next request; the token secret is unchanged.');
+ const tokenArgv = command.kind === 'bare' ? [command.name, ...command.args] : command.args;
+ const parsed = parseRescopeTokenArgs(tokenArgv);
+ printTokenRescope(await rescopeLegacyToken(engine, parsed), parsed.json);
});
} catch (error) {
- console.error('Error:', error instanceof Error ? error.message : String(error));
+ const message = error instanceof Error ? error.message : String(error);
+ if (json) {
+ const grantError = error instanceof GrantError ? error : undefined;
+ console.log(JSON.stringify({ error: { code: grantError?.code ?? 'rescope_failed', reasons: grantError?.reasons ?? [], message } }, null, 2));
+ }
+ console.error('Error:', message);
process.exit(1);
}
}
+async function rescopeClientWith(engine: BrainEngine, clientId: string, parsed: RescopeGrantArgs) {
+ const existing = await readClientGrant(engine, clientId);
+ const profile = parsed.profile ? resolveGrantProfile({
+ profile: parsed.profile, existing, sourceId: parsed.patch.sourceId ?? existing.sourceId ?? 'default',
+ boundTools: parsed.patch.boundTools ?? undefined,
+ federatedRead: parsed.patch.federatedRead,
+ boundSlugPrefixes: parsed.patch.boundSlugPrefixes,
+ delegatedSlugPrefixes: parsed.patch.delegatedSlugPrefixes ?? undefined,
+ delegatedNamespace: parsed.patch.delegatedNamespace,
+ }) : {};
+ const result = await rescopeClientGrant(engine, clientId, { ...profile, ...parsed.patch }, {
+ actor: 'operator:cli', expectedRevision: parsed.expectedRevision ?? existing.revision,
+ repair: parsed.repair, dryRun: parsed.dryRun,
+ });
+ if (parsed.json) { console.log(JSON.stringify({ ...result, principal_grant: grantFromClient(result.after) }, null, 2)); return; }
+ console.log(`OAuth client ${parsed.dryRun ? 'grant preview' : 'rescoped'}: ${result.after.clientName} (${clientId})`);
+ console.log(` Revision: ${result.before.revision} -> ${result.after.revision}`);
+ console.log(` Scopes: ${result.after.scopes.join(' ') || '<none>'}`);
+ console.log(` Write source: ${result.after.sourceId}`);
+ console.log(` Federated reads: ${result.after.federatedRead.join(', ')}`);
+ console.log(` Tool surface: ${result.after.surface ?? '<server default>'}`);
+ console.log(` Delegated spending: ${result.after.budgetUsdPerDay === null ? 'unlimited' : '$' + result.after.budgetUsdPerDay + '/day'}`);
+ console.log('Restrictions apply on the next request. Added scopes require a new access token; the client secret is unchanged.');
+}
+
+function printTokenRescope(result: RescopeTokenResult, json: boolean) {
+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }
+ const verb = !result.changed ? 'grants' : result.dryRun ? 'grant preview' : 'rescoped';
+ console.log(`Legacy token ${verb}: ${result.name} (${result.id})`);
+ const rows: Array<[string, keyof typeof result.before]> = [['Sources', 'sources'], ['Takes holders', 'takesHolders'], ['Operations', 'operations']];
+ for (const [label, key] of rows) {
+ const before = renderLegacyGrantAxis(result.before[key]);
+ const after = renderLegacyGrantAxis(result.after[key]);
+ console.log(` ${label}: ${before === after ? after : `${before} -> ${after}`}`);
+ }
+ console.log(` Grant revision: ${result.revision.before === result.revision.after ? result.revision.after : `${result.revision.before} -> ${result.revision.after}`}`);
+ if (result.drift.length && !result.written) {
+ console.log(` Drift: ${result.drift.join(', ')} deny every request (the permissions JSON disagrees with the grant columns). `
+ + `Ask the user which grant is intended, then run gbrain auth rescope --token ${result.name} --adopt-permissions or --adopt-columns.`);
+ }
+ if (result.shape === 'legacy_permissions' && !result.written) {
+ console.log(` Shape: legacy permissions JSON (still enforced). The next grant edit migrates it, or run gbrain auth rescope --migrate-legacy.`);
+ }
+ if (result.migrated) console.log(' Migrated to the unified grant columns; the permissions JSON is kept as a mirror for older gbrain binaries.');
+ if (result.refresh) {
+ const { available, added, unregistered } = result.refresh;
+ console.log(` New operations available: ${available.length ? available.join(', ') : 'none'}`);
+ if (unregistered.length) console.log(` Granted but no longer registered: ${unregistered.join(', ')}`);
+ if (added.length) console.log(` Added: ${added.join(', ')}`);
+ else if (available.length) {
+ const add = available.length <= 8 ? `--add ${available.join(',')}` : '--add <op,...>';
+ console.log(` Nothing widened. Grant them with: gbrain auth rescope --token ${result.name} --refresh-operations ${add} (or --all-new)`);
+ }
+ }
+ if (result.changed && !result.dryRun) console.log('Grants apply on the next request; the token secret is unchanged.');
+}
+
+function printMigrateLegacy(result: MigrateLegacyResult, json: boolean) {
+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }
+ const verb = result.dryRun ? 'Would migrate' : 'Migrated';
+ console.log(`${verb} ${result.migrated.length} legacy token(s) to the unified grant columns; no effective grant changes.`);
+ for (const t of result.migrated) {
+ console.log(` ${t.name} (${t.id}): sources ${renderLegacyGrantAxis(t.grant.sources)}; takes holders ${renderLegacyGrantAxis(t.grant.takesHolders)}; operations ${renderLegacyGrantAxis(t.grant.operations)}`);
+ }
+ for (const t of result.skipped) console.log(` Skipped ${t.name} (${t.id}): ${t.reason}. Fix: ${t.fix}`);
+ if (result.dryRun && result.migrated.length) console.log('Apply with: gbrain auth rescope --migrate-legacy');
+}
+
/**
* E4 (WP4 expansion): `gbrain auth clients [--usage] [--days N] [--json]`.
*
@@ -1126,20 +1115,33 @@ Usage:
gbrain auth list List all tokens (id, scopes, usage)
gbrain auth revoke <name> Revoke a legacy token (ALL active rows with that name)
gbrain auth revoke --id <uuid> Revoke exactly one token by id (names are not unique)
- gbrain auth permissions <name> set-takes-holders <h1,h2,h3>
- Update visibility for an existing token (alias of
- rescope-token --takes-holders)
- gbrain auth rescope-token <name>|--id <uuid> [options] Change a legacy token's grants in place (the token
- twin of rescope-client). Only the flags you pass
- change; the token secret is unchanged. With no
- grant flag it prints the stored grants.
- --sources <id1,id2,...|none> Source grant (first = write source; 'none' = deny-all)
- --takes-holders <h1,h2,...|none> Takes-holder allow-list ('none' = deny-all)
+ gbrain auth rescope --token <name>|--id <uuid>|--client <client_id>|<name> [options]
+ Change a legacy token's or OAuth client's grants in
+ place. Only the flags you pass change; the secret is
+ unchanged. With no grant flag it prints the stored
+ grants. A bare name matching both a token and a
+ client refuses; pass --token or --client.
+ --sources <id1,id2,...|none> Source grant (first = write source; 'none' = deny-all,
+ tokens only — revoke a client with revoke-client)
+ --read-sources <id1,id2,...> Client only: a read set that differs from --sources
+ --takes-holders <h1,h2,...|none> Token only: takes-holder allow-list ('none' = deny-all)
--operations <op1,op2,...|none> Operation snapshot ('none' = deny-all)
- --reset-default <sources,takes-holders,operations> Restore the auth create default for those axes
- --refresh-operations [--add <op,...>|--all-new] Preview operations added since the snapshot; widen only
- by the ones --add names (or all with --all-new)
+ --scopes <read,write,...> Replace the scopes
+ --reset-default <sources,takes-holders,operations> Token only: restore the auth create default for those axes
+ --refresh-operations [--add <op,...>|--all-new] Token only: preview operations added since the snapshot;
+ widen only by the ones --add names (or all with --all-new)
+ --if-version <N> Refuse unless the stored grant revision is N
+ --adopt-permissions | --adopt-columns Token only: resolve grant drift by keeping the permissions
+ JSON (an older gbrain's edit) or restoring the columns
--dry-run / --json Preview without writing / machine-readable output
+ (--json also prints refusals as JSON on stdout)
+ Client-only flags of rescope-client (--surface, --bound-*, --profile, ...) pass through.
+ gbrain auth rescope --migrate-legacy [--dry-run] [--json]
+ Write the unified grant columns for every token still on
+ the permissions-JSON shape; changes no effective grant
+ gbrain auth rescope-token <name>|--id <uuid> [options] Alias of: auth rescope --token <name> [options]
+ gbrain auth permissions <name> set-takes-holders <h1,h2,h3>
+ Alias of: auth rescope --token <name> --takes-holders
gbrain auth register-client <name> [options] Register an OAuth 2.1 client (v0.26+)
--grant-types <client_credentials,authorization_code> (default: client_credentials;
auto-set to authorization_code,refresh_token
@@ -1163,9 +1165,10 @@ Usage:
unavailable to a bound client. Omit = full-source writes.
--bound-max-concurrent <n> Bound submit_agent concurrency (default: 1)
--budget-usd-per-day <usd> Bound submit_agent daily spend cap
- gbrain auth rescope-client <client_id> [options] Change an existing client's source scope (e.g. a DCR
- client stuck on the 'default' source). Only the flags
- you pass change; the other axes are left as-is.
+ gbrain auth rescope-client <client_id> [options] Alias of: auth rescope --client <client_id>, with these
+ legacy flags. Change an existing client's source scope
+ (e.g. a DCR client stuck on the 'default' source). Only
+ the flags you pass change; the other axes are left as-is.
--source <id> New write source
--federated-read <id1,id2,...> New read-scope source list
--bound-slug-prefixes <p1,p2|none> Replace the slug-prefix write fence ('none' clears it)
@@ -1228,6 +1231,7 @@ export async function runAuth(args: string[]): Promise<void> {
case 'register-client': await registerClient(rest[0], rest.slice(1)); return;
case 'rescope-client': await rescopeClient(rest[0], rest.slice(1)); return;
case 'rescope-token': await rescopeToken(rest); return;
+ case 'rescope': await runRescope(rest); return;
case 'revoke-client': await revokeClient(rest[0]); return;
case 'clients': await clientsCmd(rest); return;
case 'test': {
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index b317c262d5..8e949a2ea0 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -18,7 +18,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--yes'],
- 'auth': ['--add', '--admin-intent', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--no-pull', '--operations', '--path', '--probe', '--profile', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
@@ -46,7 +46,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
- 'doctor': ['--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--operations', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
@@ -74,8 +74,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--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': ['--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', '--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-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--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', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--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'],
+ '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', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--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'],
'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', '--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'],
'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
@@ -102,7 +102,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--add', '--admin-intent', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
+ 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -115,11 +115,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--add', '--admin-intent', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
+ 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/grants/cli.ts b/src/core/grants/cli.ts
index 777028f545..3038e8d8a4 100644
--- a/src/core/grants/cli.ts
+++ b/src/core/grants/cli.ts
@@ -1,4 +1,4 @@
-import { GRANT_PROFILES, GrantError, type GrantPatch, type GrantProfileId } from './model.ts';
+import { GRANT_PROFILES, GrantError, validatePrincipalGrant, type GrantPatch, type GrantProfileId } from './model.ts';
import { parseScopeString, assertAllowedScopes } from '../scope.ts';
export interface RescopeGrantArgs {
@@ -11,6 +11,12 @@ export interface RescopeGrantArgs {
}
export function parseRescopeGrantArgs(args: string[]): RescopeGrantArgs {
+ const result = parseRescopeGrantFlags(args);
+ if (!result.profile && Object.keys(result.patch).length === 0) throw new GrantError('invalid_grant', 'Pass a grant field or --profile to rescope');
+ return result;
+}
+
+function parseRescopeGrantFlags(args: string[]): RescopeGrantArgs {
const result: RescopeGrantArgs = { patch: {}, repair: false, dryRun: false, json: false };
const csv = (value: string): string[] => value.split(',').map(s => s.trim()).filter(Boolean);
for (let i = 0; i < args.length; i++) {
@@ -53,6 +59,109 @@ export function parseRescopeGrantArgs(args: string[]): RescopeGrantArgs {
default: throw new GrantError('invalid_grant', `Unknown flag: ${flag}`);
}
}
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// F3: `gbrain auth rescope`, one command for legacy tokens and OAuth clients.
+// ---------------------------------------------------------------------------
+
+export type RescopeCommand =
+ | { kind: 'migrate-legacy'; dryRun: boolean; json: boolean }
+ | { kind: 'token'; args: string[] }
+ | { kind: 'client'; clientId: string; args: string[] }
+ | { kind: 'bare'; name: string; args: string[] };
+
+const BOOLEAN_FLAGS = new Set(['--dry-run', '--json', '--refresh-operations', '--all-new', '--adopt-permissions', '--adopt-columns', '--repair']);
+const TARGET_USAGE = 'Name what to rescope: --token <name>, --id <uuid>, --client <client-id>, a bare token or client name, or --migrate-legacy';
+
+/** Split the target off `auth rescope` args; the remaining flags go to the token or client parser. */
+export function splitRescopeTarget(args: string[]): RescopeCommand {
+ const targets: { token?: string; id?: string; client?: string; bare?: string } = {};
+ const rest: string[] = [];
+ let migrate = false;
+ for (let i = 0; i < args.length; i++) {
+ const flag = args[i];
+ if (flag === '--migrate-legacy') { migrate = true; continue; }
+ if (flag === '--token' || flag === '--id' || flag === '--client') {
+ const value = args[++i];
+ if (value === undefined || value.startsWith('--')) throw new GrantError('invalid_grant', `${flag} requires a value`);
+ targets[flag.slice(2) as 'token' | 'id' | 'client'] = value;
+ continue;
+ }
+ if (!flag.startsWith('--')) {
+ if (targets.bare !== undefined) throw new GrantError('invalid_grant', `Unexpected argument: ${flag}`);
+ targets.bare = flag;
+ continue;
+ }
+ rest.push(flag);
+ if (!BOOLEAN_FLAGS.has(flag) && args[i + 1] !== undefined) rest.push(args[++i]);
+ }
+ const named = Object.values(targets).filter(v => v !== undefined).length;
+ if (migrate) {
+ if (named) throw new GrantError('invalid_grant', '--migrate-legacy migrates every unmigrated token; it takes no target');
+ const extra = rest.filter(f => f !== '--dry-run' && f !== '--json');
+ if (extra.length) throw new GrantError('invalid_grant', `--migrate-legacy changes no grant, so it takes only --dry-run and --json (got ${extra.join(' ')})`);
+ return { kind: 'migrate-legacy', dryRun: rest.includes('--dry-run'), json: rest.includes('--json') };
+ }
+ if (named !== 1) throw new GrantError('invalid_grant', named ? `Pass exactly one target. ${TARGET_USAGE}` : TARGET_USAGE);
+ if (targets.token !== undefined) return { kind: 'token', args: [targets.token, ...rest] };
+ if (targets.id !== undefined) return { kind: 'token', args: ['--id', targets.id, ...rest] };
+ if (targets.client !== undefined) return { kind: 'client', clientId: targets.client, args: rest };
+ return { kind: 'bare', name: targets.bare as string, args: rest };
+}
+
+const TOKEN_ONLY_FLAGS: Record<string, string> = {
+ '--takes-holders': 'client_takes_holders_unsupported',
+ '--reset-default': 'client_reset_default_unsupported',
+ '--refresh-operations': 'client_refresh_operations_unsupported',
+ '--add': 'client_refresh_operations_unsupported',
+ '--all-new': 'client_refresh_operations_unsupported',
+ '--adopt-permissions': 'client_adopt_unsupported',
+ '--adopt-columns': 'client_adopt_unsupported',
+};
+
+/**
+ * Client flags of `auth rescope --client`: the unified `--sources a,b`
+ * (element 0 = write source, the list = read set unless `--read-sources`
+ * names a different one), `--read-sources`, `--operations a,b|none` and every
+ * `auth rescope-client` flag. `--sources none` refuses (decision 4: client
+ * deny-all is `auth revoke-client`).
+ */
+export function parseClientRescopeArgs(clientId: string, args: string[]): RescopeGrantArgs {
+ const legacy: string[] = [];
+ let sources: string[] | undefined;
+ let readSources: string[] | undefined;
+ let operations: string[] | undefined;
+ const csv = (value: string): string[] => [...new Set(value.split(',').map(s => s.trim()).filter(Boolean))];
+ for (let i = 0; i < args.length; i++) {
+ const flag = args[i];
+ if (TOKEN_ONLY_FLAGS[flag]) {
+ throw new GrantError('invalid_grant', `${flag} applies to legacy tokens only; OAuth client ${clientId} has no such grant in this release (see gbrain auth rescope --help)`, [TOKEN_ONLY_FLAGS[flag]]);
+ }
+ if (!['--sources', '--read-sources', '--operations'].includes(flag)) {
+ legacy.push(flag);
+ if (!BOOLEAN_FLAGS.has(flag) && args[i + 1] !== undefined) legacy.push(args[++i]);
+ continue;
+ }
+ const value = args[++i];
+ if (value === undefined || value.startsWith('--')) throw new GrantError('invalid_grant', `${flag} requires a value`);
+ if (flag === '--sources') sources = value === 'none' ? [] : csv(value);
+ if (flag === '--read-sources') readSources = csv(value);
+ if (flag === '--operations') operations = value === 'none' ? [] : csv(value);
+ }
+ const result = parseRescopeGrantFlags(legacy);
+ if (sources !== undefined) {
+ validatePrincipalGrant({
+ principal: { kind: 'oauth_client', id: clientId }, scopes: [], allowedOperations: null, takesHolders: null, revision: 0,
+ shape: 'unified', drift: [], permissionsMalformed: false,
+ sources: sources.length === 0 ? { kind: 'none' } : { kind: 'federated', writeSource: sources[0], readSources: sources },
+ }, { operationNames: new Set() });
+ result.patch.sourceId = sources[0];
+ }
+ if (readSources !== undefined && readSources.length === 0) throw new GrantError('invalid_grant', '--read-sources needs at least one source id');
+ if (sources !== undefined || readSources !== undefined) result.patch.federatedRead = readSources ?? sources;
+ if (operations !== undefined) result.patch.allowedOperations = operations;
if (!result.profile && Object.keys(result.patch).length === 0) throw new GrantError('invalid_grant', 'Pass a grant field or --profile to rescope');
return result;
}
diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.ts
index c465060db1..6cabbaf834 100644
--- a/src/core/grants/legacy-token.ts
+++ b/src/core/grants/legacy-token.ts
@@ -1,39 +1,54 @@
/**
- * Legacy bearer-token grants (`gbrain auth rescope-token`), the token twin of
- * `auth rescope-client`. Three axes live in `access_tokens.permissions`:
+ * Legacy bearer-token grants (`gbrain auth rescope --token`, alias
+ * `auth rescope-token`), the token twin of `auth rescope --client`. Three axes:
*
- * - `source_id` (`--sources a,b|none`): array, element 0 = write source
- * - `takes_holders` (`--takes-holders a,b|none`)
- * - `allowed_operations` (`--operations a,b|none`, `--refresh-operations`)
+ * - sources (`--sources a,b|none`): element 0 = write source
+ * - takes holders (`--takes-holders a,b|none`)
+ * - operations (`--operations a,b|none`, `--refresh-operations`)
*
* `none` stores the explicit empty list (deny-all). An omitted flag preserves
* the stored value. `--reset-default <axes>` restores the `auth create`
* default for the named axes (no source grant → the historical `default`
- * floor; takes holders `['world']`; no operation snapshot). Every other key in
- * `permissions` is preserved. `--refresh-operations` only previews unless
- * `--add <op,...>` or `--all-new` names the operations to widen by. With no
- * grant flag the command only prints the stored grants.
+ * floor; takes holders `['world']`; no operation snapshot).
+ * `--refresh-operations` only previews unless `--add <op,...>` or `--all-new`
+ * names the operations to widen by. With no grant flag the command only prints
+ * the stored grants.
+ *
+ * F3 storage: every write lands in the unified columns (`source_grant`,
+ * `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.
*/
import type { BrainEngine } from '../engine.ts';
-import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyOperationGrant, parseLegacyTokenScope, parseTakesHoldersAllowList } from '../legacy-token-scope.ts';
-import { NO_SOURCES, isValidSourceId } from '../source-id.ts';
-import { operationScopesAllowed } from '../scope.ts';
+import { assertAllowedScopes, operationScopesAllowed } from '../scope.ts';
+import { isValidSourceId } from '../source-id.ts';
import { executeRawJsonb } from '../sql-query.ts';
import { TOKEN_ID_RE } from '../token-mint.ts';
-import { GrantError } from './model.ts';
+import { isUndefinedColumnError } from '../utils.ts';
+import {
+ GrantError, LEGACY_GRANT_AXES, grantFromTokenRow, permissionsMirror, tokenGrantColumnValues, tokenGrantFromColumns,
+ tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant,
+} from './model.ts';
+
+export type { LegacyGrantAxis } from './model.ts';
-export type LegacyGrantAxis = 'sources' | 'takes-holders' | 'operations';
-const AXES: readonly LegacyGrantAxis[] = ['sources', 'takes-holders', 'operations'];
+type TokenGrantAxes = Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>;
export interface RescopeTokenArgs {
target: { name: string } | { id: string };
sources?: string[];
takesHolders?: string[];
operations?: string[];
+ scopes?: string[];
reset: LegacyGrantAxis[];
refreshOperations: boolean;
add?: string[];
allNew: boolean;
+ adopt?: 'permissions' | 'columns';
+ expectedRevision?: number;
dryRun: boolean;
json: boolean;
}
@@ -51,6 +66,13 @@ export interface RescopeTokenResult {
changed: boolean;
before: LegacyTokenGrantView;
after: LegacyTokenGrantView;
+ /** Grant shape before this call; `migrated` is true when this call wrote the unified columns for the first time. */
+ shape: PrincipalGrant['shape'];
+ migrated: boolean;
+ written: boolean;
+ revision: { before: number; after: number };
+ /** Axes that were drifted (deny-all) before this call. */
+ drift: LegacyGrantAxis[];
refresh?: { available: string[]; added: string[]; unregistered: string[] };
}
@@ -60,12 +82,18 @@ const csvOrNone = (value: string): string[] =>
export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {
let target: RescopeTokenArgs['target'] | undefined;
const out: Omit<RescopeTokenArgs, 'target'> = { reset: [], refreshOperations: false, allNew: false, dryRun: false, json: false };
+ const adopt = (mode: 'permissions' | 'columns') => {
+ if (out.adopt && out.adopt !== mode) throw new GrantError('invalid_grant', 'Pass either --adopt-permissions or --adopt-columns, not both');
+ out.adopt = mode;
+ };
for (let i = 0; i < args.length; i++) {
const flag = args[i];
if (flag === '--dry-run') { out.dryRun = true; continue; }
if (flag === '--json') { out.json = true; continue; }
if (flag === '--refresh-operations') { out.refreshOperations = true; continue; }
if (flag === '--all-new') { out.allNew = true; continue; }
+ if (flag === '--adopt-permissions') { adopt('permissions'); continue; }
+ if (flag === '--adopt-columns') { adopt('columns'); continue; }
if (!flag.startsWith('--')) {
if (target) throw new GrantError('invalid_grant', `Unexpected argument: ${flag}`);
target = { name: flag };
@@ -83,9 +111,18 @@ export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {
case '--takes-holders': out.takesHolders = csvOrNone(value); break;
case '--operations': out.operations = csvOrNone(value); break;
case '--add': out.add = csvOrNone(value); break;
+ case '--scopes':
+ out.scopes = csvOrNone(value.replaceAll(' ', ','));
+ if (out.scopes.length === 0) throw new GrantError('invalid_grant', '--scopes needs at least one scope (to cut a token off, use --sources none or gbrain auth revoke)');
+ assertAllowedScopes(out.scopes);
+ break;
+ case '--if-version':
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value))) throw new GrantError('invalid_grant', '--if-version must be a non-negative integer');
+ out.expectedRevision = Number(value);
+ break;
case '--reset-default':
for (const axis of csvOrNone(value)) {
- if (!(AXES as readonly string[]).includes(axis)) throw new GrantError('invalid_grant', `--reset-default takes ${AXES.join(', ')}`);
+ if (!(LEGACY_GRANT_AXES as readonly string[]).includes(axis)) throw new GrantError('invalid_grant', `--reset-default takes ${LEGACY_GRANT_AXES.join(', ')}`);
out.reset.push(axis as LegacyGrantAxis);
}
break;
@@ -105,14 +142,12 @@ export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {
return { target, ...out };
}
-function view(permissions: Record<string, unknown>): LegacyTokenGrantView {
- const scope = parseLegacyTokenScope(permissions.source_id);
- const operations = parseLegacyOperationGrant(permissions.allowed_operations);
+function grantView(g: TokenGrantAxes): LegacyTokenGrantView {
+ const s = g.sources;
return {
- sources: permissions.source_id == null ? 'default'
- : scope.sourceId === NO_SOURCES ? [] : scope.allowedSources ?? [scope.sourceId],
- takesHolders: parseTakesHoldersAllowList(permissions.takes_holders) ?? ['world'],
- operations: operations ?? 'unrestricted',
+ sources: s.kind === 'default' ? 'default' : s.kind === 'none' ? [] : s.kind === 'scalar' ? [s.writeSource] : [...s.readSources],
+ takesHolders: g.takesHolders ?? ['world'],
+ operations: g.allowedOperations ?? 'unrestricted',
};
}
@@ -138,54 +173,171 @@ async function assertActiveSources(engine: BrainEngine, ids: string[]): Promise<
if (missing.length) throw new GrantError('invalid_grant', `Unknown or archived source: ${missing.join(', ')} (see gbrain sources list)`);
}
+const SCHEMA_HINT = 'this brain predates the unified token grant columns (access_tokens.source_grant); run `gbrain apply-migrations --yes` (no user decision needed), then retry';
+
+function schemaError(error: unknown): unknown {
+ return ['source_grant', 'grant_revision', ...TOKEN_GRANT_COLUMNS].some(c => isUndefinedColumnError(error, c)) ? new GrantError('grant_schema_required', SCHEMA_HINT) : error;
+}
+
+/** Write the unified columns and the `permissions` mirror in one UPDATE; returns the new revision. */
+async function writeTokenGrant(tx: BrainEngine, row: Record<string, unknown>, grant: TokenGrantAxes, scopes?: string[]): Promise<number> {
+ const [written] = await executeRawJsonb<{ grant_revision: number }>(
+ tx,
+ `UPDATE access_tokens SET source_grant = $2, source_id = $3, federated_read = $4::text[], allowed_operations = $5::text[],
+ takes_holders = $6::text[], scopes = COALESCE($7::text[], scopes), grant_revision = grant_revision + 1, permissions = $8::jsonb
+ WHERE id = $1::uuid RETURNING grant_revision`,
+ [String(row.id), ...tokenGrantColumnValues(grant), scopes === undefined ? null : `{${scopes.join(',')}}`],
+ [permissionsMirror(grant, row.permissions)],
+ );
+ return Number(written.grant_revision);
+}
+
+function driftRefusal(name: string, id: string, axes: readonly LegacyGrantAxis[]): GrantError {
+ return new GrantError('invalid_grant',
+ `Token "${name}" (${id}) has grant drift on ${axes.join(', ')}: its permissions JSON disagrees with the grant columns `
+ + '(an older gbrain edited the JSON after migration), so those axes deny every request. Ask the user which grant is intended, then run '
+ + `gbrain auth rescope --token ${name} --adopt-permissions (keep the JSON edit) or gbrain auth rescope --token ${name} --adopt-columns `
+ + '(restore the columns), and retry.', ['legacy_token_grant_drift']);
+}
+
export async function rescopeLegacyToken(engine: BrainEngine, args: RescopeTokenArgs): Promise<RescopeTokenResult> {
- return engine.transaction(async tx => {
- const rows = 'id' in args.target
- ? await tx.executeRaw<Record<string, unknown>>('SELECT id, name, scopes, permissions FROM access_tokens WHERE id = $1::uuid AND revoked_at IS NULL FOR UPDATE', [args.target.id])
- : await tx.executeRaw<Record<string, unknown>>('SELECT id, name, scopes, permissions FROM access_tokens WHERE name = $1 AND revoked_at IS NULL FOR UPDATE', [args.target.name]);
- const label = 'id' in args.target ? `id ${args.target.id}` : `"${args.target.name}"`;
- if (rows.length === 0) throw new GrantError('invalid_grant', `No active token ${label} (see gbrain auth list)`);
- if (rows.length > 1) throw new GrantError('invalid_grant', `${rows.length} active tokens are named ${label}; pass --id <uuid> from gbrain auth list`);
- const row = rows[0];
- const current = coerceLegacyPermissions(row.permissions) ?? {};
- const next: Record<string, unknown> = { ...current };
-
- if (args.sources !== undefined) {
- await assertActiveSources(tx, args.sources);
- next.source_id = args.sources;
- }
- if (args.takesHolders !== undefined) next.takes_holders = args.takesHolders;
- let refresh: RescopeTokenResult['refresh'];
- const { all, grantable } = await grantableOperations(normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin']);
- if (args.operations !== undefined) {
- const unknown = args.operations.filter(op => !all.has(op));
- if (unknown.length) throw new GrantError('invalid_grant', `Unknown remote operation: ${unknown.join(', ')}`);
- next.allowed_operations = args.operations;
- }
- for (const axis of args.reset) {
- if (axis === 'sources') delete next.source_id;
- if (axis === 'takes-holders') next.takes_holders = ['world'];
- if (axis === 'operations') delete next.allowed_operations;
+ try {
+ return await engine.transaction(tx => rescopeInTransaction(tx, args));
+ } catch (error) {
+ throw schemaError(error);
+ }
+}
+
+async function rescopeInTransaction(tx: BrainEngine, args: RescopeTokenArgs): Promise<RescopeTokenResult> {
+ const rows = 'id' in args.target
+ ? await tx.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id = $1::uuid AND revoked_at IS NULL FOR UPDATE', [args.target.id])
+ : await tx.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE name = $1 AND revoked_at IS NULL FOR UPDATE', [args.target.name]);
+ const label = 'id' in args.target ? `id ${args.target.id}` : `"${args.target.name}"`;
+ if (rows.length === 0) throw new GrantError('invalid_grant', `No active token ${label} (see gbrain auth list)`);
+ if (rows.length > 1) throw new GrantError('invalid_grant', `${rows.length} active tokens are named ${label}; pass --id <uuid> from gbrain auth list`);
+ const row = rows[0];
+ const id = String(row.id);
+ const name = String(row.name);
+ const current = grantFromTokenRow(row);
+ if (args.expectedRevision !== undefined && current.revision !== args.expectedRevision) {
+ throw new GrantError('grant_conflict', `Token "${name}" is at grant revision ${current.revision}, not ${args.expectedRevision}: someone changed it since you read it. `
+ + `Re-read it with gbrain auth rescope --token ${name} --json, then retry with --if-version ${current.revision}.`);
+ }
+ if (args.adopt === 'columns' && current.shape !== 'unified') {
+ throw new GrantError('invalid_grant', `Token "${name}" has no grant columns yet, so there is nothing to adopt; its permissions JSON is the grant. Migrate it with gbrain auth rescope --migrate-legacy.`);
+ }
+ let base: TokenGrantAxes = current;
+ if (args.adopt === 'permissions') {
+ const { malformed: _, ...parsed } = tokenGrantFromPermissions(row.permissions);
+ base = parsed;
+ } else if (args.adopt === 'columns') {
+ base = tokenGrantFromColumns(row);
+ }
+
+ const next: TokenGrantAxes = { ...base };
+ if (args.sources !== undefined) {
+ await assertActiveSources(tx, args.sources);
+ next.sources = args.sources.length === 0 ? { kind: 'none' } : { kind: 'federated', writeSource: args.sources[0], readSources: args.sources };
+ }
+ if (args.takesHolders !== undefined) next.takesHolders = args.takesHolders;
+ const { all, grantable } = await grantableOperations(args.scopes ?? current.scopes);
+ if (args.operations !== undefined) {
+ const unknown = args.operations.filter(op => !all.has(op));
+ if (unknown.length) throw new GrantError('invalid_grant', `Unknown remote operation: ${unknown.join(', ')}`);
+ next.allowedOperations = args.operations;
+ }
+ for (const axis of args.reset) {
+ if (axis === 'sources') next.sources = { kind: 'default' };
+ if (axis === 'takes-holders') next.takesHolders = ['world'];
+ if (axis === 'operations') next.allowedOperations = null;
+ }
+ let refresh: RescopeTokenResult['refresh'];
+ if (args.refreshOperations) {
+ const granted = base.allowedOperations;
+ if (granted === null) {
+ throw new GrantError('invalid_grant', `Token ${label} has no operation snapshot, so it already reaches every operation its scopes allow; nothing to refresh`);
}
- if (args.refreshOperations) {
- const granted = parseLegacyOperationGrant(current.allowed_operations);
- if (granted === undefined) {
- throw new GrantError('invalid_grant', `Token ${label} has no operation snapshot, so it already reaches every operation its scopes allow; nothing to refresh`);
+ const available = grantable.filter(op => !granted.includes(op));
+ const added = args.allNew ? available : args.add ?? [];
+ const notAvailable = added.filter(op => !available.includes(op));
+ if (notAvailable.length) throw new GrantError('invalid_grant', `Not a new operation for this token: ${notAvailable.join(', ')} (run --refresh-operations alone to preview)`);
+ if (added.length) next.allowedOperations = [...granted, ...added];
+ refresh = { available, added, unregistered: granted.filter(op => !all.has(op)) };
+ }
+ const opsEdited = args.operations !== undefined || Boolean(refresh?.added.length);
+ validatePrincipalGrant({
+ ...current, ...next,
+ sources: args.sources !== undefined ? next.sources : { kind: 'default' },
+ allowedOperations: opsEdited ? next.allowedOperations : null,
+ }, { operationNames: all });
+
+ const edits = args.sources !== undefined || args.takesHolders !== undefined || opsEdited || args.reset.length > 0 || args.scopes !== undefined;
+ if (edits && !args.adopt && current.drift.length) throw driftRefusal(name, id, current.drift);
+ const before = grantView(current);
+ const after = grantView(next);
+ const changed = JSON.stringify(before) !== JSON.stringify(after)
+ || (args.scopes !== undefined && JSON.stringify(args.scopes) !== JSON.stringify(current.scopes));
+ const write = !args.dryRun && (edits || Boolean(args.adopt));
+ const revision = write ? await writeTokenGrant(tx, row, next, args.scopes) : current.revision;
+ return {
+ id, name, dryRun: args.dryRun, changed, before, after,
+ shape: current.shape, migrated: write && current.shape === 'legacy_permissions', written: write,
+ revision: { before: current.revision, after: revision }, drift: current.drift,
+ ...(refresh ? { refresh } : {}),
+ };
+}
+
+export interface MigrateLegacyResult {
+ dryRun: boolean;
+ migrated: Array<{ id: string; name: string; grant: LegacyTokenGrantView }>;
+ skipped: Array<{ id: string; name: string; reason: 'permissions_malformed'; fix: string }>;
+}
+
+/**
+ * `auth rescope --migrate-legacy`: write the unified columns for every active
+ * token still on the JSONB-only shape, without changing any effective grant.
+ * A malformed `permissions` value has no column equivalent (the HTTP paths
+ * read it as no grant while publication denies it), so it is skipped and
+ * reported with the command that gives it an explicit grant.
+ */
+export async function migrateLegacyTokens(engine: BrainEngine, opts: { dryRun: boolean }): Promise<MigrateLegacyResult> {
+ try {
+ return await engine.transaction(async tx => {
+ const rows = await tx.executeRaw<Record<string, unknown>>(
+ 'SELECT * FROM access_tokens WHERE revoked_at IS NULL AND source_grant IS NULL ORDER BY created_at, id FOR UPDATE');
+ const result: MigrateLegacyResult = { dryRun: opts.dryRun, migrated: [], skipped: [] };
+ for (const row of rows) {
+ const grant = grantFromTokenRow(row);
+ const entry = { id: String(row.id), name: String(row.name) };
+ if (grant.permissionsMalformed) {
+ result.skipped.push({ ...entry, reason: 'permissions_malformed',
+ fix: `ask the user which grant this token should hold, then run gbrain auth rescope --id ${entry.id} --reset-default sources,takes-holders,operations (or pass explicit --sources/--takes-holders/--operations)` });
+ continue;
+ }
+ if (!opts.dryRun) await writeTokenGrant(tx, row, grant);
+ result.migrated.push({ ...entry, grant: grantView(grant) });
}
- const available = grantable.filter(op => !granted.includes(op));
- const added = args.allNew ? available : args.add ?? [];
- const notAvailable = added.filter(op => !available.includes(op));
- if (notAvailable.length) throw new GrantError('invalid_grant', `Not a new operation for this token: ${notAvailable.join(', ')} (run --refresh-operations alone to preview)`);
- if (added.length) next.allowed_operations = [...granted, ...added];
- refresh = { available, added, unregistered: granted.filter(op => !all.has(op)) };
- }
+ return result;
+ });
+ } catch (error) {
+ throw schemaError(error);
+ }
+}
- const changed = JSON.stringify(next) !== JSON.stringify(current);
- if (changed && !args.dryRun) {
- await executeRawJsonb(tx, 'UPDATE access_tokens SET permissions = $2::jsonb WHERE id = $1::uuid', [String(row.id)], [next]);
- }
- return { id: String(row.id), name: String(row.name), dryRun: args.dryRun, changed, before: view(current), after: view(next), ...(refresh ? { refresh } : {}) };
- });
+/** 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]);
+ const clients = await engine.executeRaw<{ client_id: string }>(
+ 'SELECT client_id FROM oauth_clients WHERE (client_id = $1 OR client_name = $1) AND deleted_at IS NULL', [name]);
+ if (tokens.length && clients.length) {
+ throw new GrantError('invalid_grant', `"${name}" names both a legacy token and an OAuth client; pass --token ${name} or --client ${clients[0].client_id}`, ['rescope_target_ambiguous']);
+ }
+ if (clients.length > 1) {
+ throw new GrantError('invalid_grant', `"${name}" names ${clients.length} OAuth clients (${clients.map(c => c.client_id).join(', ')}); pass --client <client-id> from gbrain auth clients`, ['rescope_target_ambiguous']);
+ }
+ if (clients.length === 1) return { kind: 'client', clientId: clients[0].client_id };
+ if (tokens.length) return { kind: 'token' };
+ throw new GrantError('invalid_grant', `No active token or OAuth client named "${name}" (see gbrain auth list and gbrain auth clients)`);
}
export function renderLegacyGrantAxis(value: string[] | 'default' | 'unrestricted'): string {
diff --git a/src/core/token-mint.ts b/src/core/token-mint.ts
index 3db41989c0..bf133e9266 100644
--- a/src/core/token-mint.ts
+++ b/src/core/token-mint.ts
@@ -5,9 +5,10 @@
*
* Least-privilege by construction: scopes land in the original-schema
* `access_tokens.scopes TEXT[]` column (structurally immune to the
- * permissions-object-replacement wipe class), and the federation grant rides
- * `permissions.source_id` as an array (element 0 = write floor — the
- * parseLegacyTokenScope contract).
+ * permissions-object-replacement wipe class). F3: the grant lands in the
+ * unified columns (source_grant, source_id, federated_read,
+ * allowed_operations, takes_holders) with a `permissions` JSONB mirror for
+ * older binaries; the federation grant is an array, element 0 = write floor.
*
* Rotation contract [C7]: mint FIRST, revoke the previous token BY ID only
* after the new one is wired and smoke-tested. revokeLegacyTokenById never
@@ -19,7 +20,7 @@ import type { BrainEngine } from './engine.ts';
import { ALLOWED_SCOPES_LIST, assertAllowedScopes } from './scope.ts';
import { executeRawJsonb, type SqlQuery } from './sql-query.ts';
import { generateToken, hashToken, isUndefinedColumnError } from './utils.ts';
-import { coerceLegacyPermissions, parseLegacyOperationGrant, parseTakesHoldersAllowList } from './legacy-token-scope.ts';
+import { permissionsMirror, tokenGrantColumnValues, tokenGrantFromPermissions, TOKEN_GRANT_COLUMNS, type GrantSources, type PrincipalGrant } from './grants/model.ts';
/** Canonical token-id shape — shared with the `auth revoke --id` CLI gate. */
export const TOKEN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -74,27 +75,54 @@ export async function mintLegacyToken(
}
}
const token = generateToken('gbrain_');
- const hash = hashToken(token);
- const permissions: Record<string, unknown> = { takes_holders: opts.takesHolders };
- if (opts.sourceGrant !== undefined) permissions.source_id = opts.sourceGrant;
- if (opts.allowedOperations !== undefined) permissions.allowed_operations = [...new Set(opts.allowedOperations)];
+ const sources: GrantSources = opts.sourceGrant === undefined ? { kind: 'default' }
+ : opts.sourceGrant.length === 0 ? { kind: 'none' }
+ : { kind: 'federated', writeSource: opts.sourceGrant[0], readSources: [...opts.sourceGrant] };
+ const rows = await insertUnifiedToken(engine, {
+ name: opts.name, tokenHash: hashToken(token), scopes: opts.scopes,
+ grant: { sources, takesHolders: opts.takesHolders, allowedOperations: opts.allowedOperations === undefined ? null : [...new Set(opts.allowedOperations)] },
+ });
+ const id = rows[0]?.id;
+ if (!id) throw new Error('token insert returned no id');
+ return { token, id, name: opts.name, scopes: [...opts.scopes] };
+}
- // Scopes bind as a Postgres array literal through a TEXT param + ::text[]
- // cast — values are allowlisted ([a-z_]+), so the literal needs no quoting,
- // and the same SQL runs on both engines (a bare JS array param would bind
- // engine-dependently; the JSONB object goes through executeRawJsonb per the
- // repo invariant).
- const scopesLiteral = `{${opts.scopes.join(',')}}`;
- let rows: Array<{ id: string }>;
+/**
+ * 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.
+ */
+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 {
- rows = await executeRawJsonb<{ id: string }>(
- engine,
- `INSERT INTO access_tokens (name, token_hash, permissions, scopes)
- VALUES ($1, $2, $4::jsonb, $3::text[])
- RETURNING id`,
- [opts.name, hash, scopesLiteral],
- [permissions],
- );
+ 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],
+ );
+ }
} catch (e) {
// isUndefinedColumnError also matches message-shaped variants — some
// driver-wrapped errors drop the SQLSTATE code.
@@ -106,9 +134,6 @@ export async function mintLegacyToken(
}
throw e;
}
- const id = rows[0]?.id;
- if (!id) throw new Error('token insert returned no id');
- return { token, id, name: opts.name, scopes: [...opts.scopes] };
}
/**
@@ -136,18 +161,25 @@ export async function revokeLegacyTokenById(sql: SqlQuery, id: string): Promise<
* as stored, narrowed to the operations this run would grant, plus only the
* operations a skills-policy change adds; `[]` stays `[]`. Operations new
* since the snapshot are withheld (reported, never silently granted): widen
- * with `gbrain auth rescope-token <name> --refresh-operations`.
+ * with `gbrain auth rescope --token <name> --refresh-operations`.
+ *
+ * F3: the prior grant is read from its `permissions` JSONB through the shared
+ * parser. On a unified row that JSONB mirrors the columns. On a drifted row
+ * (an older gbrain edited the JSONB after migration) the edit is the newest
+ * operator intent, so rotation carries it, the same resolution as
+ * `auth rescope --adopt-permissions`; the replacement is born unified and the
+ * drifted row is revoked after the swap.
*/
export function carryLegacyGrant(priorRaw: unknown, fresh: {
sourceGrant?: string[]; explicitSource: boolean; allowedOperations: string[]; policyAdded: string[];
}): { takesHolders: string[]; sourceGrant?: string[]; allowedOperations: string[]; withheldOperations: string[] } {
- const prior = coerceLegacyPermissions(priorRaw) ?? {};
- const takesHolders = parseTakesHoldersAllowList(prior.takes_holders) ?? ['world'];
- const storedSource = Array.isArray(prior.source_id)
- ? prior.source_id.filter((s): s is string => typeof s === 'string' && s.length > 0)
- : typeof prior.source_id === 'string' && prior.source_id.length > 0 ? [prior.source_id] : undefined;
+ const prior = tokenGrantFromPermissions(priorRaw);
+ const takesHolders = prior.takesHolders ?? ['world'];
+ const stored = prior.sources;
+ const storedSource = stored.kind === 'default' ? undefined : stored.kind === 'none' ? []
+ : stored.kind === 'scalar' ? [stored.writeSource] : stored.readSources;
const sourceGrant = fresh.explicitSource || storedSource === undefined ? fresh.sourceGrant : storedSource;
- const priorOps = parseLegacyOperationGrant(prior.allowed_operations);
+ const priorOps = prior.allowedOperations ?? undefined;
if (priorOps === undefined) return { takesHolders, sourceGrant, allowedOperations: fresh.allowedOperations, withheldOperations: [] };
const allowedOperations = priorOps.length === 0 ? [] : [...new Set([
...priorOps.filter(op => fresh.allowedOperations.includes(op)), ...fresh.policyAdded,
diff --git a/test/e2e/persistence-http-liveness.test.ts b/test/e2e/persistence-http-liveness.test.ts
index c7d5130b99..1b8a760524 100644
--- a/test/e2e/persistence-http-liveness.test.ts
+++ b/test/e2e/persistence-http-liveness.test.ts
@@ -97,7 +97,8 @@ describe.skipIf(!url)('authenticated PostgreSQL HTTP accepted-write liveness', (
GBRAIN_MCP_FORCE_SURFACE: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_REMOTE_PRIVATE_PAGES: undefined });
const legacy = cli(['auth', 'create', 'synthetic-http-writer', '--scopes', 'read,write']);
tokens.push(legacy.match(/gbrain_[a-f0-9]{64}/)![0]);
- await pg.engine.executeRaw("UPDATE access_tokens SET permissions=jsonb_set(COALESCE(permissions,'{}'::jsonb),'{source_id}',to_jsonb($1::text)) WHERE name='synthetic-http-writer'", [config.sourceIds[0]]);
+ // F3: grant through the editor; a raw JSONB edit on a unified token reads as drift and denies.
+ cli(['auth', 'rescope', '--token', 'synthetic-http-writer', '--sources', config.sourceIds[0]]);
const oauth = cli(['auth', 'register-client', 'synthetic-oauth-writer', '--grant-types', 'client_credentials',
'--scopes', 'read write', '--source', config.sourceIds[0]]);
oauthId = oauth.match(/Client ID:\s+(gbrain_cl_\S+)/)![1];
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 2b0a331afc..8eedf7dff5 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -198,7 +198,7 @@
" [--install] [--json] Print the paste-ready command, or --install to run it",
" auth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clients",
" auth --help Full subcommand list (register-client,",
- " rescope-client, rescope-token, revoke-client, permissions, ...)",
+ " rescope, rescope-client, rescope-token, revoke-client, ...)",
" watch [--json] Push-based context: pipe conversation turns in,",
" volunteered brain pages stream out (#2095)",
" call <tool> '<json>' Raw tool invocation",
@@ -407,7 +407,7 @@
" [--install] [--json] Print the paste-ready command, or --install to run it",
" auth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clients",
" auth --help Full subcommand list (register-client,",
- " rescope-client, rescope-token, revoke-client, permissions, ...)",
+ " rescope, rescope-client, rescope-token, revoke-client, ...)",
" watch [--json] Push-based context: pipe conversation turns in,",
" volunteered brain pages stream out (#2095)",
" call <tool> '<json>' Raw tool invocation",
@@ -616,7 +616,7 @@
" [--install] [--json] Print the paste-ready command, or --install to run it",
" auth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clients",
" auth --help Full subcommand list (register-client,",
- " rescope-client, rescope-token, revoke-client, permissions, ...)",
+ " rescope, rescope-client, rescope-token, revoke-client, ...)",
" watch [--json] Push-based context: pipe conversation turns in,",
" volunteered brain pages stream out (#2095)",
" call <tool> '<json>' Raw tool invocation",
diff --git a/test/persistence-take-receipt-authority.test.ts b/test/persistence-take-receipt-authority.test.ts
index c3d0606ff5..870c5d32c9 100644
--- a/test/persistence-take-receipt-authority.test.ts
+++ b/test/persistence-take-receipt-authority.test.ts
@@ -4,6 +4,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { operationsByName, type OperationContext } from '../src/core/operations.ts';
import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { parseRescopeTokenArgs, rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { compactWriteReceipts, getWriteRequest } from '../src/core/persistence/journal.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
@@ -71,8 +72,9 @@ test('holder narrowing hides every affected take receipt and replay after real c
await engine.executeRaw("UPDATE persistence_requests SET authority=authority-'takeHoldersUsed' WHERE request_id=$1::uuid",
[privateCalls[0].params.request_id]);
expect((await operationsByName.get_write_request.handler(ctx, { request_id: privateCalls[0].params.request_id }) as any).state).toBe('committed');
- await engine.executeRaw('UPDATE access_tokens SET permissions=$2::text::jsonb WHERE id=$1::uuid',
- [token.id, JSON.stringify({ source_id: [sourceId], takes_holders: ['world'] })]);
+ // F3: narrow through the grant editor (columns + JSONB mirror). A raw
+ // JSONB-only edit now reads as older-binary drift and denies the axis.
+ await rescopeLegacyToken(engine, parseRescopeTokenArgs(['--id', token.id, '--takes-holders', 'world']));
const narrowed = { ...ctx, takesHoldersAllowList: ['world'] };
for (const call of privateCalls) {
const row = (await getWriteRequest(engine, principal, String(call.params.request_id)))!;