Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
bootstrap harness: rotation carries the replaced token's grants (#5893)
garrytan90d618cc8679
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex f18e97205a..9e37799487 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap insrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail readsrc/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)src/core/config.ts 1813 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge-src/core/bootstrap/harness.ts 2674 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts)+src/core/bootstrap/harness.ts 2690 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +16 #5893: rotation grant carry wiring (carry rules live in token-mint.ts carryLegacyGrant)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 626 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages opsrc/core/search/mode.ts 1527 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= partdiff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex e0f424995d..0857bbe95f 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -67,7 +67,7 @@ import {redactToken,validateToken,} from '../mcp-registration.ts';-import { mintLegacyToken, revokeLegacyTokenById, type MintedLegacyToken } from '../token-mint.ts';+import { carryLegacyGrant, mintLegacyToken, readActiveTokenPermissions, revokeLegacyTokenById, type MintedLegacyToken } from '../token-mint.ts';import { generateToken } from '../utils.ts';import { readCredentials, writeCredentials, type HarnessCredentials } from '../harness/credentials.ts';import { installSharedSkillsConnection, type SharedSkillsConnectionOptions } from '../harness/shared-skills.ts';@@ -306,6 +306,8 @@ export interface HarnessDeps {scopes: string[];sourceGrant?: string[];allowedOperations?: string[];+ /** #5893: rotate from this token id, carrying its grants (carryLegacyGrant). */+ carry?: { fromId: string; explicitSource: boolean; policyAdded: string[] };}) => Promise<MintedLegacyToken>;installSharedSkills?: (credentials: HarnessCredentials, options: SharedSkillsConnectionOptions) => Promise<{status: string; reason?: string; retained_files?: string[]; next_action?: string; remote_membership_pending?: boolean;@@ -356,7 +358,7 @@ function resolveDeps(deps: HarnessDeps): Required<Omit<HarnessDeps, 'gbrainBin'>deps.codexAgentsOverride ??(deps.codexConfig ? join(dirname(deps.codexConfig), 'AGENTS.override.md') : codexAgentsOverridePath()),loadFileConfig: deps.loadFileConfig ?? loadConfigFileOnly,- mint: deps.mint ?? defaultMint,+ mint: deps.mint ?? mintHarnessToken,installSharedSkills: deps.installSharedSkills ?? installSharedSkillsConnection,nativeSkillsDir: deps.nativeSkillsDir ?? ((host) => {const config = host === 'claude-code' ? deps.userSettingsPath : host === 'codex' ? deps.codexConfig : deps.opencodeConfig;@@ -422,7 +424,7 @@ export function harnessDetectDeps(o?: HarnessDetectOverrides): Partial<HarnessDe}/** Production mint: open the configured engine just long enough to insert. */-async function defaultMint(opts: { name: string; scopes: string[]; sourceGrant?: string[]; allowedOperations?: string[] }): Promise<MintedLegacyToken> {+export async function mintHarnessToken(opts: Parameters<NonNullable<HarnessDeps['mint']>>[0]): Promise<MintedLegacyToken> {const cfg = loadConfig();if (!cfg) {throw new Error('no brain configured — run `gbrain init` first (the harness wires an EXISTING brain).');@@ -442,6 +444,13 @@ async function defaultMint(opts: { name: string; scopes: string[]; sourceGrant?:sourceGrant = undefined; // historical default floor}}+ const prior = opts.carry && await readActiveTokenPermissions(engine, opts.carry.fromId);+ if (prior !== undefined && opts.carry && opts.allowedOperations) {+ const carried = carryLegacyGrant(prior, { ...opts.carry, allowedOperations: opts.allowedOperations,+ ...(sourceGrant && sourceGrant.length > 0 ? { sourceGrant } : {}) });+ const minted = await mintLegacyToken(engine, { name: opts.name, scopes: opts.scopes, ...carried });+ return { ...minted, withheldOperations: carried.withheldOperations };+ }return await mintLegacyToken(engine, {name: opts.name,takesHolders: ['world'],@@ -1209,13 +1218,17 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P}} else {const allowedOperations = await harnessOperationSnapshot(skillsPolicy === 'follow');+ const priorSnapshot = prior ? await harnessOperationSnapshot(prior.skills_policy === 'follow') : allowedOperations;+ const policyAdded = allowedOperations.filter(op => !priorSnapshot.includes(op));for (const host of hosts) {let minted: MintedLegacyToken;+ const fromId = prior?.harness_tokens?.[host]?.minted ? prior.harness_tokens[host]!.id : prior?.token.minted ? prior.token.id : undefined;try {minted = await d.mint({name: hosts.length === 1 ? flags.tokenName : `${flags.tokenName}-${host}`,scopes: skillsPolicy === 'follow' ? ['read', 'write', 'skills_member_self'] : ['read', 'write'],allowedOperations,+ ...(fromId ? { carry: { fromId, explicitSource: !!flags.source, policyAdded } } : {}),// [X2] --source is the write floor — a scalar grant, the stdio// env-tier mirror. An implicit non-default source carries its// federated read set (#4897 — the same set search/think read, not a@@ -1229,6 +1242,9 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Pthrow e;}tokens.set(host, minted.token);+ if (minted.withheldOperations?.length) {+ d.log(`token ${minted.name}: carried the previous grants; ${minted.withheldOperations.length} newer operation(s) withheld — preview with \`gbrain auth rescope-token ${minted.name} --refresh-operations\`.`);+ }receipt.harness_tokens![host] = { id: minted.id, name: minted.name, minted: true };if (host === hosts[0]) {receipt.token.id = minted.id;diff --git a/src/core/token-mint.ts b/src/core/token-mint.tsindex ad15b5f21a..3db41989c0 100644--- a/src/core/token-mint.ts+++ b/src/core/token-mint.ts@@ -19,19 +19,21 @@ 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';/** 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;export interface MintLegacyTokenOpts {name: string;- /** Per-token takes-holder allow-list; harness default ['world']. */+ /** Per-token takes-holder allow-list; harness default ['world']. `[]` is stored as deny-all. */takesHolders: string[];/** Scope grant → the scopes TEXT[] column. Must be non-empty known scopes. */scopes: string[];/*** Federation grant → permissions.source_id (array; element 0 = write- * floor). Omit for the historical default-source floor.+ * floor). Omit for the historical default-source floor; `[]` is stored as+ * the explicit no-source grant.*/sourceGrant?: string[];allowedOperations?: string[];@@ -44,6 +46,8 @@ export interface MintedLegacyToken {id: string;name: string;scopes: string[];+ /** Rotation only: operations this run would grant that the carried snapshot withheld. */+ withheldOperations?: string[];}/**@@ -69,14 +73,10 @@ export async function mintLegacyToken(throw new Error('allowedOperations must contain only registered remote operation names');}}- const takesHolders = opts.takesHolders.length > 0 ? opts.takesHolders : ['world'];-const token = generateToken('gbrain_');const hash = hashToken(token);- const permissions: Record<string, unknown> = { takes_holders: takesHolders };- if (opts.sourceGrant && opts.sourceGrant.length > 0) {- permissions.source_id = opts.sourceGrant;- }+ 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)];// Scopes bind as a Postgres array literal through a TEXT param + ::text[]@@ -127,3 +127,39 @@ export async function revokeLegacyTokenById(sql: SqlQuery, id: string): Promise<`;return rows.length > 0;}++/**+ * #5893 rotation carry-over: the grants a rotated harness token inherits from+ * the token it replaces. Takes holders and the source grant are carried as+ * stored, explicit empty lists included (an explicit `--source` on this run+ * wins over the stored source grant). A stored operation snapshot is carried+ * 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`.+ */+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 sourceGrant = fresh.explicitSource || storedSource === undefined ? fresh.sourceGrant : storedSource;+ const priorOps = parseLegacyOperationGrant(prior.allowed_operations);+ 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,+ ])].sort();+ return { takesHolders, sourceGrant, allowedOperations,+ withheldOperations: fresh.allowedOperations.filter(op => !allowedOperations.includes(op)) };+}++/** The stored grant of an active token, or undefined when it is gone or revoked. */+export async function readActiveTokenPermissions(engine: BrainEngine, id: string): Promise<unknown> {+ if (!TOKEN_ID_RE.test(id)) return undefined;+ const [row] = await engine.executeRaw<{ permissions: unknown }>(+ 'SELECT permissions FROM access_tokens WHERE id = $1::uuid AND revoked_at IS NULL', [id]);+ return row ? row.permissions ?? {} : undefined;+}diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.tsindex 30a4efac52..e52ddbe822 100644--- a/test/bootstrap-harness.serial.test.ts+++ b/test/bootstrap-harness.serial.test.ts@@ -320,6 +320,19 @@ describe('full apply', () => {expect(Object.keys(hooks).sort()).toEqual(['PreCompact', 'SessionStart', 'UserPromptSubmit']);});+ test('#5893 re-run mints each host from the token it replaces, carrying its grants', async () => {+ const f = makeFake();+ expect(await applyHarness(flags(), f.deps)).toBe(0);+ const first = readHarnessReceiptState(f.home);+ if (first.state !== 'ok') throw new Error('expected a receipt');+ expect(f.mintCalls.slice(0, 3).every(call => (call as { carry?: unknown }).carry === undefined)).toBe(true);+ expect(await applyHarness(flags(['--source', 'wiki']), f.deps)).toBe(0);+ const carried = f.mintCalls.slice(3).map(call => (call as { name: string; carry?: { fromId: string; explicitSource: boolean; policyAdded: string[] } }));+ expect(carried.map(call => call.carry?.fromId)).toEqual(+ carried.map(call => first.receipt.harness_tokens![call.name.replace('bootstrap-harness-', '') as HarnessTarget['host']]!.id));+ expect(carried.every(call => call.carry?.explicitSource === true && call.carry.policyAdded.length === 0)).toBe(true);+ });+test('re-run rotates mint-first [C7]: one entry per event, previous token revoked by id AFTER confirm', async () => {const f = makeFake();expect(await applyHarness(flags(), f.deps)).toBe(0);diff --git a/test/harness-rotation-grants.serial.test.ts b/test/harness-rotation-grants.serial.test.tsnew file mode 100644index 0000000000..a0e0b582ad--- /dev/null+++ b/test/harness-rotation-grants.serial.test.ts@@ -0,0 +1,83 @@+/**+ * #5893: `bootstrap harness` rotation carries the replaced token's grants.+ *+ * Protects: the production harness mint (`mintHarnessToken`, the default+ * `deps.mint`) reads the previous token's stored `permissions` and mints the+ * replacement with the same takes holders and source grant, explicit empty+ * lists included, and with its operation snapshot narrowed (never widened) to+ * this run's snapshot. Regression it catches: the pre-fix mint hardcoding+ * `takes_holders: ['world']` and re-snapshotting operations, which silently+ * undid `auth rescope-token` / `auth permissions set-takes-holders` edits.+ * Serial: GBRAIN_HOME is remapped so the mint opens this sandboxed PGLite brain.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createEngine } from '../src/core/engine-factory.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { mintHarnessToken } from '../src/core/bootstrap/harness.ts';+import { carryLegacyGrant, mintLegacyToken } from '../src/core/token-mint.ts';+import { executeRawJsonb } from '../src/core/sql-query.ts';+import { withEnv } from './helpers/with-env.ts';++let root: string, home: string, db: string;++async function withBrain<T>(run: (engine: BrainEngine) => Promise<T>): Promise<T> {+ const config = { engine: 'pglite' as const, database_path: db };+ const engine = await createEngine(config);+ await engine.connect(config);+ try { return await run(engine); } finally { await engine.disconnect(); }+}++const permissionsOf = (id: string) => withBrain(async engine => (await engine.executeRaw<{ permissions: Record<string, unknown> }>(+ 'SELECT permissions FROM access_tokens WHERE id = $1::uuid', [id]))[0].permissions);++beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'gb-harness-rotation-'));+ home = join(root, 'home');+ db = join(root, 'db');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: db }));+ await withBrain(engine => engine.initSchema());+}, 120_000);++afterAll(() => { rmSync(root, { recursive: true, force: true }); });++const env = () => ({ GBRAIN_HOME: home, HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined });++test('rotation preserves explicit empty lists and operator-set holders', async () => {+ const snapshot = ['get_page', 'query', 'search'];+ const prior = await withBrain(async engine => {+ const minted = await mintLegacyToken(engine, { name: 'bootstrap-harness', takesHolders: ['world'], scopes: ['read', 'write'], allowedOperations: snapshot });+ await executeRawJsonb(engine, 'UPDATE access_tokens SET permissions = $2::jsonb WHERE id = $1::uuid', [minted.id],+ [{ takes_holders: [], source_id: [], allowed_operations: [], note: 'kept only on the old row' }]);+ return minted;+ });+ const rotated = await withEnv(env(), () => mintHarnessToken({ name: 'bootstrap-harness', scopes: ['read', 'write'],+ allowedOperations: snapshot, carry: { fromId: prior.id, explicitSource: false, policyAdded: [] } }));+ expect(rotated.id).not.toBe(prior.id);+ expect(await permissionsOf(rotated.id)).toEqual({ takes_holders: [], source_id: [], allowed_operations: [] });+}, 120_000);++test('rotation narrows to this run and withholds new operations instead of widening', async () => {+ const prior = await withBrain(async engine => {+ const minted = await mintLegacyToken(engine, { name: 'bootstrap-harness', takesHolders: ['world'], scopes: ['read', 'write'], allowedOperations: ['get_page', 'search'] });+ await executeRawJsonb(engine, 'UPDATE access_tokens SET permissions = $2::jsonb WHERE id = $1::uuid', [minted.id],+ [{ takes_holders: ['world', 'brain'], source_id: ['default'], allowed_operations: ['get_page', 'search'] }]);+ return minted;+ });+ const rotated = await withEnv(env(), () => mintHarnessToken({ name: 'bootstrap-harness', scopes: ['read', 'write'],+ allowedOperations: ['get_page', 'query'], carry: { fromId: prior.id, explicitSource: false, policyAdded: [] } }));+ expect(await permissionsOf(rotated.id)).toEqual({ takes_holders: ['world', 'brain'], source_id: ['default'], allowed_operations: ['get_page'] });+ expect(rotated.withheldOperations).toEqual(['query']);+}, 120_000);++test('carry rules: an explicit --source wins; policy changes add only their own operations; absent snapshot re-snapshots', () => {+ const fresh = { sourceGrant: ['wiki'], explicitSource: true, allowedOperations: ['get_page', 'join_brain'], policyAdded: ['join_brain'] };+ expect(carryLegacyGrant({ source_id: [], takes_holders: ['world'], allowed_operations: ['get_page'] }, fresh))+ .toEqual({ takesHolders: ['world'], sourceGrant: ['wiki'], allowedOperations: ['get_page', 'join_brain'], withheldOperations: [] });+ expect(carryLegacyGrant({ source_id: 'team-a' }, { ...fresh, explicitSource: false }))+ .toEqual({ takesHolders: ['world'], sourceGrant: ['team-a'], allowedOperations: ['get_page', 'join_brain'], withheldOperations: [] });+ expect(carryLegacyGrant({ allowed_operations: [] }, { ...fresh, explicitSource: false }).allowedOperations).toEqual([]);+});