Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(harness): Codex tool approvals no longer make connect --install refuse configuration_conflict (#6799)

time-attacke3ffda5e26cc
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index dad16c5a90..73cbe6244e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -912,6 +912,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.307.0', text: 'A worker registry directory that exists but cannot be listed (permission denied, or a file where the directory should be) now reads as unknown worker liveness instead of no workers. Doctor `queue_health` reports `worker_alive: null` with a liveness-unknown message and no start-a-worker fix, `legacy_job_authority` reports `live_workers: null`, `gbrain jobs supervisor status --json` reports `workers: null`, a submitted job\'s `queue_state` omits `worker_alive` and warns that liveness is unknown, `gbrain jobs stats` reports a wedge instead of `no_worker`, and the `migrate-embeddings` plan warns about an unknown worker count. Each names the errno and path in `worker_registry_errno` and `worker_registry_path`. A missing registry directory still means no workers.' },
{ since: '0.60.307.0', text: '`gbrain sources attach` with an invalid source id now refuses with `invalid_params` (a caller error) and a fix that lists the existing ids (`gbrain sources list --json`), instead of an `internal_error`. Nothing is written in either case.' },
{ since: '0.60.307.0', text: 'On a managed brain, a dream synthesis output or summary whose publish is refused because the principal or brain outstanding-request cap (`persistence.limits.principal_outstanding`, `persistence.limits.brain_outstanding`) is full is now deferred like a pending publish: the phase warns with `publish_pending`, leaves the cooldown unstamped and the next cycle retries the same request, instead of failing the phase. A zero cap and cumulative quotas still fail it.' },
+ // #6799 (Codex tool approvals).
+ { since: '0.60.307.0', text: 'A Codex connection installed with `gbrain connect --harness codex --install` (or `bootstrap harness`) now keeps Codex\'s own per-tool settings (`[mcp_servers.<name>.tools.<tool>]`, written when you pick "always allow") instead of refusing the next install or `--fresh-token` renewal with `configuration_conflict`: settings inside the gbrain-managed block are carried into the rewritten block, settings outside it stay where they are, and any other edit to the entry (its URL, headers or other keys) still refuses. Removing the connection refuses with `configuration_conflict` while such settings sit outside the block, naming the tables to delete, so the server is never left half-defined.' },
// #6796 (apply-migrations applied_pending_host_work).
{ since: '0.60.307.0', text: '`gbrain apply-migrations --list` now shows v0.53.0 as `applied_pending_host_work` instead of `applied` while its stored shared-skills report still names host work (a source\'s inventory, writer, projection or publication-policy stage, or a brain-level pending action), and no longer prints "All migrations up to date" for it; `--list --json` rows carry that status and an `applied_pending_host_work` array whose fix is the read-only `gbrain apply-migrations --migration 0.53.0 --dry-run --json` inventory. Scripts that match `applied` should accept both. `gbrain doctor` warns on `minions_migration` (`details.code: migration_host_work_pending`) until a later `gbrain apply-migrations --yes` re-check finds the work done. Unenrolled members (every new brain), sources that opted out and a declined migration are never reported.' },
];
diff --git a/src/core/bootstrap/codex-toml.ts b/src/core/bootstrap/codex-toml.ts
index c73bb2b339..93d95d5797 100644
--- a/src/core/bootstrap/codex-toml.ts
+++ b/src/core/bootstrap/codex-toml.ts
@@ -134,15 +134,47 @@ function parseToml(text: string): Record<string, unknown> {
* appending to a broken file could only deepen the damage.
*/
export function detectForeignCodexServer(configText: string, name: string): boolean {
- const lines = configText.replace(/\r\n/g, '\n').split('\n');
- const { remainder } = stripBlock(lines);
- const parsed = parseToml(remainder.join('\n'));
- const servers = parsed.mcp_servers;
- if (typeof servers !== 'object' || servers === null) return false;
- return (servers as Record<string, unknown>)[name] !== undefined;
+ const server = outsideServer(configText, name);
+ return server !== undefined && !isToolsOnly(server);
}
-function renderBlock(block: CodexHttpServerBlock): string[] {
+/** `mcp_servers.<name>` as defined outside our managed block, or undefined. */
+function outsideServer(configText: string, name: string): unknown {
+ const { remainder } = stripBlock(configText.replace(/\r\n/g, '\n').split('\n'));
+ const servers = parseToml(remainder.join('\n')).mcp_servers;
+ return isTable(servers) ? servers[name] : undefined;
+}
+
+/**
+ * Codex's per-tool settings for a server (`[mcp_servers.<name>.tools.<tool>]`,
+ * e.g. `approval_mode = "approve"` from "always allow", #6799): tool name to
+ * scalar settings. Null for any other shape, which stays a foreign edit.
+ */
+export type CodexToolPolicy = Record<string, Record<string, string | number | boolean>>;
+
+const isTable = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+export function codexToolPolicy(value: unknown): CodexToolPolicy | null {
+ if (!isTable(value)) return null;
+ for (const settings of Object.values(value)) {
+ if (!isTable(settings) || Object.values(settings).some(v => !['string', 'number', 'boolean'].includes(typeof v))) return null;
+ }
+ return value as CodexToolPolicy;
+}
+
+/** A server table holding nothing but a valid tool policy: Codex's approvals, not a server definition. */
+function isToolsOnly(server: unknown): boolean {
+ return isTable(server) && Object.keys(server).join(',') === 'tools' && codexToolPolicy(server.tools) !== null;
+}
+
+/** Tools whose Codex settings sit outside our managed block (removing the block would orphan them). */
+export function codexToolsOutsideBlock(configText: string, name: string): string[] {
+ const server = outsideServer(configText, name);
+ return isToolsOnly(server) ? Object.keys((server as { tools: CodexToolPolicy }).tools) : [];
+}
+
+function renderBlock(block: CodexHttpServerBlock, tools: CodexToolPolicy = {}): string[] {
// http_headers inline table, NOT `bearer_token`: codex-cli >=0.149 rejects
// bearer_token for streamable_http at config load (#4574); this shape loads
// on 0.147.x and 0.149.x.
@@ -151,18 +183,24 @@ function renderBlock(block: CodexHttpServerBlock): string[] {
`[mcp_servers.${block.name}]`,
`url = ${tomlString(block.url)}`,
`http_headers = { Authorization = ${tomlString(`Bearer ${block.bearerToken}`)} }`,
+ ...Object.entries(tools).flatMap(([tool, settings]) => [
+ `[mcp_servers.${block.name}.tools.${tomlKey(tool)}]`,
+ ...Object.entries(settings).map(([k, v]) => `${tomlKey(k)} = ${typeof v === 'string' ? tomlString(v) : String(v)}`),
+ ]),
CODEX_TOML_BLOCK_END,
];
}
/** Post-render assertion shared by the writer and the snippet renderer: our
- * table's keys are EXACTLY [http_headers, url], and the http_headers inline
+ * table's keys are EXACTLY [http_headers, url] (plus a `tools` table of
+ * Codex's own per-tool settings, #6799), and the http_headers inline
* table carries EXACTLY the Authorization header we wrote. Returns an error
* string (caller prefixes its own context) or null when valid. */
function validateOurKeys(ours: unknown): string | null {
const ourKeys = typeof ours === 'object' && ours !== null ? Object.keys(ours as object).sort() : [];
- if (ourKeys.join(',') !== 'http_headers,url') {
- return `keys are [${ourKeys.join(', ')}], expected exactly [http_headers, url]`;
+ const withTools = ourKeys.join(',') === 'http_headers,tools,url' && codexToolPolicy((ours as Record<string, unknown>).tools) !== null;
+ if (ourKeys.join(',') !== 'http_headers,url' && !withTools) {
+ return `keys are [${ourKeys.join(', ')}], expected exactly [http_headers, url] (plus Codex tool settings)`;
}
const headers = (ours as Record<string, unknown>).http_headers;
const headerKeys = typeof headers === 'object' && headers !== null ? Object.keys(headers as object) : [];
@@ -231,9 +269,15 @@ export function writeCodexHttpServerBlock(
const lines = rawText.replace(/\r\n/g, '\n').split('\n');
const { remainder, hadBlock } = stripBlock(lines);
+ // #6799: Codex's tool approvals written inside our block are carried into the new one.
+ const span = findBlock(lines);
+ const priorServers = span.begin === -1 ? undefined : parseToml(lines.slice(span.begin, span.end + 1).join('\n')).mcp_servers;
+ const prior = isTable(priorServers) ? priorServers[block.name] : undefined;
+ const carried: CodexToolPolicy = (isTable(prior) && codexToolPolicy(prior.tools)) || {};
// Foreign ownership guard — a duplicate table definition is a hard TOML
- // parse error that would brick codex entirely.
+ // parse error that would brick codex entirely. A table holding only Codex's
+ // tool settings is not a server definition (#6799).
const remainderText = remainder.join('\n');
let parsedRemainder: Record<string, unknown>;
try {
@@ -245,7 +289,7 @@ export function writeCodexHttpServerBlock(
);
}
const servers = parsedRemainder.mcp_servers;
- if (typeof servers === 'object' && servers !== null && (servers as Record<string, unknown>)[block.name] !== undefined) {
+ if (isTable(servers) && servers[block.name] !== undefined && !isToolsOnly(servers[block.name])) {
throw new Error(
`[mcp_servers.${block.name}] is already defined in ${configPath} outside the gbrain-managed block — ` +
`refusing to double-define it (that is a hard TOML parse error). ` +
@@ -258,13 +302,15 @@ export function writeCodexHttpServerBlock(
const trimmed = [...remainder];
while (trimmed.length > 0 && trimmed[trimmed.length - 1].trim() === '') trimmed.pop();
const body = trimmed.length > 0 ? [...trimmed, ''] : [];
- const nextLines = [...body, ...renderBlock(block), ''];
+ const nextLines = [...body, ...renderBlock(block, carried), ''];
const nextText = nextLines.join('\n');
// Post-render validation: parse + assert OUR table's keys are exactly ours.
const rendered = parseToml(nextText);
const renderedServers = rendered.mcp_servers as Record<string, unknown> | undefined;
- const problem = validateOurKeys(renderedServers?.[block.name]);
+ const ours = renderedServers?.[block.name] as Record<string, unknown> | undefined;
+ const lost = Object.keys(carried).find(tool => canonicalJson((ours?.tools as CodexToolPolicy | undefined)?.[tool]) !== canonicalJson(carried[tool]));
+ const problem = validateOurKeys(ours) ?? (lost === undefined ? null : `Codex settings for tool ${lost} did not round-trip`);
if (problem !== null) {
throw new Error(
`post-render validation failed: [mcp_servers.${block.name}] ${problem} — original file left untouched.`,
diff --git a/src/core/harness/install.ts b/src/core/harness/install.ts
index 3154408d9d..fedb2c14ac 100644
--- a/src/core/harness/install.ts
+++ b/src/core/harness/install.ts
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
import { acquireBootstrapLock } from '../bootstrap/lock.ts';
import { claudeUserMcpConfigPath, codexConfigPath, opencodeGlobalConfigPath, opencodeGlobalSiblingPath, CODEX_TOML_BLOCK_BEGIN } from '../bootstrap/host-specs.ts';
-import { writeCodexHttpServerBlock, removeCodexHttpServerBlock } from '../bootstrap/codex-toml.ts';
+import { writeCodexHttpServerBlock, removeCodexHttpServerBlock, codexToolPolicy, codexToolsOutsideBlock } from '../bootstrap/codex-toml.ts';
import { writeOpencodeMcpEntry, removeOpencodeMcpEntry, parseOpencodeConfig } from '../bootstrap/opencode-json.ts';
import { renderAgentLauncher } from '../agent-install/launcher.ts';
import { isValidName, shellQuote } from '../mcp-registration.ts';
@@ -74,8 +74,22 @@ export function inlineTokenReceipt(c: HarnessCredentials, harness: string, name:
};
}
-function assertEntryOwned(entry: unknown, prior: Record<string, any>) {
- if (entry !== undefined && (!prior.client_id || ![prior.entry_hash, prior.pending_entry_hash].includes(hash(entry)))) throw new Error('configuration_conflict: refusing to replace an unowned or edited MCP entry');
+/**
+ * #6799: the hash gbrain owns a native entry by. A Codex entry's `tools` table
+ * holds Codex's own per-tool settings ("always allow"), so it is left out;
+ * every other key, including any unexpected one, stays covered.
+ */
+function ownedEntryHash(entry: unknown, connection: string): string {
+ if (connection !== 'codex-toml' || !entry || typeof entry !== 'object' || codexToolPolicy((entry as Record<string, unknown>).tools) === null) return hash(entry);
+ const { tools: _tools, ...owned } = entry as Record<string, unknown>;
+ return hash(owned);
+}
+
+/** Owned when the receipt recorded either hash: the current one or the whole-entry hash older installs wrote. */
+function assertEntryOwned(entry: unknown, prior: Record<string, any>, connection: string) {
+ if (entry === undefined) return;
+ const recorded = [prior.entry_hash, prior.pending_entry_hash];
+ if (!prior.client_id || ![hash(entry), ownedEntryHash(entry, connection)].some(h => recorded.includes(h))) throw new Error('configuration_conflict: refusing to replace an unowned or edited MCP entry');
}
/** Install only in the current environment. Foreign entries are never adopted. */
@@ -114,7 +128,11 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
const prior = readJson(receiptPath);
if (prior.client_id && (prior.client_id !== c.client_id || prior.mcp_url !== c.mcp_url)) throw new Error('configuration_conflict: connection name belongs to another client');
const before = nativeEntry(configPath, adapter.connection, name);
- assertEntryOwned(before, prior);
+ assertEntryOwned(before, prior, adapter.connection);
+ if (opts.remove && adapter.connection === 'codex-toml' && existsSync(configPath)) {
+ const orphaned = codexToolsOutsideBlock(readFileSync(configPath, 'utf8'), name);
+ if (orphaned.length) throw new Error(`configuration_conflict: Codex tool settings for ${orphaned.join(', ')} ([mcp_servers.${name}.tools.*]) sit outside the gbrain-managed block; removing the server would leave them without one. Delete those tables in ${configPath}, then re-run.`);
+ }
if (adapter.connection === 'opencode-json') {
const sibling = opencodeGlobalSiblingPath(configPath);
if (sibling && nativeEntry(sibling, adapter.connection, name) !== undefined) throw new Error('configuration_conflict: same-name entry in sibling opencode config; preserve it and choose one explicit configuration before installing');
@@ -123,7 +141,7 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
const entry = adapter.connection === 'codex-toml' ? { url: c.mcp_url, http_headers: { Authorization: `Bearer ${token}` } }
: adapter.connection === 'opencode-json' ? { type: 'remote', url: c.mcp_url, headers: { Authorization: `Bearer ${token}` }, enabled: true }
: { type: 'http', url: c.mcp_url, headers: { Authorization: `Bearer ${token}` } };
- if (!opts.remove) atomicWriteTextFile(receiptPath, `${JSON.stringify({ ...prior, ...common, status: 'prepared', entry_hash: before === undefined ? null : hash(before), pending_entry_hash: hash(entry), config_path: configPath })}\n`, { forceMode: 0o600 });
+ if (!opts.remove) atomicWriteTextFile(receiptPath, `${JSON.stringify({ ...prior, ...common, status: 'prepared', entry_hash: before === undefined ? null : ownedEntryHash(before, adapter.connection), pending_entry_hash: hash(entry), config_path: configPath })}\n`, { forceMode: 0o600 });
if (adapter.connection === 'codex-toml') {
if (opts.remove) removeCodexHttpServerBlock(configPath, name);
else writeCodexHttpServerBlock(configPath, { name, url: c.mcp_url, bearerToken: token });
@@ -151,7 +169,7 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
next_action: pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'
: 'The client configuration was removed. Revoke the grant on the brain host if access should end.' };
}
- const nextReceipt = { ...common, entry_hash: hash(nativeEntry(configPath, adapter.connection, name)), status: 'installed',
+ const nextReceipt = { ...common, entry_hash: ownedEntryHash(nativeEntry(configPath, adapter.connection, name), adapter.connection), status: 'installed',
...inlineTokenReceipt(c, adapter.id, name, configPath, adapter.reload, opts.credentialsFile) };
atomicWriteTextFile(receiptPath, `${JSON.stringify(nextReceipt, null, 2)}\n`, { forceMode: 0o600 });
const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });
diff --git a/test/codex-toml.test.ts b/test/codex-toml.test.ts
index 63ea3d2881..79909ac5f6 100644
--- a/test/codex-toml.test.ts
+++ b/test/codex-toml.test.ts
@@ -10,6 +10,7 @@ import { describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, statSync, writeFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import * as codexToml from '../src/core/bootstrap/codex-toml.ts';
import {
detectForeignCodexServer,
removeCodexHttpServerBlock,
@@ -19,6 +20,8 @@ import {
} from '../src/core/bootstrap/codex-toml.ts';
import { CODEX_TOML_BLOCK_BEGIN, CODEX_TOML_BLOCK_END } from '../src/core/bootstrap/host-specs.ts';
+// Read through the namespace so a tree without it reports the missing behaviour, not an import error.
+const codexToolsOutsideBlock = (text: string, name: string): string[] => (codexToml as Record<string, any>).codexToolsOutsideBlock(text, name);
const BLOCK = { name: 'gbrain', url: 'http://127.0.0.1:3131/mcp', bearerToken: 'gbrain_deadbeef' };
function tmpConfig(): string {
@@ -173,6 +176,38 @@ describe('writeCodexHttpServerBlock', () => {
});
});
+describe('Codex tool settings (#6799)', () => {
+ const approval = '[mcp_servers.gbrain.tools.search]\napproval_mode = "approve"\n';
+ const parsedEntry = (path: string) => (Bun.TOML.parse(readFileSync(path, 'utf8')) as any).mcp_servers.gbrain;
+
+ test('settings inside the block are carried through a rewrite', () => {
+ const path = tmpConfig();
+ writeCodexHttpServerBlock(path, BLOCK);
+ writeFileSync(path, readFileSync(path, 'utf8').replace(CODEX_TOML_BLOCK_END, `${approval}${CODEX_TOML_BLOCK_END}`));
+ writeCodexHttpServerBlock(path, { ...BLOCK, bearerToken: 'gbrain_rotated' });
+ const text = readFileSync(path, 'utf8');
+ expect(text.indexOf('[mcp_servers.gbrain.tools.search]')).toBeLessThan(text.indexOf(CODEX_TOML_BLOCK_END));
+ expect(parsedEntry(path)).toEqual({ url: BLOCK.url, http_headers: { Authorization: 'Bearer gbrain_rotated' }, tools: { search: { approval_mode: 'approve' } } });
+ });
+
+ test('a settings-only table outside the block is not a foreign server; one with server keys still is', () => {
+ const path = tmpConfig();
+ writeCodexHttpServerBlock(path, BLOCK);
+ writeFileSync(path, `${readFileSync(path, 'utf8')}\n${approval}`);
+ expect(detectForeignCodexServer(readFileSync(path, 'utf8'), 'gbrain')).toBe(false);
+ expect(codexToolsOutsideBlock(readFileSync(path, 'utf8'), 'gbrain')).toEqual(['search']);
+ writeCodexHttpServerBlock(path, { ...BLOCK, bearerToken: 'gbrain_rotated' });
+ expect(parsedEntry(path).tools).toEqual({ search: { approval_mode: 'approve' } });
+ expect(readFileSync(path, 'utf8').split('[mcp_servers.gbrain.tools.search]').length - 1).toBe(1);
+
+ const foreign = tmpConfig();
+ const text = `[mcp_servers.gbrain]\ncommand = "npx"\n${approval}`;
+ writeFileSync(foreign, text);
+ expect(detectForeignCodexServer(text, 'gbrain')).toBe(true);
+ expect(() => writeCodexHttpServerBlock(foreign, BLOCK)).toThrow(/already defined/);
+ });
+});
+
describe('removeCodexHttpServerBlock', () => {
test('removes exactly the block; foreign content byte-identical; .bak 0600', () => {
const path = tmpConfig();
diff --git a/test/harness-install-ownership.test.ts b/test/harness-install-ownership.test.ts
index 782e2d249c..6dc9b15a07 100644
--- a/test/harness-install-ownership.test.ts
+++ b/test/harness-install-ownership.test.ts
@@ -1,4 +1,6 @@
-import { afterEach, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { CODEX_TOML_BLOCK_END } from '../src/core/bootstrap/host-specs.ts';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -69,6 +71,64 @@ for (const harness of ['codex', 'opencode']) test(`${harness} refuses edited and
expect(readFileSync(configPath, 'utf8')).toBe(original);
});
+describe('#6799 Codex tool approvals ("always allow")', () => {
+ const approval = (tool: string) => `[mcp_servers.gbrain.tools.${tool}]\napproval_mode = "approve"\n`;
+ const entryOf = (configPath: string) => (Bun.TOML.parse(readFileSync(configPath, 'utf8')) as any).mcp_servers.gbrain;
+ const wholeHash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
+ const receiptPath = (root: string) => join(root, '.gbrain-connection-codex-gbrain.json');
+ const renewed = { ...credentials, access_token: 'renewed-token-not-real' };
+
+ test('an install keyed by the legacy whole-entry hash renews with approvals inside the block and keeps them', async () => {
+ const root = temp(); const configPath = join(root, 'config.toml');
+ await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ expect(JSON.parse(readFileSync(receiptPath(root), 'utf8')).entry_hash).toBe(wholeHash(entryOf(configPath)));
+ writeFileSync(configPath, readFileSync(configPath, 'utf8').replace(CODEX_TOML_BLOCK_END, `${approval('search')}${CODEX_TOML_BLOCK_END}`));
+ expect((await installHarnessConnection(renewed, { harness: 'codex', configPath })).status).toBe('installed');
+ const entry = entryOf(configPath);
+ expect(entry.http_headers.Authorization).toBe('Bearer renewed-token-not-real');
+ expect(entry.tools).toEqual({ search: { approval_mode: 'approve' } });
+ expect((await installHarnessConnection(credentials, { harness: 'codex', configPath })).status).toBe('installed');
+ expect(entryOf(configPath).tools).toEqual({ search: { approval_mode: 'approve' } });
+ });
+
+ test('approvals after the block renew in place; removal refuses rather than orphan them', async () => {
+ const root = temp(); const configPath = join(root, 'config.toml');
+ await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ writeFileSync(configPath, `${readFileSync(configPath, 'utf8')}\n${approval('get_page')}`);
+ expect((await installHarnessConnection(renewed, { harness: 'codex', configPath })).status).toBe('installed');
+ expect(entryOf(configPath).tools).toEqual({ get_page: { approval_mode: 'approve' } });
+ expect(entryOf(configPath).http_headers.Authorization).toBe('Bearer renewed-token-not-real');
+ const before = readFileSync(configPath, 'utf8');
+ await expect(installHarnessConnection(renewed, { harness: 'codex', configPath, remove: true })).rejects.toThrow('outside the gbrain-managed block');
+ expect(readFileSync(configPath, 'utf8')).toBe(before);
+ });
+
+ test('a receipt that recorded the whole entry with its approvals still owns it', async () => {
+ const root = temp(); const configPath = join(root, 'config.toml');
+ await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ writeFileSync(configPath, readFileSync(configPath, 'utf8').replace(CODEX_TOML_BLOCK_END, `${approval('search')}${CODEX_TOML_BLOCK_END}`));
+ const receipt = JSON.parse(readFileSync(receiptPath(root), 'utf8'));
+ writeFileSync(receiptPath(root), JSON.stringify({ ...receipt, entry_hash: wholeHash(entryOf(configPath)) }));
+ expect((await installHarnessConnection(renewed, { harness: 'codex', configPath })).status).toBe('installed');
+ });
+
+ test('approvals never bless other edits: a changed URL, header or execution key still refuses', async () => {
+ for (const edit of [
+ (t: string) => t.replace('https://brain.example.com/mcp', 'https://elsewhere.example.com/mcp'),
+ (t: string) => t.replace('fixture-token-not-real', 'edited-token'),
+ (t: string) => t.replace(CODEX_TOML_BLOCK_END, `${approval('search')}[mcp_servers.gbrain.env]\nEXTRA = "1"\n${CODEX_TOML_BLOCK_END}`),
+ (t: string) => t.replace(CODEX_TOML_BLOCK_END, `[mcp_servers.gbrain.tools.search]\napproval_mode = { nested = "x" }\n${CODEX_TOML_BLOCK_END}`),
+ ]) {
+ const root = temp(); const configPath = join(root, 'config.toml');
+ await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ const edited = edit(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, edited);
+ await expect(installHarnessConnection(renewed, { harness: 'codex', configPath })).rejects.toThrow('edited');
+ expect(readFileSync(configPath, 'utf8')).toBe(edited);
+ }
+ });
+});
+
test('credentials and roots reject intermediate symlinks and credential-bearing issuer URLs', async () => {
const root = temp(); const real = join(root, 'real'); mkdirSync(real);
symlinkSync(real, join(root, 'alias'));