From bcc9c0d9e19def6ab62a2020695a2f4452e8cdfd Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 30 May 2026 11:19:12 -0700 Subject: [PATCH] Deduplicate Codex hook trust blocks (#3196) Co-authored-by: Orca Co-authored-by: brennanb2025 --- src/main/codex/config-toml-trust.test.ts | 242 ++++++++++++++++++++ src/main/codex/config-toml-trust.ts | 277 +++++++++++++---------- src/main/codex/hook-service.test.ts | 77 ++++++- src/main/codex/hook-service.ts | 8 +- 4 files changed, 484 insertions(+), 120 deletions(-) diff --git a/src/main/codex/config-toml-trust.test.ts b/src/main/codex/config-toml-trust.test.ts index 763dcca58..d3501323e 100644 --- a/src/main/codex/config-toml-trust.test.ts +++ b/src/main/codex/config-toml-trust.test.ts @@ -11,9 +11,11 @@ import { } from 'fs' import { tmpdir } from 'os' import { join } from 'path' +import { escapeRegex } from '../../shared/string-utils' import { computeTrustKey, computeTrustedHash, + escapeTomlString, parseTrustKey, readHookTrustEntries, removeHookTrustEntries, @@ -341,6 +343,49 @@ describe('upsertHookTrustEntries', () => { expect(occurrences).toHaveLength(1) }) + it('collapses duplicate blocks for the same hook key while preserving unrelated hook state', () => { + const key = + 'C:\\Users\\me\\AppData\\Roaming\\orca\\codex-runtime-home\\home\\hooks.json:session_start:0:0' + const unrelatedKey = + 'C:\\Users\\me\\AppData\\Roaming\\orca\\codex-runtime-home\\home\\hooks.json:stop:0:0' + const original = [ + `[hooks.state."${escapeTomlString(key)}"]`, + 'enabled = true', + 'trusted_hash = "sha256:STALE1"', + '', + `[hooks.state."${escapeTomlString(unrelatedKey)}"]`, + 'enabled = true', + 'trusted_hash = "sha256:KEEP"', + '', + `[hooks.state."${escapeTomlString(key)}"]`, + 'enabled = false', + 'trusted_hash = "sha256:STALE2"', + '' + ].join('\r\n') + writeFileSync(configPath, original, 'utf-8') + + const entry: CodexTrustEntry = { + sourcePath: 'C:\\Users\\me\\AppData\\Roaming\\orca\\codex-runtime-home\\home\\hooks.json', + eventLabel: 'session_start', + groupIndex: 0, + handlerIndex: 0, + command: 'echo session' + } + upsertHookTrustEntries(configPath, [entry]) + + const written = readFileSync(configPath, 'utf-8') + const duplicateKeyOccurrences = written.match( + new RegExp(`\\[hooks\\.state\\."${escapeRegex(escapeTomlString(key))}"\\]`, 'g') + ) + expect(duplicateKeyOccurrences).toHaveLength(1) + expect(written).toContain(`[hooks.state."${escapeTomlString(unrelatedKey)}"]`) + expect(written).toContain('trusted_hash = "sha256:KEEP"') + expect(written).toContain('enabled = false') + expect(written).not.toContain('STALE1') + expect(written).not.toContain('STALE2') + expect(written).toContain(`trusted_hash = "${computeTrustedHash(entry)}"`) + }) + it('writes a .bak file before overwriting an existing config', () => { writeFileSync(configPath, 'model = "old"\n', 'utf-8') upsertHookTrustEntries(configPath, [ @@ -517,6 +562,96 @@ describe('upsertHookTrustEntries', () => { ) }) + it('does not treat the target hook header inside a multi-line basic string as a duplicate', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const original = [ + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:STALE"', + '', + '[notes]', + 'body = """', + `[hooks.state."${key}"]`, + 'is only documentation here.', + '"""', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + upsertHookTrustEntries(configPath, [ + { + sourcePath: '/x/hooks.json', + eventLabel: 'pre_tool_use', + groupIndex: 0, + handlerIndex: 0, + command: 'echo' + } + ]) + + const written = readFileSync(configPath, 'utf-8') + expect(written).toContain( + ['body = """', `[hooks.state."${key}"]`, 'is only documentation here.', '"""'].join('\n') + ) + expect(written).toContain('[notes]') + expect(written).not.toContain('sha256:STALE') + }) + + it('does not let triple quotes in comments hide an existing trust block', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const original = [ + '# user note mentions triple quote: """', + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:STALE"', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + upsertHookTrustEntries(configPath, [ + { + sourcePath: '/x/hooks.json', + eventLabel: 'pre_tool_use', + groupIndex: 0, + handlerIndex: 0, + command: 'echo' + } + ]) + + const written = readFileSync(configPath, 'utf-8') + expect(written).toContain('# user note mentions triple quote: """') + expect(written.match(/\[hooks\.state\."/g)).toHaveLength(1) + expect(written).not.toContain('sha256:STALE') + }) + + it('does not let triple quotes in single-line strings hide an existing trust block', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const original = [ + 'note = "\\"\\"\\""', + "literal_note = '\"\"\"'", + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:STALE"', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + upsertHookTrustEntries(configPath, [ + { + sourcePath: '/x/hooks.json', + eventLabel: 'pre_tool_use', + groupIndex: 0, + handlerIndex: 0, + command: 'echo' + } + ]) + + const written = readFileSync(configPath, 'utf-8') + expect(written).toContain('note = "\\"\\"\\""') + expect(written).toContain("literal_note = '\"\"\"'") + expect(written.match(/\[hooks\.state\."/g)).toHaveLength(1) + expect(written).not.toContain('sha256:STALE') + }) + it('treats `\\"""` inside a multi-line basic string as an escaped quote, not a close', () => { // Why: a basic multi-line string with `\"` escapes must not be misread as // closing early — content and any following real header must survive intact. @@ -783,6 +918,80 @@ describe('removeHookTrustEntries', () => { expect(written).toContain('[unrelated]\nvalue = 42') }) + it('removes duplicate blocks for the requested key', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const otherKey = '/x/hooks.json:post_tool_use:0:0' + const original = [ + `[hooks.state."${key}"]`, + 'enabled = false', + 'trusted_hash = "sha256:A"', + '', + `[hooks.state."${otherKey}"]`, + 'enabled = true', + 'trusted_hash = "sha256:OTHER"', + '', + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:B"', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + removeHookTrustEntries(configPath, [key]) + + const written = readFileSync(configPath, 'utf-8') + expect(written).not.toContain(`[hooks.state."${key}"]`) + expect(written).not.toContain('sha256:A') + expect(written).not.toContain('sha256:B') + expect(written).toContain(`[hooks.state."${otherKey}"]`) + expect(written).toContain('sha256:OTHER') + }) + + it('does not remove the target hook header text inside a multi-line string', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const original = [ + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:K"', + '', + '[notes]', + 'body = """', + `[hooks.state."${key}"]`, + 'is only documentation here.', + '"""', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + removeHookTrustEntries(configPath, [key]) + + const written = readFileSync(configPath, 'utf-8') + expect(written).not.toContain('sha256:K') + expect(written).toContain('[notes]') + expect(written).toContain( + ['body = """', `[hooks.state."${key}"]`, 'is only documentation here.', '"""'].join('\n') + ) + }) + + it('does not let triple quotes in comments hide a block being removed', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const original = [ + '# user note mentions triple quote: """', + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:K"', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + removeHookTrustEntries(configPath, [key]) + + const written = readFileSync(configPath, 'utf-8') + expect(written).toContain('# user note mentions triple quote: """') + expect(written).not.toContain(`[hooks.state."${key}"]`) + expect(written).not.toContain('sha256:K') + }) + it('preserves the line separator when no blank line precedes the removed block', () => { // Why: regression — removeTrustBlock used to cut from match.index (the // captured leading newline) and fused the previous content into the next @@ -873,6 +1082,39 @@ describe('readHookTrustEntries', () => { expect(result.get(keyB)?.enabled).toBe(true) }) + it('does not let triple quotes in comments hide later trust entries', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const original = [ + '# user note mentions triple quote: """', + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:AAA"', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + const result = readHookTrustEntries(configPath) + + expect(result.get(key)).toEqual({ trustedHash: 'sha256:AAA', enabled: true }) + }) + + it('does not let triple quotes in single-line strings hide later trust entries', () => { + const key = '/x/hooks.json:pre_tool_use:0:0' + const original = [ + 'note = "\\"\\"\\""', + "literal_note = '\"\"\"'", + `[hooks.state."${key}"]`, + 'enabled = true', + 'trusted_hash = "sha256:AAA"', + '' + ].join('\n') + writeFileSync(configPath, original, 'utf-8') + + const result = readHookTrustEntries(configPath) + + expect(result.get(key)).toEqual({ trustedHash: 'sha256:AAA', enabled: true }) + }) + it('unescapes `\\\\` in the block key', () => { // Why: a real Windows path on disk like C:\foo gets written escaped as // `C:\\foo` inside the TOML key — the returned Map should expose the diff --git a/src/main/codex/config-toml-trust.ts b/src/main/codex/config-toml-trust.ts index d4f2026e1..626c80f8a 100644 --- a/src/main/codex/config-toml-trust.ts +++ b/src/main/codex/config-toml-trust.ts @@ -307,9 +307,8 @@ export function escapeTomlString(value: string): string { } function upsertTrustBlock(content: string, key: string, hash: string): string { - const headerPattern = buildHeaderPattern(key) - const match = headerPattern.exec(content) - if (!match) { + const ranges = findTrustBlockRanges(content, key) + if (ranges.length === 0) { const block = buildTrustBlock(key, hash, true) if (content.length === 0) { return `${block}\n` @@ -320,46 +319,74 @@ function upsertTrustBlock(content: string, key: string, hash: string): string { const separator = content.endsWith('\n\n') ? '' : content.endsWith('\n') ? '\n' : '\n\n' return `${content}${separator}${block}\n` } - const headerStart = match.index + (match[1] ? match[1].length : 0) - const headerLineEnd = match.index + match[0].length - // Why: find the next top-level table header [...] so we replace ONLY this - // block. Comments and blank lines between us and the next header are part - // of our block and get rewritten — Codex itself only writes the two known - // fields, so this is safe. - const after = content.slice(headerLineEnd) - const nextHeaderRel = findNextTableHeader(after) - const blockEnd = nextHeaderRel === -1 ? content.length : headerLineEnd + nextHeaderRel + // Why: preserve a user-set `enabled = false` so a hand-disabled hook is not // silently re-enabled by the next auto-install on app start. - const existingBlock = content.slice(headerLineEnd, blockEnd) - const enabledMatch = /^[ \t]*enabled[ \t]*=[ \t]*(true|false)[ \t\r]*(?:#.*)?$/m.exec( - existingBlock - ) - const enabled = enabledMatch ? enabledMatch[1] === 'true' : true + // If duplicate blocks already exist, treat any disabled copy as authoritative + // while collapsing the malformed TOML back to one table. + const enabled = !ranges.some((range) => { + const existingBlock = content.slice(range.headerLineEnd, range.end) + const enabledMatch = /^[ \t]*enabled[ \t]*=[ \t]*(true|false)[ \t\r]*(?:#.*)?$/m.exec( + existingBlock + ) + return enabledMatch?.[1] === 'false' + }) const block = buildTrustBlock(key, hash, enabled) - return `${content.slice(0, headerStart)}${block}\n${content.slice(blockEnd)}` + let cursor = 0 + let deduped = '' + ranges.forEach((range, index) => { + deduped += content.slice(cursor, range.start) + if (index === 0) { + deduped += `${block}\n` + } + cursor = range.end + }) + return deduped + content.slice(cursor) } // Why: Codex emits the canonical form with the key double-quoted; we never // share this slot with another tool, so we don't bother accepting bare -// dotted-key variants. -// Why: accept both LF and CRLF — Windows editors (and some user-edited files) -// terminate the header line with \r\n. -// Why: TOML allows leading whitespace before headers, so accept indented -// headers — the reader does too, and a column-0-only writer would otherwise -// append a duplicate block on hand-indented configs. -// Why: trailing newline is a lookahead so a header at EOS without a final -// newline still matches (otherwise we append a duplicate block). -// Why: TOML allows `# inline comment` after `]`, so accept it before the -// line-end lookahead — otherwise a user-annotated header would force the -// no-match branch and append a duplicate block. -function buildHeaderPattern(key: string): RegExp { +// dotted-key variants. The caller applies this only to complete physical lines +// outside TOML multi-line strings. +function buildHeaderLinePattern(key: string): RegExp { const escapedKey = escapeRegex(escapeTomlString(key)) return new RegExp( - `(^|\\r?\\n)[ \\t]*\\[hooks\\.state\\."${escapedKey}"\\][ \\t]*(?:#[^\\r\\n]*)?(?=\\r?\\n|$)` + `^[ \\t]*\\[hooks\\.state\\."${escapedKey}"\\][ \\t]*(?:#[^\\r\\n]*)?$` ) } +type TrustBlockRange = { + start: number + headerLineEnd: number + end: number +} + +function findTrustBlockRanges(content: string, key: string): TrustBlockRange[] { + const headerPattern = buildHeaderLinePattern(key) + const ranges: TrustBlockRange[] = [] + let cursor = 0 + let multilineState: TomlMultilineState = { basic: false, literal: false } + while (cursor < content.length) { + const newlineIdx = content.indexOf('\n', cursor) + const lineEnd = newlineIdx === -1 ? content.length : newlineIdx + const rawLine = content.slice(cursor, lineEnd) + const line = rawLine.replace(/\r$/, '') + const nextCursor = newlineIdx === -1 ? content.length : newlineIdx + 1 + if (!isInsideTomlMultilineString(multilineState) && headerPattern.test(line)) { + const headerLineEnd = rawLine.endsWith('\r') ? lineEnd - 1 : lineEnd + const after = content.slice(headerLineEnd) + const nextHeaderRel = findNextTableHeader(after) + const blockEnd = nextHeaderRel === -1 ? content.length : headerLineEnd + nextHeaderRel + ranges.push({ start: cursor, headerLineEnd, end: blockEnd }) + cursor = Math.max(blockEnd, nextCursor) + continue + } + multilineState = updateTomlMultilineState(multilineState, line) + cursor = nextCursor + } + return ranges +} + function buildProjectHeaderPattern(projectPath: string): RegExp { const escapedPath = escapeRegex(escapeTomlString(projectPath)) return new RegExp( @@ -371,22 +398,13 @@ function buildProjectHeaderPattern(projectPath: string): RegExp { // a flat regex misclassifies both cases. function findNextTableHeader(text: string): number { let cursor = 0 - let inMultilineBasic = false - let inMultilineLiteral = false + let multilineState: TomlMultilineState = { basic: false, literal: false } while (cursor < text.length) { const newlineIdx = text.indexOf('\n', cursor) const lineEnd = newlineIdx === -1 ? text.length : newlineIdx const rawLine = text.slice(cursor, lineEnd) const line = rawLine.replace(/\r$/, '') - if (inMultilineBasic) { - if (countUnescapedTripleQuote(line, '"""') % 2 === 1) { - inMultilineBasic = false - } - } else if (inMultilineLiteral) { - if (countTripleQuote(line, "'''") % 2 === 1) { - inMultilineLiteral = false - } - } else { + if (!isInsideTomlMultilineString(multilineState)) { const trimmed = line.trimStart() // Why: stop at both `[table]` and `[[array.of.tables]]` — both end our // block. Skipping `[[ ]]` here would let our slice consume past array @@ -394,14 +412,8 @@ function findNextTableHeader(text: string): number { if (trimmed.startsWith('[') && isCompleteTableHeader(trimmed)) { return cursor } - // Odd count means this line opens a multi-line string without closing it. - if (countUnescapedTripleQuote(line, '"""') % 2 === 1) { - inMultilineBasic = true - } - if (countTripleQuote(line, "'''") % 2 === 1) { - inMultilineLiteral = true - } } + multilineState = updateTomlMultilineState(multilineState, line) if (newlineIdx === -1) { return -1 } @@ -410,38 +422,6 @@ function findNextTableHeader(text: string): number { return -1 } -// Why: literal strings (`'''`) don't honor escapes, so a plain indexOf scan -// suffices. -function countTripleQuote(line: string, quote: string): number { - let count = 0 - let i = 0 - while ((i = line.indexOf(quote, i)) !== -1) { - count++ - i += 3 - } - return count -} - -// Why: basic multi-line strings honor `\"` (and `\\`) escapes. Skip past -// `\` so an escaped quote doesn't count toward triple-quote scans. -function countUnescapedTripleQuote(line: string, quote: '"""'): number { - let count = 0 - let i = 0 - while (i < line.length) { - if (line[i] === '\\' && i + 1 < line.length) { - i += 2 - continue - } - if (line.startsWith(quote, i)) { - count++ - i += 3 - continue - } - i++ - } - return count -} - // Why: walk the header byte-by-byte so `]` inside a quoted key segment // doesn't terminate us early. Basic strings honor `\` escapes; literal // strings (single quotes) don't allow escapes per TOML spec. @@ -500,6 +480,92 @@ function isCompleteTableHeader(line: string): boolean { return false } +type TomlMultilineState = { + basic: boolean + literal: boolean +} + +type TomlMultilineMode = 'basic' | 'literal' | null + +function isInsideTomlMultilineString(state: TomlMultilineState): boolean { + return state.basic || state.literal +} + +function updateTomlMultilineState(state: TomlMultilineState, line: string): TomlMultilineState { + let mode: TomlMultilineMode = state.basic ? 'basic' : state.literal ? 'literal' : null + let index = 0 + while (index < line.length) { + if (mode === 'basic') { + if (line[index] === '\\') { + index += 2 + continue + } + if (line.startsWith('"""', index)) { + mode = null + index += 3 + continue + } + index++ + continue + } + if (mode === 'literal') { + if (line.startsWith("'''", index)) { + mode = null + index += 3 + continue + } + index++ + continue + } + + const char = line[index] + if (char === '#') { + break + } + if (line.startsWith('"""', index)) { + mode = 'basic' + index += 3 + continue + } + if (line.startsWith("'''", index)) { + mode = 'literal' + index += 3 + continue + } + if (char === '"') { + index = skipTomlBasicString(line, index + 1) + continue + } + if (char === "'") { + index = skipTomlLiteralString(line, index + 1) + continue + } + index++ + } + return { basic: mode === 'basic', literal: mode === 'literal' } +} + +function skipTomlBasicString(line: string, startIndex: number): number { + let index = startIndex + while (index < line.length) { + const char = line[index] + if (char === '\\') { + index += 2 + continue + } + if (char === '"') { + return index + 1 + } + index++ + } + return index +} + +function skipTomlLiteralString(line: string, startIndex: number): number { + const endIndex = line.indexOf("'", startIndex) + return endIndex === -1 ? line.length : endIndex + 1 +} + // Why: same atomic-rename + .bak rotation pattern as writeHooksJson — a // half-written config.toml can brick a user's Codex install, so write to // tmp and rename. Random-suffix tmp name avoids cross-process races on @@ -543,19 +609,18 @@ export function removeHookTrustEntries(configPath: string, keys: readonly string } function removeTrustBlock(content: string, key: string): string { - const headerPattern = buildHeaderPattern(key) - const match = headerPattern.exec(content) - if (!match) { + const ranges = findTrustBlockRanges(content, key) + if (ranges.length === 0) { return content } - // Why: skip past the captured leading newline so we don't fuse the previous - // line into the next header (e.g. `a = 1[other]` — invalid TOML). - const cutStart = match.index + (match[1] ? match[1].length : 0) - const headerLineEnd = match.index + match[0].length - const after = content.slice(headerLineEnd) - const nextHeaderRel = findNextTableHeader(after) - const cutEnd = nextHeaderRel === -1 ? content.length : headerLineEnd + nextHeaderRel - return content.slice(0, cutStart) + content.slice(cutEnd) + + let cursor = 0 + let updated = '' + for (const range of ranges) { + updated += content.slice(cursor, range.start) + cursor = range.end + } + return updated + content.slice(cursor) } export function readHookTrustEntries(configPath: string): Map { @@ -570,29 +635,16 @@ export function readHookTrustEntries(configPath: string): Map { const service = new CodexHookService() expect(service.install().state).toBe('installed') + const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home') + const managedHooksPath = join(managedCodexHome, 'hooks.json') + const runtimeTomlPath = join(managedCodexHome, 'config.toml') + const permissionRequestHeader = hookTrustHeader(`${managedHooksPath}:permission_request:0:0`) + const installedToml = readFileSync(runtimeTomlPath, 'utf-8') + const permissionRequestIndex = installedToml.indexOf(permissionRequestHeader) + expect(permissionRequestIndex).not.toBe(-1) + const nextHeaderIndex = installedToml.indexOf( + '\n[', + permissionRequestIndex + permissionRequestHeader.length + ) + const permissionRequestBlock = installedToml.slice( + permissionRequestIndex, + nextHeaderIndex === -1 ? installedToml.length : nextHeaderIndex + ) + writeFileSync( + runtimeTomlPath, + `${installedToml.trimEnd()}\n\n${permissionRequestBlock.trimEnd()}\n`, + 'utf-8' + ) const status = service.refreshRuntimeUserHooks() expect(status.state).toBe('not_installed') expect(status.managedHooksPresent).toBe(false) - const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home') - const managedHooksPath = join(managedCodexHome, 'hooks.json') const runtimeHooks = JSON.parse(readFileSync(managedHooksPath, 'utf-8')) as { hooks: Record } @@ -574,7 +592,7 @@ describe('CodexHookService', () => { expect(runtimeCommands).toEqual(['user-stop-hook']) expect(runtimeCommands.some((command) => command.includes('codex-hook'))).toBe(false) - const runtimeToml = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8') + const runtimeToml = readFileSync(runtimeTomlPath, 'utf-8') expect(runtimeToml).toContain( `${hookTrustHeader(`${managedHooksPath}:stop:0:0`)}\nenabled = false` ) @@ -911,6 +929,59 @@ describe('CodexHookService', () => { expect(trustConfig).not.toContain('model = "runtime-model"') }) + it('repairs duplicate managed SessionStart trust tables on restart install', () => { + const systemCodexHome = join(tmpHome, '.codex') + mkdirSync(systemCodexHome, { recursive: true }) + writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "system-model"\n', 'utf-8') + + const service = new CodexHookService() + expect(service.install().state).toBe('installed') + + const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home') + const managedHooksPath = join(managedCodexHome, 'hooks.json') + const runtimeTomlPath = join(managedCodexHome, 'config.toml') + const sessionStartHeader = hookTrustHeader(`${managedHooksPath}:session_start:0:0`) + const installedToml = readFileSync(runtimeTomlPath, 'utf-8') + const sessionStartIndex = installedToml.indexOf(sessionStartHeader) + expect(sessionStartIndex).not.toBe(-1) + const nextHeaderIndex = installedToml.indexOf( + '\n[', + sessionStartIndex + sessionStartHeader.length + ) + const sessionStartBlock = installedToml + .slice(sessionStartIndex, nextHeaderIndex === -1 ? installedToml.length : nextHeaderIndex) + .trimEnd() + const staleDisabledBlock = sessionStartBlock + .replace('enabled = true', 'enabled = false') + .replace(/trusted_hash = "[^"]+"/, 'trusted_hash = "sha256:STALE_DISABLED"') + const staleEnabledBlock = sessionStartBlock.replace( + /trusted_hash = "[^"]+"/, + 'trusted_hash = "sha256:STALE_ENABLED"' + ) + writeFileSync( + runtimeTomlPath, + `${installedToml.slice( + 0, + sessionStartIndex + )}${staleDisabledBlock}\n\n${staleEnabledBlock}${installedToml.slice( + nextHeaderIndex === -1 ? installedToml.length : nextHeaderIndex + )}`, + 'utf-8' + ) + expect(readFileSync(runtimeTomlPath, 'utf-8').split(sessionStartHeader)).toHaveLength(3) + + // Why: preserving `enabled = false` is the repair contract; status can be + // partial because the user-disabled managed hook remains disabled. + expect(['installed', 'partial']).toContain(service.install().state) + + const repairedToml = readFileSync(runtimeTomlPath, 'utf-8') + expect(repairedToml.split(sessionStartHeader)).toHaveLength(2) + expect(repairedToml).toContain('enabled = false') + expect(repairedToml).not.toContain('STALE_DISABLED') + expect(repairedToml).not.toContain('STALE_ENABLED') + expect(repairedToml).toContain('model = "system-model"') + }) + it('preserves runtime-only project trust while honoring system project untrust', () => { const systemCodexHome = join(tmpHome, '.codex') mkdirSync(systemCodexHome, { recursive: true }) diff --git a/src/main/codex/hook-service.ts b/src/main/codex/hook-service.ts index bda41ad1b..4c4de7bc4 100644 --- a/src/main/codex/hook-service.ts +++ b/src/main/codex/hook-service.ts @@ -857,8 +857,10 @@ export class CodexHookService { // Why: system user hook approvals are mirrored into runtime CODEX_HOME. // If the user later revokes approval in ~/.codex/config.toml, preserving // all old runtime [hooks.state.*] blocks would keep Orca Codex trusted. - removeStaleRuntimeHookTrustEntries(tomlPath, configPath, trustEntries) + // Upsert first so duplicate repair can preserve a disabled managed copy + // before stale cleanup removes old managed hook keys. upsertHookTrustEntries(tomlPath, trustEntries) + removeStaleRuntimeHookTrustEntries(tomlPath, configPath, trustEntries) applyMirroredRuntimeUserHookTrustStates(tomlPath, mirroredUserTrustEntries) } catch (error) { return { @@ -998,8 +1000,10 @@ export class CodexHookService { syncSystemConfigIntoManagedCodexHome() // Why: this path is used when Orca status hooks are disabled. The // runtime CODEX_HOME should keep user hooks, but not Orca-managed trust. - removeStaleRuntimeHookTrustEntries(tomlPath, configPath, trustEntries) + // Write current mirrored user trust first so stale cleanup compares + // against current hashes while deleting old managed hook keys. upsertHookTrustEntries(tomlPath, trustEntries) + removeStaleRuntimeHookTrustEntries(tomlPath, configPath, trustEntries) applyMirroredRuntimeUserHookTrustStates(tomlPath, hookPlan.trustEntries) } catch (error) { return {