Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(grants): diagnosis names execution prerequisites; refresh works on snapshot-less tokens (#6621, #6663)

time-attack89331d433278
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index ca7ba16ed2..caf0a2d99a 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -288,6 +288,20 @@ separate, disclosed choice, never the default repair: `--operations all` for a
client (`--reset-default operations` for a token) stores no snapshot, so the
scopes and surface allow every operation, including ones later upgrades add.
+Two exceptions no snapshot change alone covers (the grant diagnosis lists them
+in `prerequisites[]` as `{operation, prerequisite, fix}`):
+
+- Membership operations (`join_brain`, `sync_brain_skills`, `leave_brain`)
+ need explicit approval by name. A grant with no snapshot never reaches them,
+ so the diagnosis counts them as unreachable. On a token with no snapshot,
+ `--refresh-operations` previews them, and `--refresh-operations --add
+ join_brain` writes a snapshot of every operation the scopes allow today plus
+ exactly the added one. Operations later upgrades add then need their own
+ refresh. `--all-new` is refused there; name each membership operation.
+- `confirm_memory` promotes trust only with the `memory_confirm` scope, which
+ the brain owner grants from the local CLI. Admitting it to a snapshot lets
+ its dry-run and no-op paths run, not promotion.
+
### Access-token lifetime
An access token lives at most 90 days (7,776,000 seconds), whatever a
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index fecdad0efd..eccf9f106e 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -888,13 +888,17 @@ function printTokenRescope(result: RescopeTokenResult, json: boolean) {
}
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'}`);
+ const { available, added, unregistered, materialized } = result.refresh;
+ if (materialized) {
+ console.log(' This token has no operation snapshot: it reaches every operation its scopes allow except membership operations, which need explicit approval.');
+ console.log(' Adding one writes a snapshot of every operation its scopes allow today plus the ones you add; operations later upgrades add then need --refresh-operations.');
+ }
+ console.log(` ${materialized ? 'Operations that need approval' : '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)`);
+ console.log(` Nothing widened. Grant them with: gbrain auth rescope --token ${result.name} --refresh-operations ${add}${materialized ? '' : ' (or --all-new)'}`);
}
}
if (result.changed && !result.dryRun) console.log('Grants apply on the next request; the token secret is unchanged.');
diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.ts
index ffee6f2854..766ba52502 100644
--- a/src/core/grants/legacy-token.ts
+++ b/src/core/grants/legacy-token.ts
@@ -29,6 +29,7 @@ import { isValidSourceId } from '../source-id.ts';
import { executeRawJsonb, type SqlQuery } from '../sql-query.ts';
import { TOKEN_ID_RE } from '../token-mint.ts';
import { isUndefinedColumnError } from '../utils.ts';
+import { requiresExplicitApproval } from '../ops/execution-prerequisites.ts';
import {
GrantError, LEGACY_GRANT_AXES, grantFromTokenRow, permissionsMirror, tokenGrantColumnValues, tokenGrantFromColumns,
tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant,
@@ -74,7 +75,11 @@ export interface RescopeTokenResult {
revision: { before: number; after: number };
/** Axes that were drifted (deny-all) before this call. */
drift: LegacyGrantAxis[];
- refresh?: { available: string[]; added: string[]; unregistered: string[] };
+ /**
+ * `materialized`: the token had no operation snapshot (#6663). Adding writes one: every operation its scopes
+ * allow today plus the added ones, so operations later upgrades add need their own refresh.
+ */
+ refresh?: { available: string[]; added: string[]; unregistered: string[]; materialized?: true };
}
const csvOrNone = (value: string): string[] =>
@@ -257,16 +262,21 @@ async function rescopeInTransaction(tx: BrainEngine, args: RescopeTokenArgs): Pr
}
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`);
+ // #6663 (D17): a token with no snapshot reaches every operation its scopes allow except the membership
+ // operations, which need explicit approval. Refreshing it materializes exactly that reachable set and
+ // adds only the operations --add names, so nothing narrows today and no other membership op is approved.
+ const materialized = base.allowedOperations === null;
+ const granted = base.allowedOperations ?? grantable.filter(op => !requiresExplicitApproval(op));
+ if (materialized && args.allNew) {
+ throw new GrantError('invalid_grant', `Token ${label} has no operation snapshot; --all-new would approve every membership operation at once. `
+ + `Preview with gbrain auth rescope ${'id' in args.target ? `--id ${args.target.id}` : `--token ${args.target.name}`} --refresh-operations, then name each one with --add`);
}
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)) };
+ refresh = { available, added, unregistered: granted.filter(op => !all.has(op)), ...(materialized ? { materialized: true } : {}) };
}
const opsEdited = args.operations !== undefined || Boolean(refresh?.added.length);
validatePrincipalGrant({
diff --git a/src/core/harness/capabilities.ts b/src/core/harness/capabilities.ts
index 6e240f3354..b4829265f0 100644
--- a/src/core/harness/capabilities.ts
+++ b/src/core/harness/capabilities.ts
@@ -6,6 +6,7 @@ import { TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, normalizeGrantBrain, vali
import { shellQuote } from '../mcp-registration.ts';
import type { CatalogProvenance } from '../grants/profiles.ts';
import type { Action, Notice } from '../agent-output.ts';
+import { EXECUTION_PREREQUISITES, requiresExplicitApproval } from '../ops/execution-prerequisites.ts';
type GrantSurface = 'verbs' | 'starter' | 'full';
@@ -82,11 +83,21 @@ export interface GrantGapInput {
export interface GrantGaps {
missingScopes: string[];
snapshotExcluded: string[];
+ /** #6663: operations that need explicit snapshot approval, which a grant with no snapshot never gives. */
+ approvalExcluded: string[];
pinExcluded: string[];
serverExcluded: string[];
unreachable: string[];
+ /**
+ * #6621/#6663: eligible operations whose execution needs something no snapshot or surface change gives
+ * (ops/execution-prerequisites.ts), each with what lifts it. Not counted in `unreachable` unless a blocker
+ * above also applies; named because every one is within the grant's own scopes.
+ */
+ prerequisites: GrantPrerequisite[];
}
+export interface GrantPrerequisite { operation: string; prerequisite: string; fix: string }
+
export async function grantOperationGaps(input: GrantGapInput): Promise<GrantGaps> {
const [{ operations, opAllowedForBoundClient }, { filterOpsForSurface }] = await Promise.all([
import('../operations.ts'), import('../../mcp/surface.ts'),
@@ -101,13 +112,25 @@ export async function grantOperationGaps(input: GrantGapInput): Promise<GrantGap
};
const snapshot = input.allowedOperations ? new Set(input.allowedOperations) : null;
const snapshotExcluded = snapshot ? eligible.filter(op => !snapshot.has(op.name)).map(op => op.name) : [];
+ const approvalExcluded = snapshot ? [] : eligible.filter(op => requiresExplicitApproval(op.name)).map(op => op.name);
const pinExcluded = outside(input.clientSurface);
const serverExcluded = outside(input.serverSurface);
- const blocked = new Set([...snapshotExcluded, ...pinExcluded, ...serverExcluded]);
+ const blocked = new Set([...snapshotExcluded, ...approvalExcluded, ...pinExcluded, ...serverExcluded]);
+ const prerequisites: GrantPrerequisite[] = [];
+ for (const op of eligible) {
+ const need = EXECUTION_PREREQUISITES[op.name];
+ if (!need) continue;
+ if (need.kind === 'owner_granted_scope' && need.scope && !hasScope([...input.scopes], need.scope)) {
+ prerequisites.push({ operation: op.name, prerequisite: `scope:${need.scope}`, fix: need.fix });
+ } else if (need.kind === 'explicit_operation_approval' && !snapshot?.has(op.name)) {
+ prerequisites.push({ operation: op.name, prerequisite: 'explicit_operation_approval', fix: need.fix });
+ }
+ }
return {
missingScopes: ['read', 'write'].filter(scope => !hasScope([...input.scopes], scope)),
- snapshotExcluded, pinExcluded, serverExcluded,
+ snapshotExcluded, approvalExcluded, pinExcluded, serverExcluded,
unreachable: eligible.filter(op => blocked.has(op.name)).map(op => op.name),
+ prerequisites,
};
}
@@ -152,7 +175,7 @@ export type RescopeTarget = { kind: 'oauth_client'; id: string } | { kind: 'lega
* leaves the `<OPERATIONS>` placeholder for the owner to choose. `all` is the
* disclosed no-snapshot choice, never the default repair.
*/
-export function grantRescopeArgvs(target: RescopeTarget, gaps: Pick<GrantGaps, 'snapshotExcluded' | 'pinExcluded'>, operations: string | null) {
+export function grantRescopeArgvs(target: RescopeTarget, gaps: Pick<GrantGaps, 'snapshotExcluded' | 'pinExcluded'> & Partial<Pick<GrantGaps, 'approvalExcluded'>>, operations: string | null) {
const value = operations ?? '<OPERATIONS>';
if (target.kind === 'legacy_token') {
const base = ['gbrain', 'auth', 'rescope', ...target.flag];
@@ -161,7 +184,7 @@ export function grantRescopeArgvs(target: RescopeTarget, gaps: Pick<GrantGaps, '
}
const base = ['gbrain', 'auth', 'rescope', '--client', target.id];
const surface = gaps.pinExcluded.length ? ['--surface', 'full'] : [];
- const apply = [...base, ...(gaps.snapshotExcluded.length ? ['--operations', value] : []), ...surface];
+ const apply = [...base, ...(gaps.snapshotExcluded.length || gaps.approvalExcluded?.length ? ['--operations', value] : []), ...surface];
return { preview: [...apply, '--dry-run'], apply, all_operations: [...base, '--operations', 'all', ...surface, '--dry-run'] };
}
@@ -170,6 +193,7 @@ export function grantBlockers(gaps: GrantGaps, surfaces: { clientSurface: GrantS
const blockers: Array<Record<string, unknown>> = [];
if (gaps.missingScopes.length) blockers.push({ blocker: 'scope', missing_scopes: gaps.missingScopes });
if (gaps.snapshotExcluded.length) blockers.push({ blocker: 'operation_snapshot', excluded_count: gaps.snapshotExcluded.length });
+ if (gaps.approvalExcluded?.length) blockers.push({ blocker: 'explicit_approval', excluded_count: gaps.approvalExcluded.length });
if (gaps.pinExcluded.length) blockers.push({ blocker: 'client_pin', surface: surfaces.clientSurface, set_by: surfaces.clientSurfaceSetBy, excluded_count: gaps.pinExcluded.length });
if (gaps.serverExcluded.length) blockers.push({ blocker: 'server_ceiling', surface: surfaces.serverSurface, excluded_count: gaps.serverExcluded.length });
return blockers;
@@ -187,11 +211,16 @@ export function describeGrantDiagnosis(gaps: GrantGaps, opts: {
serverSurface: GrantSurface | null; target: RescopeTarget | null;
}) {
const blockers = grantBlockers(gaps, opts);
- const repairable = opts.target && (gaps.snapshotExcluded.length || gaps.pinExcluded.length);
+ const repairable = opts.target && (gaps.snapshotExcluded.length || gaps.approvalExcluded?.length || gaps.pinExcluded.length);
const argvs = repairable ? grantRescopeArgvs(opts.target!, gaps, null) : null;
+ const prerequisites = gaps.prerequisites ?? [];
+ const prerequisiteNote = prerequisites.length
+ ? ` Some operations need more than this change: ${prerequisites.map(p => `${p.operation} (${p.fix})`).join('; ')}`
+ : '';
return {
blockers,
unreachable_count: gaps.unreachable.length,
+ prerequisites,
grant_age: grantAge(gaps.snapshotExcluded, opts.hasSnapshot, opts.provenance),
fix: argvs ? {
next: 'tell_user_to_run' as const, actor: 'host_admin' as const,
@@ -199,7 +228,7 @@ export function describeGrantDiagnosis(gaps: GrantGaps, opts: {
then_argv: argvs.apply,
...(argvs.apply.includes('<OPERATIONS>') ? { inputs: [{ name: 'OPERATIONS', how: 'The brain owner chooses: the current operation snapshot plus each operation they approve, comma-separated.' }] } : {}),
why: 'This grant cannot call operations its scopes allow until the brain owner changes it; nothing widens automatically.',
- user_message: `This gbrain connection cannot call ${gaps.unreachable.length} operation(s) its scopes allow. Ask the brain owner to preview the change on the brain host with the command shown, then apply it.`,
+ user_message: `This gbrain connection cannot call ${gaps.unreachable.length} operation(s) its scopes allow. Ask the brain owner to preview the change on the brain host with the command shown, then apply it.${prerequisiteNote}`,
all_operations: { argv: argvs.all_operations, label: ALL_OPERATIONS_CHOICE },
} : null,
};
@@ -236,6 +265,7 @@ export function grantRepairAction(d: GrantDiagnosis): Action | null {
function blockerPhrase(b: Record<string, unknown>): string {
if (b.blocker === 'operation_snapshot') return `its operation snapshot (${b.excluded_count})`;
+ if (b.blocker === 'explicit_approval') return `missing explicit approval of membership operations, which a grant with no operation snapshot never gives (${b.excluded_count})`;
if (b.blocker === 'client_pin') return `its stored ${b.surface} tool surface${b.set_by === 'operator' ? ', which the brain owner pinned' : ''} (${b.excluded_count})`;
return `the server's ${b.surface} tool surface (${b.excluded_count})`;
}
diff --git a/src/core/ops/execution-prerequisites.ts b/src/core/ops/execution-prerequisites.ts
new file mode 100644
index 0000000000..5571b1ca99
--- /dev/null
+++ b/src/core/ops/execution-prerequisites.ts
@@ -0,0 +1,42 @@
+/**
+ * #6621/#6663: what an operation needs at execution time beyond the scope its
+ * definition declares. The grant diagnosis (harness/capabilities.ts) reads
+ * this table so it never tells a connection that a snapshot or scope change
+ * alone makes these operations work. Enforcement stays where it is:
+ * `memory_confirm` in trust/confirm.ts (requireOwnerConfirmation) and explicit
+ * snapshot approval in shared-skills/membership-authority.ts (memberAuthority).
+ * Kept as data beside the operations so the generated operation manifest does
+ * not change; test/grant-execution-prerequisites.test.ts pins every key to a
+ * registered operation and to the enforcement it describes.
+ */
+import { MEMORY_CONFIRM_SCOPE } from '../trust/confirm.ts';
+
+export type ExecutionPrerequisiteKind = 'owner_granted_scope' | 'explicit_operation_approval';
+
+export interface ExecutionPrerequisite {
+ kind: ExecutionPrerequisiteKind;
+ /** owner_granted_scope: the scope the operation's real work also needs. */
+ scope?: string;
+ /** What lifts it, for the diagnosis. */
+ fix: string;
+}
+
+const MEMBERSHIP_APPROVAL: ExecutionPrerequisite = {
+ kind: 'explicit_operation_approval',
+ fix: 'The brain owner approves this membership operation by name in the grant\'s operation snapshot; a grant with no snapshot does not reach it.',
+};
+
+export const EXECUTION_PREREQUISITES: Readonly<Record<string, ExecutionPrerequisite>> = {
+ confirm_memory: {
+ kind: 'owner_granted_scope', scope: MEMORY_CONFIRM_SCOPE,
+ fix: `Snapshot admission does not grant trust promotion: confirming memory needs the ${MEMORY_CONFIRM_SCOPE} scope, which only the brain owner grants from the local CLI.`,
+ },
+ join_brain: MEMBERSHIP_APPROVAL,
+ sync_brain_skills: MEMBERSHIP_APPROVAL,
+ leave_brain: MEMBERSHIP_APPROVAL,
+};
+
+/** Operations a grant reaches only when its operation snapshot names them (never through a missing snapshot). */
+export function requiresExplicitApproval(operation: string): boolean {
+ return EXECUTION_PREREQUISITES[operation]?.kind === 'explicit_operation_approval';
+}
diff --git a/test/grant-execution-prerequisites.test.ts b/test/grant-execution-prerequisites.test.ts
new file mode 100644
index 0000000000..0a1fb7410d
--- /dev/null
+++ b/test/grant-execution-prerequisites.test.ts
@@ -0,0 +1,117 @@
+/**
+ * #6621 / #6663: the grant diagnosis names execution prerequisites a snapshot
+ * or scope change alone does not satisfy (confirm_memory needs memory_confirm;
+ * membership operations need explicit snapshot approval, which a grant with no
+ * snapshot never gives), and `auth rescope --refresh-operations --add` works on
+ * a token with no snapshot without narrowing it or approving other membership
+ * operations (D17).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { describeGrantDiagnosis, grantOperationGaps } from '../src/core/harness/capabilities.ts';
+import { EXECUTION_PREREQUISITES, requiresExplicitApproval } from '../src/core/ops/execution-prerequisites.ts';
+import { MEMORY_CONFIRM_SCOPE, requireOwnerConfirmation } from '../src/core/trust/confirm.ts';
+import { memberAuthority } from '../src/core/shared-skills/membership-authority.ts';
+import { rescopeLegacyToken, type LegacyGrantAxis } from '../src/core/grants/legacy-token.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { operations } from '../src/core/operations.ts';
+import { operationScopesAllowed } from '../src/core/scope.ts';
+
+const gapsFor = (scopes: string[], allowedOperations: string[] | null) =>
+ grantOperationGaps({ scopes, allowedOperations, clientSurface: null, serverSurface: null, disabled: new Set() });
+const diagnose = (gaps: Awaited<ReturnType<typeof gapsFor>>, hasSnapshot: boolean, target = { kind: 'legacy_token', flag: ['--token', 't'] } as const) =>
+ describeGrantDiagnosis(gaps, { hasSnapshot, provenance: null, clientSurface: null, clientSurfaceSetBy: null, serverSurface: null, target: target as never });
+const MEMBERSHIP = ['join_brain', 'leave_brain', 'sync_brain_skills'];
+
+describe('execution prerequisite table', () => {
+ test('names registered operations and the enforcement it describes', () => {
+ const names = new Set(operations.map(op => op.name));
+ for (const op of Object.keys(EXECUTION_PREREQUISITES)) expect(names.has(op)).toBe(true);
+ expect(EXECUTION_PREREQUISITES.confirm_memory).toMatchObject({ kind: 'owner_granted_scope', scope: MEMORY_CONFIRM_SCOPE });
+ const membershipSource = readFileSync(join(resolve(import.meta.dir, '..'), 'src/core/shared-skills/membership.ts'), 'utf8');
+ const enforced = [...membershipSource.matchAll(/memberAuthority\(\w+, '([a-z_]+)'\)/g)].map(m => m[1]).sort();
+ expect(enforced).toEqual(MEMBERSHIP);
+ expect(Object.keys(EXECUTION_PREREQUISITES).filter(requiresExplicitApproval).sort()).toEqual(MEMBERSHIP);
+ });
+});
+
+describe('#6621 confirm_memory needs memory_confirm, not just a snapshot', () => {
+ test('the diagnosis names the prerequisite next to the snapshot repair; counts are unchanged', async () => {
+ const gaps = await gapsFor(['read', 'write'], ['get_page', 'put_page']);
+ expect(gaps.unreachable).toContain('confirm_memory');
+ expect(gaps.prerequisites).toContainEqual(expect.objectContaining({ operation: 'confirm_memory', prerequisite: `scope:${MEMORY_CONFIRM_SCOPE}` }));
+ const d = diagnose(gaps, true);
+ expect(d.unreachable_count).toBe(gaps.unreachable.length);
+ expect(d.prerequisites.map(p => p.operation)).toContain('confirm_memory');
+ expect(d.fix?.user_message).toContain(MEMORY_CONFIRM_SCOPE);
+ let gate = 'allowed';
+ try {
+ await requireOwnerConfirmation({ remote: true, auth: { scopes: ['read', 'write', 'admin'] } } as never,
+ { ref: 'f1', token: 't', summary: 's', command: ['gbrain', 'trust', 'confirm', 'f1'] });
+ } catch (e) { gate = (e as { code?: string }).code ?? String(e); }
+ expect(gate).toBe('insufficient_scope');
+ });
+
+ test('a grant that holds memory_confirm has no prerequisite left', async () => {
+ const gaps = await gapsFor(['read', 'write', MEMORY_CONFIRM_SCOPE], null);
+ expect(gaps.prerequisites.map(p => p.operation)).not.toContain('confirm_memory');
+ });
+});
+
+describe('#6663 membership operations on a grant with no snapshot', () => {
+ test('are unreachable, named, and get a refresh repair', async () => {
+ const scopes = ['read', 'skills_member_self'];
+ const gaps = await gapsFor(scopes, null);
+ expect(gaps.approvalExcluded.sort()).toEqual(MEMBERSHIP);
+ for (const op of MEMBERSHIP) expect(gaps.unreachable).toContain(op);
+ expect(gaps.unreachable).toHaveLength(MEMBERSHIP.length);
+ let gate = 'allowed';
+ try {
+ await memberAuthority({ remote: true, auth: { scopes, principal: { kind: 'legacy_token', id: 't1' }, allowedOperations: undefined }, engine: { executeRaw: async () => [] } } as never, 'join_brain');
+ } catch (e) { gate = (e as { code?: string }).code ?? String(e); }
+ expect(gate).toBe('permission_denied');
+ const d = diagnose(gaps, false);
+ expect(d.blockers).toContainEqual({ blocker: 'explicit_approval', excluded_count: MEMBERSHIP.length });
+ expect(d.fix?.argv).toEqual(['gbrain', 'auth', 'rescope', '--token', 't', '--refresh-operations']);
+ expect(d.fix?.then_argv).toEqual(['gbrain', 'auth', 'rescope', '--token', 't', '--refresh-operations', '--add', '<OPERATIONS>']);
+ const client = diagnose(gaps, false, { kind: 'oauth_client', id: 'c1' } as never);
+ expect(client.fix?.then_argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'c1', '--operations', '<OPERATIONS>']);
+ });
+
+ test('a snapshot that names a membership operation reaches it', async () => {
+ const gaps = await gapsFor(['read', 'skills_member_self'], ['get_page', 'join_brain']);
+ expect(gaps.approvalExcluded).toEqual([]);
+ expect(gaps.unreachable).not.toContain('join_brain');
+ expect(gaps.prerequisites.map(p => p.operation)).not.toContain('join_brain');
+ });
+});
+
+describe('D17: --refresh-operations --add on a token with no snapshot', () => {
+ let engine: BrainEngine;
+ beforeAll(async () => { const pg = new PGLiteEngine(); await pg.connect({}); await pg.initSchema(); engine = pg; }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('previews the approval-only operations, then materializes the reachable set plus exactly the added one', async () => {
+ const scopes = ['read', 'write', 'skills_member_self'];
+ await mintLegacyToken(engine, { name: 'member-example', scopes, takesHolders: ['world'] });
+ const base = { target: { name: 'member-example' }, reset: [] as LegacyGrantAxis[], refreshOperations: true, allNew: false, json: true };
+ const preview = await rescopeLegacyToken(engine, { ...base, dryRun: false });
+ expect(preview.written).toBe(false);
+ expect(preview.after.operations).toBe('unrestricted');
+ expect(preview.refresh).toMatchObject({ materialized: true, added: [] });
+ expect([...preview.refresh!.available].sort()).toEqual(MEMBERSHIP);
+
+ await expect(rescopeLegacyToken(engine, { ...base, allNew: true, dryRun: false })).rejects.toThrow(/name each one with --add/);
+
+ const applied = await rescopeLegacyToken(engine, { ...base, add: ['join_brain'], dryRun: false });
+ expect(applied.written).toBe(true);
+ const granted = applied.after.operations as string[];
+ const reachable = operations.filter(op => !op.localOnly && operationScopesAllowed(scopes, op) && !MEMBERSHIP.includes(op.name)).map(op => op.name);
+ expect([...granted].sort()).toEqual([...reachable, 'join_brain'].sort());
+ expect(granted).not.toContain('sync_brain_skills');
+ expect(granted).not.toContain('leave_brain');
+ });
+});