Isolate Codex hooks in Orca runtime home (#2350)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-05-25 15:07:40 -07:00
committed by GitHub
co-authored by Orca
parent 3a40c62169
commit a2c71461b4
59 changed files with 3923 additions and 722 deletions
+264
View File
@@ -0,0 +1,264 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import type * as NodeOs from 'node:os'
import { join } from 'node:path'
const { getPathMock, homedirMock } = vi.hoisted(() => ({
getPathMock: vi.fn<(name: string) => string>(),
homedirMock: vi.fn<() => string>()
}))
vi.mock('electron', () => ({
app: {
getPath: getPathMock
}
}))
vi.mock('node:os', async () => {
const actual = await vi.importActual<typeof NodeOs>('node:os')
return {
...actual,
homedir: homedirMock
}
})
import { syncSystemConfigIntoManagedCodexHome } from './codex-config-mirror'
let fakeHomeDir: string
let userDataDir: string
let previousUserDataPath: string | undefined
function getSystemCodexHomePath(): string {
return join(fakeHomeDir, '.codex')
}
function getSystemConfigPath(): string {
return join(getSystemCodexHomePath(), 'config.toml')
}
function getRuntimeConfigPath(): string {
return join(userDataDir, 'codex-runtime-home', 'home', 'config.toml')
}
beforeEach(() => {
fakeHomeDir = mkdtempSync(join(tmpdir(), 'orca-codex-config-home-'))
userDataDir = mkdtempSync(join(tmpdir(), 'orca-codex-config-user-data-'))
previousUserDataPath = process.env.ORCA_USER_DATA_PATH
process.env.ORCA_USER_DATA_PATH = userDataDir
homedirMock.mockReturnValue(fakeHomeDir)
getPathMock.mockImplementation((name: string) => {
if (name === 'userData') {
return userDataDir
}
throw new Error(`unexpected app.getPath(${name})`)
})
mkdirSync(getSystemCodexHomePath(), { recursive: true })
})
afterEach(() => {
rmSync(fakeHomeDir, { recursive: true, force: true })
rmSync(userDataDir, { recursive: true, force: true })
if (previousUserDataPath === undefined) {
delete process.env.ORCA_USER_DATA_PATH
} else {
process.env.ORCA_USER_DATA_PATH = previousUserDataPath
}
vi.clearAllMocks()
})
describe('syncSystemConfigIntoManagedCodexHome', () => {
it('seeds a missing runtime config without copying system hook trust', () => {
writeFileSync(
getSystemConfigPath(),
[
'model = "system-model"',
'',
'[hooks.state."system-hooks:stop:0:0"]',
'enabled = true',
'trusted_hash = "sha256:system"',
'',
'[projects."/repo"]',
'trust_level = "trusted"',
''
].join('\n'),
'utf-8'
)
syncSystemConfigIntoManagedCodexHome()
const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8')
expect(runtimeConfig).toContain('model = "system-model"')
expect(runtimeConfig).toContain('[projects."/repo"]')
expect(runtimeConfig).not.toContain('[hooks.state."system-hooks:stop:0:0"]')
})
it('normalizes deprecated codex_hooks feature flag only in runtime config', () => {
writeFileSync(
getSystemConfigPath(),
['model = "system-model"', '', '[features]', 'codex_hooks = true', ''].join('\n'),
'utf-8'
)
syncSystemConfigIntoManagedCodexHome()
const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8')
expect(runtimeConfig).toContain('[features]\nhooks = true')
expect(runtimeConfig).not.toContain('codex_hooks')
expect(readFileSync(getSystemConfigPath(), 'utf-8')).toContain('codex_hooks = true')
})
it('drops deprecated codex_hooks when the new hooks flag already exists', () => {
writeFileSync(
getSystemConfigPath(),
['[features]', 'hooks = true', 'codex_hooks = true', ''].join('\n'),
'utf-8'
)
syncSystemConfigIntoManagedCodexHome()
const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8')
expect(runtimeConfig).toContain('[features]\nhooks = true')
expect(runtimeConfig).not.toContain('codex_hooks')
})
it('mirrors system config updates while preserving runtime-owned trust sections', () => {
mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true })
writeFileSync(
getRuntimeConfigPath(),
[
'model = "runtime-model"',
'',
'[hooks.state."runtime-hooks:stop:0:0"]',
'enabled = false',
'trusted_hash = "sha256:runtime"',
'',
'[projects."/repo"]',
'trust_level = "trusted"',
'',
'[projects."/runtime-only"]',
'trust_level = "trusted"',
''
].join('\n'),
'utf-8'
)
writeFileSync(
getSystemConfigPath(),
[
'model = "system-model"',
'',
'[projects."/repo"] # explicit revocation',
'trust_level = "untrusted"',
'',
'[projects."/system-only"]',
'trust_level = "trusted"',
'',
'[hooks.state."system-hooks:stop:0:0"]',
'enabled = true',
'trusted_hash = "sha256:system"',
''
].join('\n'),
'utf-8'
)
syncSystemConfigIntoManagedCodexHome()
const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8')
expect(runtimeConfig).toContain('model = "system-model"')
expect(runtimeConfig).not.toContain('model = "runtime-model"')
expect(runtimeConfig).toContain('[projects."/repo"]')
expect(runtimeConfig).toContain('[projects."/runtime-only"]')
expect(runtimeConfig).toContain('[projects."/system-only"]')
expect(runtimeConfig).toContain('[hooks.state."runtime-hooks:stop:0:0"]')
expect(runtimeConfig).not.toContain('[hooks.state."system-hooks:stop:0:0"]')
expect(runtimeConfig).toContain('trust_level = "untrusted"')
expect(runtimeConfig.match(/\[projects\."\/repo"\]/g)?.length).toBe(1)
})
it('does not treat TOML table headers inside multiline strings as sections', () => {
mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true })
writeFileSync(
getRuntimeConfigPath(),
[
'[hooks.state."runtime-hooks:stop:0:0"]',
'enabled = true',
'trusted_hash = "sha256:runtime"',
''
].join('\n'),
'utf-8'
)
writeFileSync(
getSystemConfigPath(),
[
'instructions = """',
'[hooks.state."inside-basic-string"]',
'trusted_hash = "not-a-section"',
'"""',
'',
"literal_instructions = '''",
'[hooks.state."inside-literal-string"]',
"'''",
'',
'[model_providers.openai]',
'name = "OpenAI"',
''
].join('\n'),
'utf-8'
)
syncSystemConfigIntoManagedCodexHome()
const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8')
expect(runtimeConfig).toContain('[hooks.state."inside-basic-string"]')
expect(runtimeConfig).toContain('[hooks.state."inside-literal-string"]')
expect(runtimeConfig).toContain('[model_providers.openai]')
expect(runtimeConfig).toContain('[hooks.state."runtime-hooks:stop:0:0"]')
})
it('does not let triple quotes in comments affect runtime-owned section mirroring', () => {
mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true })
writeFileSync(
getRuntimeConfigPath(),
[
'# example: """ in a comment',
"# example: ''' in a comment",
'model = "runtime-model"',
'',
'[hooks.state."runtime-hooks:stop:0:0"]',
'enabled = true',
'trusted_hash = "sha256:runtime"',
''
].join('\n'),
'utf-8'
)
writeFileSync(
getSystemConfigPath(),
[
'# system example: """ in a comment',
"# system example: ''' in a comment",
'model = "system-model"',
'',
'[hooks.state."system-hooks:stop:0:0"]',
'enabled = true',
'trusted_hash = "sha256:system"',
''
].join('\n'),
'utf-8'
)
syncSystemConfigIntoManagedCodexHome()
const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8')
expect(runtimeConfig).toContain('model = "system-model"')
expect(runtimeConfig).toContain('[hooks.state."runtime-hooks:stop:0:0"]')
expect(runtimeConfig).toContain('trusted_hash = "sha256:runtime"')
expect(runtimeConfig).not.toContain('[hooks.state."system-hooks:stop:0:0"]')
expect(runtimeConfig).not.toContain('trusted_hash = "sha256:system"')
})
it('does not create a runtime config when neither system nor runtime config exists', () => {
syncSystemConfigIntoManagedCodexHome()
expect(existsSync(getRuntimeConfigPath())).toBe(false)
})
})
+327
View File
@@ -0,0 +1,327 @@
import { existsSync, readFileSync } from 'fs'
import { join } from 'path'
import { writeFileAtomically } from '../codex-accounts/fs-utils'
import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths'
function getRuntimeCodexConfigTomlPath(): string {
return join(getOrcaManagedCodexHomePath(), 'config.toml')
}
function getSystemCodexConfigTomlPath(): string {
return join(getSystemCodexHomePath(), 'config.toml')
}
export function syncSystemConfigIntoManagedCodexHome(): void {
try {
syncSystemConfigIntoManagedCodexHomeUnsafe()
} catch (error) {
console.warn('[codex-config] Failed to mirror system Codex config:', error)
}
}
function syncSystemConfigIntoManagedCodexHomeUnsafe(): void {
const systemConfigPath = getSystemCodexConfigTomlPath()
const runtimeConfigPath = getRuntimeCodexConfigTomlPath()
const systemConfigExists = existsSync(systemConfigPath)
const runtimeConfigExists = existsSync(runtimeConfigPath)
if (!systemConfigExists && !runtimeConfigExists) {
return
}
const systemConfig = normalizeDeprecatedCodexHookFeatureFlag(
systemConfigExists ? readFileSync(systemConfigPath, 'utf-8') : ''
)
if (!runtimeConfigExists) {
// Why: trust blocks reference a hooks.json path, so system-home hook trust
// entries are not valid in Orca's runtime CODEX_HOME until install remaps them.
writeFileAtomically(runtimeConfigPath, stripRuntimeOwnedTomlSections(systemConfig))
return
}
const runtimeConfig = readFileSync(runtimeConfigPath, 'utf-8')
const mergedConfig = mergeSystemCodexConfigIntoRuntime(runtimeConfig, systemConfig)
if (mergedConfig !== runtimeConfig) {
writeFileAtomically(runtimeConfigPath, mergedConfig)
}
}
function normalizeDeprecatedCodexHookFeatureFlag(config: string): string {
if (!config.includes('codex_hooks')) {
return config
}
const lines = config.split('\n')
const featureSections: { start: number; end: number }[] = []
let featureStart: number | null = null
for (let index = 0; index <= lines.length; index += 1) {
const line = lines[index]
const isHeader = line === undefined || /^[ \t]*\[[^\]]+\][ \t]*(?:#.*)?$/.test(line)
if (!isHeader) {
continue
}
if (featureStart !== null) {
featureSections.push({ start: featureStart, end: index })
featureStart = null
}
if (line !== undefined && /^[ \t]*\[features\][ \t]*(?:#.*)?$/.test(line)) {
featureStart = index
}
}
for (const section of featureSections.reverse()) {
normalizeFeatureSectionLines(lines, section.start + 1, section.end)
}
return lines.join('\n')
}
function normalizeFeatureSectionLines(lines: string[], start: number, end: number): void {
const deprecatedIndexes: number[] = []
let hasHooksKey = false
for (let index = start; index < end; index += 1) {
const line = lines[index] ?? ''
if (/^[ \t]*hooks[ \t]*=/.test(line)) {
hasHooksKey = true
}
if (/^[ \t]*codex_hooks[ \t]*=/.test(line)) {
deprecatedIndexes.push(index)
}
}
if (deprecatedIndexes.length === 0) {
return
}
if (!hasHooksKey) {
const firstDeprecatedIndex = deprecatedIndexes.shift()
if (firstDeprecatedIndex !== undefined) {
// Why: Codex 0.133 warns on the old key. Mirror into Orca's runtime
// config using the new key without rewriting the user's real config.
lines[firstDeprecatedIndex] = lines[firstDeprecatedIndex]!.replace(
/^([ \t]*)codex_hooks([ \t]*=)/,
'$1hooks$2'
)
}
}
for (const index of deprecatedIndexes.reverse()) {
lines.splice(index, 1)
}
}
function mergeSystemCodexConfigIntoRuntime(runtimeConfig: string, systemConfig: string): string {
const runtimeSections = getTomlSections(runtimeConfig)
const runtimeProjectHeaders = new Set(
runtimeSections
.filter((section) => isRuntimeProjectTomlSection(section.header))
.map((section) => getTomlSectionHeaderKey(section.header))
)
const systemUntrustedProjectHeaders = new Set(
getTomlSections(systemConfig)
.filter((section) => isRuntimeProjectTomlSection(section.header))
.filter((section) => getProjectTrustLevel(section.block) === 'untrusted')
.map((section) => getTomlSectionHeaderKey(section.header))
)
// Why: ordinary Codex settings should mirror ~/.codex exactly; runtime hook
// trust and project trust are written under Orca's managed CODEX_HOME and
// must survive the copy unless the user explicitly revoked project trust in
// the system config.
return joinTomlBlocks([
stripRuntimeOwnedTomlSections(systemConfig, runtimeProjectHeaders),
...runtimeSections
.filter((section) => isRuntimePreservedTomlSection(section.header))
.filter(
(section) =>
!isRuntimeProjectTomlSection(section.header) ||
!systemUntrustedProjectHeaders.has(getTomlSectionHeaderKey(section.header))
)
.map((section) => section.block)
])
}
type TomlSection = {
header: string
block: string
start: number
}
type TomlMultilineState = {
basic: boolean
literal: boolean
}
type TomlMultilineMode = 'basic' | 'literal' | null
function stripRuntimeOwnedTomlSections(
config: string,
runtimeProjectHeaders = new Set<string>()
): string {
const lines = config.split('\n')
const sections = getTomlSections(config)
const firstSectionIndex = sections[0]?.start ?? -1
const preamble = firstSectionIndex === -1 ? config : lines.slice(0, firstSectionIndex).join('\n')
return joinTomlBlocks([
preamble,
...sections
.filter((section) => !isRuntimeHookTrustTomlSection(section.header))
.filter(
(section) =>
!isRuntimeProjectTomlSection(section.header) ||
!runtimeProjectHeaders.has(getTomlSectionHeaderKey(section.header)) ||
getProjectTrustLevel(section.block) === 'untrusted'
)
.map((section) => section.block)
])
}
function getTomlSections(config: string): TomlSection[] {
const lines = config.split('\n')
const sections: TomlSection[] = []
let sectionStart = -1
let sectionHeader: string | null = null
let multilineState: TomlMultilineState = { basic: false, literal: false }
for (let index = 0; index < lines.length; index += 1) {
const header = isInsideTomlMultilineString(multilineState)
? null
: getTomlTableHeader(lines[index] ?? '')
if (!header) {
multilineState = updateTomlMultilineState(multilineState, lines[index] ?? '')
continue
}
if (sectionStart !== -1) {
sections.push({
header: sectionHeader ?? '',
block: lines.slice(sectionStart, index).join('\n'),
start: sectionStart
})
}
sectionStart = index
sectionHeader = header
multilineState = updateTomlMultilineState(multilineState, lines[index] ?? '')
}
if (sectionStart !== -1) {
sections.push({
header: sectionHeader ?? '',
block: lines.slice(sectionStart).join('\n'),
start: sectionStart
})
}
return sections
}
function isRuntimePreservedTomlSection(header: string): boolean {
return isRuntimeHookTrustTomlSection(header) || isRuntimeProjectTomlSection(header)
}
function isRuntimeHookTrustTomlSection(header: string): boolean {
return header.trimStart().startsWith('[hooks.state.')
}
function isRuntimeProjectTomlSection(header: string): boolean {
return header.trimStart().startsWith('[projects.')
}
function getTomlSectionHeaderKey(header: string): string {
return header.trim()
}
function getProjectTrustLevel(block: string): 'trusted' | 'untrusted' | null {
const match =
/^[ \t]*trust_level[ \t]*=[ \t]*(?:"(trusted|untrusted)"|'(trusted|untrusted)')[ \t\r]*(?:#.*)?$/m.exec(
block
)
const trustLevel = match?.[1] ?? match?.[2] ?? null
return trustLevel === 'trusted' || trustLevel === 'untrusted' ? trustLevel : null
}
function joinTomlBlocks(blocks: string[]): string {
const normalizedBlocks = blocks.map((block) => block.trim()).filter((block) => block.length > 0)
return normalizedBlocks.length === 0 ? '' : `${normalizedBlocks.join('\n\n')}\n`
}
function getTomlTableHeader(line: string): string | null {
const match = /^(\s*\[\[?.+\]\]?\s*)(?:#.*)?$/.exec(line)
return match?.[1] ?? 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 += 1
continue
}
if (mode === 'literal') {
if (line.startsWith("'''", index)) {
mode = null
index += 3
continue
}
index += 1
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 += 1
}
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 += 1
}
return index
}
function skipTomlLiteralString(line: string, startIndex: number): number {
const endIndex = line.indexOf("'", startIndex)
return endIndex === -1 ? line.length : endIndex + 1
}
+220
View File
@@ -0,0 +1,220 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
existsSync,
lstatSync,
mkdtempSync,
mkdirSync,
readFileSync,
readlinkSync,
rmSync,
symlinkSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import type * as NodeFs from 'node:fs'
import type * as NodeOs from 'node:os'
import { join } from 'node:path'
const { getPathMock, homedirMock } = vi.hoisted(() => ({
getPathMock: vi.fn<(name: string) => string>(),
homedirMock: vi.fn<() => string>()
}))
const { fsMockState } = vi.hoisted(() => ({
fsMockState: { failSymlink: false }
}))
vi.mock('node:fs', async () => {
const actual = await vi.importActual<typeof NodeFs>('node:fs')
return {
...actual,
symlinkSync: (...args: Parameters<typeof actual.symlinkSync>) => {
if (fsMockState.failSymlink) {
throw new Error('symlink disabled for test')
}
return actual.symlinkSync(...args)
}
}
})
vi.mock('electron', () => ({
app: {
getPath: getPathMock
}
}))
vi.mock('node:os', async () => {
const actual = await vi.importActual<typeof NodeOs>('node:os')
return {
...actual,
homedir: homedirMock
}
})
import { syncSystemCodexResourcesIntoManagedHome } from './codex-home-paths'
let fakeHomeDir: string
let userDataDir: string
let previousUserDataPath: string | undefined
function getSystemCodexHomePath(): string {
return join(fakeHomeDir, '.codex')
}
function getRuntimeCodexHomePath(): string {
return join(userDataDir, 'codex-runtime-home', 'home')
}
function normalizeLinkTarget(linkTarget: string): string {
return process.platform === 'win32'
? linkTarget.replace(/^\\\\\?\\/, '').toLowerCase()
: linkTarget
}
function expectSymbolicLinkTargetIfLinked(targetPath: string, sourcePath: string): void {
if (!lstatSync(targetPath).isSymbolicLink()) {
return
}
expect(normalizeLinkTarget(readlinkSync(targetPath))).toBe(normalizeLinkTarget(sourcePath))
}
function mockElectronAppPaths(): void {
vi.doMock('electron', () => ({
app: {
getPath: getPathMock
}
}))
}
beforeEach(() => {
mockElectronAppPaths()
fsMockState.failSymlink = false
fakeHomeDir = mkdtempSync(join(tmpdir(), 'orca-codex-resource-home-'))
userDataDir = mkdtempSync(join(tmpdir(), 'orca-codex-resource-user-data-'))
previousUserDataPath = process.env.ORCA_USER_DATA_PATH
process.env.ORCA_USER_DATA_PATH = userDataDir
homedirMock.mockReturnValue(fakeHomeDir)
getPathMock.mockImplementation((name: string) => {
if (name === 'userData') {
return userDataDir
}
throw new Error(`unexpected app.getPath(${name})`)
})
mkdirSync(getSystemCodexHomePath(), { recursive: true })
})
afterEach(() => {
rmSync(fakeHomeDir, { recursive: true, force: true })
rmSync(userDataDir, { recursive: true, force: true })
if (previousUserDataPath === undefined) {
delete process.env.ORCA_USER_DATA_PATH
} else {
process.env.ORCA_USER_DATA_PATH = previousUserDataPath
}
vi.clearAllMocks()
})
describe('syncSystemCodexResourcesIntoManagedHome', () => {
it('uses ORCA_USER_DATA_PATH when Electron cannot be required', async () => {
vi.resetModules()
vi.doMock('electron', () => {
throw new Error('electron unavailable in packaged CLI')
})
const previousUserDataPath = process.env.ORCA_USER_DATA_PATH
process.env.ORCA_USER_DATA_PATH = userDataDir
try {
const { getOrcaManagedCodexHomePath: getCliSafeManagedPath } =
await import('./codex-home-paths')
expect(getCliSafeManagedPath()).toBe(join(userDataDir, 'codex-runtime-home', 'home'))
} finally {
if (previousUserDataPath === undefined) {
delete process.env.ORCA_USER_DATA_PATH
} else {
process.env.ORCA_USER_DATA_PATH = previousUserDataPath
}
mockElectronAppPaths()
vi.resetModules()
}
})
it('mirrors only user resource entries into the managed runtime home', () => {
mkdirSync(join(getSystemCodexHomePath(), 'skills', 'review'), { recursive: true })
mkdirSync(join(getSystemCodexHomePath(), 'plugins'), { recursive: true })
mkdirSync(join(getSystemCodexHomePath(), 'sessions'), { recursive: true })
writeFileSync(join(getSystemCodexHomePath(), 'skills', 'review', 'SKILL.md'), 'skill\n')
writeFileSync(join(getSystemCodexHomePath(), 'plugins', 'plugin.json'), '{}\n')
writeFileSync(join(getSystemCodexHomePath(), 'auth.json'), '{"account":"system"}\n')
writeFileSync(join(getSystemCodexHomePath(), 'hooks.json'), '{"hooks":{}}\n')
writeFileSync(join(getSystemCodexHomePath(), 'history.jsonl'), '{}\n')
syncSystemCodexResourcesIntoManagedHome()
const runtimeSkillsPath = join(getRuntimeCodexHomePath(), 'skills')
const runtimePluginsPath = join(getRuntimeCodexHomePath(), 'plugins')
expect(readFileSync(join(runtimeSkillsPath, 'review', 'SKILL.md'), 'utf-8')).toBe('skill\n')
expect(readFileSync(join(runtimePluginsPath, 'plugin.json'), 'utf-8')).toBe('{}\n')
expectSymbolicLinkTargetIfLinked(runtimeSkillsPath, join(getSystemCodexHomePath(), 'skills'))
expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions'))).toBe(false)
expect(existsSync(join(getRuntimeCodexHomePath(), 'auth.json'))).toBe(false)
expect(existsSync(join(getRuntimeCodexHomePath(), 'hooks.json'))).toBe(false)
expect(existsSync(join(getRuntimeCodexHomePath(), 'history.jsonl'))).toBe(false)
})
it('does not replace an existing runtime-owned resource entry', () => {
mkdirSync(join(getSystemCodexHomePath(), 'skills'), { recursive: true })
mkdirSync(join(getRuntimeCodexHomePath(), 'skills'), { recursive: true })
writeFileSync(join(getSystemCodexHomePath(), 'skills', 'system.md'), 'system\n')
writeFileSync(join(getRuntimeCodexHomePath(), 'skills', 'runtime.md'), 'runtime\n')
syncSystemCodexResourcesIntoManagedHome()
const runtimeSkillsPath = join(getRuntimeCodexHomePath(), 'skills')
expect(lstatSync(runtimeSkillsPath).isSymbolicLink()).toBe(false)
expect(readFileSync(join(runtimeSkillsPath, 'runtime.md'), 'utf-8')).toBe('runtime\n')
expect(existsSync(join(runtimeSkillsPath, 'system.md'))).toBe(false)
})
it('removes owned symlinks for deleted system resources without touching unrelated runtime links', () => {
const systemSkillsPath = join(getSystemCodexHomePath(), 'skills')
const runtimeSkillsPath = join(getRuntimeCodexHomePath(), 'skills')
const externalPluginsPath = join(userDataDir, 'external-plugins')
const runtimePluginsPath = join(getRuntimeCodexHomePath(), 'plugins')
mkdirSync(systemSkillsPath, { recursive: true })
mkdirSync(externalPluginsPath, { recursive: true })
mkdirSync(getRuntimeCodexHomePath(), { recursive: true })
writeFileSync(join(systemSkillsPath, 'system.md'), 'system\n')
writeFileSync(join(externalPluginsPath, 'runtime.md'), 'runtime\n')
symlinkSync(
externalPluginsPath,
runtimePluginsPath,
process.platform === 'win32' ? 'junction' : undefined
)
syncSystemCodexResourcesIntoManagedHome()
expect(lstatSync(runtimeSkillsPath).isSymbolicLink()).toBe(true)
expectSymbolicLinkTargetIfLinked(runtimeSkillsPath, systemSkillsPath)
rmSync(systemSkillsPath, { recursive: true, force: true })
syncSystemCodexResourcesIntoManagedHome()
expect(() => lstatSync(runtimeSkillsPath)).toThrow()
expect(lstatSync(runtimePluginsPath).isSymbolicLink()).toBe(true)
expectSymbolicLinkTargetIfLinked(runtimePluginsPath, externalPluginsPath)
expect(readFileSync(join(runtimePluginsPath, 'runtime.md'), 'utf-8')).toBe('runtime\n')
})
it('refreshes owned fallback copies when symlinks are unavailable', () => {
fsMockState.failSymlink = true
const systemProfilePath = join(getSystemCodexHomePath(), 'profile-v2')
const runtimeProfilePath = join(getRuntimeCodexHomePath(), 'profile-v2')
writeFileSync(systemProfilePath, 'first\n', 'utf-8')
syncSystemCodexResourcesIntoManagedHome()
writeFileSync(systemProfilePath, 'second\n', 'utf-8')
syncSystemCodexResourcesIntoManagedHome()
expect(lstatSync(runtimeProfilePath).isSymbolicLink()).toBe(false)
expect(readFileSync(runtimeProfilePath, 'utf-8')).toBe('second\n')
})
})
+229
View File
@@ -0,0 +1,229 @@
import {
cpSync,
existsSync,
lstatSync,
mkdirSync,
readFileSync,
readlinkSync,
rmdirSync,
rmSync,
symlinkSync,
unlinkSync,
writeFileSync
} from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
const CODEX_SYSTEM_RESOURCE_ENTRIES = [
'skills',
'plugins',
'plugin-state',
'profile-v2',
'themes',
'prompts'
] as const
export function getSystemCodexHomePath(): string {
return join(homedir(), '.codex')
}
export function getOrcaManagedCodexHomePath(): string {
const managedHomePath = join(getOrcaUserDataPath(), 'codex-runtime-home', 'home')
mkdirSync(managedHomePath, { recursive: true })
return managedHomePath
}
function getOrcaUserDataPath(): string {
if (process.env.ORCA_USER_DATA_PATH) {
return process.env.ORCA_USER_DATA_PATH
}
// Why: CLI hook commands import this module outside Electron. Mirror the CLI
// runtime metadata path so offline hook status/on/off uses the same userData.
if (process.platform === 'darwin') {
return join(homedir(), 'Library', 'Application Support', 'orca')
}
if (process.platform === 'win32') {
return join(process.env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), 'orca')
}
return join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'orca')
}
export function syncSystemCodexResourcesIntoManagedHome(): void {
const systemHomePath = getSystemCodexHomePath()
const managedHomePath = getOrcaManagedCodexHomePath()
for (const entryName of CODEX_SYSTEM_RESOURCE_ENTRIES) {
linkSystemCodexResource(systemHomePath, managedHomePath, entryName)
}
}
function linkSystemCodexResource(
systemHomePath: string,
managedHomePath: string,
entryName: string
): void {
const sourcePath = join(systemHomePath, entryName)
const targetPath = join(managedHomePath, entryName)
if (!existsSync(sourcePath)) {
removeCopiedResourceIfOwned(targetPath, managedHomePath, entryName, sourcePath)
return
}
if (targetAlreadyPointsToSource(targetPath, sourcePath)) {
clearCopiedResourceMarker(managedHomePath, entryName)
return
}
const shouldRefreshFallbackCopy = targetIsOwnedFallbackCopy(
targetPath,
managedHomePath,
entryName,
sourcePath
)
if (existsSync(targetPath) && !shouldRefreshFallbackCopy) {
return
}
if (shouldRefreshFallbackCopy) {
rmSync(targetPath, { recursive: true, force: true })
}
try {
const sourceStat = lstatSync(sourcePath)
symlinkSync(
sourcePath,
targetPath,
sourceStat.isDirectory() && process.platform === 'win32' ? 'junction' : undefined
)
clearCopiedResourceMarker(managedHomePath, entryName)
} catch (error) {
try {
rmSync(targetPath, { recursive: true, force: true })
// Why: Windows can reject file symlinks outside developer mode. Copy is
// a fallback for launch-time resources; mark ownership so later syncs can
// refresh the copy without touching user-created runtime resources.
cpSync(sourcePath, targetPath, { recursive: true, force: false, errorOnExist: true })
markCopiedResource(managedHomePath, entryName, sourcePath)
} catch {
console.warn('[codex-home] Failed to link system Codex resource:', entryName, error)
}
}
}
function targetAlreadyPointsToSource(targetPath: string, sourcePath: string): boolean {
try {
return (
lstatSync(targetPath).isSymbolicLink() &&
linkTargetsMatch(readlinkSync(targetPath), sourcePath)
)
} catch {
return false
}
}
function linkTargetsMatch(actualTarget: string, expectedTarget: string): boolean {
if (process.platform !== 'win32') {
return actualTarget === expectedTarget
}
return normalizeWindowsLinkTarget(actualTarget) === normalizeWindowsLinkTarget(expectedTarget)
}
function normalizeWindowsLinkTarget(linkTarget: string): string {
return linkTarget.replace(/^\\\\\?\\/, '').toLowerCase()
}
function getResourceCopyMarkerPath(managedHomePath: string, entryName: string): string {
return join(managedHomePath, '.orca-resource-copies', `${entryName}.json`)
}
function markCopiedResource(managedHomePath: string, entryName: string, sourcePath: string): void {
const markerPath = getResourceCopyMarkerPath(managedHomePath, entryName)
mkdirSync(dirname(markerPath), { recursive: true })
writeFileSync(markerPath, `${JSON.stringify({ sourcePath }, null, 2)}\n`, {
encoding: 'utf-8',
mode: 0o600
})
}
function readCopiedResourceSourcePath(managedHomePath: string, entryName: string): string | null {
try {
const parsed: unknown = JSON.parse(
readFileSync(getResourceCopyMarkerPath(managedHomePath, entryName), 'utf-8')
)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null
}
const sourcePath = 'sourcePath' in parsed ? parsed.sourcePath : null
return typeof sourcePath === 'string' ? sourcePath : null
} catch {
return null
}
}
function clearCopiedResourceMarker(managedHomePath: string, entryName: string): void {
rmSync(getResourceCopyMarkerPath(managedHomePath, entryName), { force: true })
}
function targetIsOwnedFallbackCopy(
targetPath: string,
managedHomePath: string,
entryName: string,
sourcePath: string
): boolean {
if (readCopiedResourceSourcePath(managedHomePath, entryName) !== sourcePath) {
return false
}
try {
return existsSync(targetPath) && !lstatSync(targetPath).isSymbolicLink()
} catch {
return false
}
}
function removeCopiedResourceIfOwned(
targetPath: string,
managedHomePath: string,
entryName: string,
sourcePath: string
): void {
if (removeSymlinkedResourceIfOwned(targetPath, sourcePath)) {
clearCopiedResourceMarker(managedHomePath, entryName)
return
}
if (!targetIsOwnedFallbackCopy(targetPath, managedHomePath, entryName, sourcePath)) {
return
}
rmSync(targetPath, { recursive: true, force: true })
clearCopiedResourceMarker(managedHomePath, entryName)
}
function removeSymlinkedResourceIfOwned(targetPath: string, sourcePath: string): boolean {
try {
if (!lstatSync(targetPath).isSymbolicLink()) {
return false
}
if (!linkTargetsMatch(readlinkSync(targetPath), sourcePath)) {
return false
}
return removeSymlinkEntry(targetPath)
} catch {
return false
}
}
function removeSymlinkEntry(targetPath: string): boolean {
try {
// Why: recursive rm can leave a broken directory symlink behind; unlink the
// link entry itself so deleted system resources do not linger in runtime home.
unlinkSync(targetPath)
return true
} catch {
if (process.platform !== 'win32') {
return false
}
}
try {
rmdirSync(targetPath)
return true
} catch {
return false
}
}
+40 -1
View File
@@ -1,6 +1,14 @@
/* eslint-disable max-lines -- Why: this suite keeps the hash fixture, TOML edit edge cases, and trust-state parser regressions together so Codex compatibility failures are easy to audit. */
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
rmSync,
writeFileSync
} from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import {
@@ -219,6 +227,23 @@ describe('computeTrustKey', () => {
})
).toBe('/Users/thebr/.codex/hooks.json:pre_tool_use:0:0')
})
it('uses Codex canonicalized source paths when hooks.json exists', () => {
const nestedDir = join(tmpDir, 'nested')
mkdirSync(nestedDir)
const hooksPath = join(nestedDir, '..', 'hooks.json')
writeFileSync(hooksPath, '{"hooks":{}}\n', 'utf-8')
expect(
computeTrustKey({
sourcePath: hooksPath,
eventLabel: 'user_prompt_submit',
groupIndex: 0,
handlerIndex: 0,
command: 'irrelevant'
})
).toBe(`${realpathSync.native(hooksPath)}:user_prompt_submit:0:0`)
})
})
describe('upsertHookTrustEntries', () => {
@@ -642,6 +667,20 @@ describe('upsertProjectTrustLevel', () => {
)
})
it('uses Codex canonicalized project paths when the project exists', () => {
const nestedDir = join(tmpDir, 'nested')
const projectDir = join(tmpDir, 'project')
mkdirSync(nestedDir)
mkdirSync(projectDir)
const aliasedProjectPath = join(nestedDir, '..', 'project')
const trustedPath = realpathSync.native(aliasedProjectPath)
const trustedTomlPath = trustedPath.replaceAll('\\', '\\\\').replaceAll('"', '\\"')
expect(upsertProjectTrustLevelInContent('', aliasedProjectPath, 'trusted')).toBe(
[`[projects."${trustedTomlPath}"]`, 'trust_level = "trusted"', ''].join('\n')
)
})
it('updates an existing project block without touching unrelated keys', () => {
const original = [
'model = "gpt-5.5"',
+16 -3
View File
@@ -5,6 +5,7 @@ import {
mkdirSync,
readFileSync,
renameSync,
realpathSync,
unlinkSync,
writeFileSync
} from 'fs'
@@ -101,7 +102,18 @@ export function computeTrustedHash(entry: CodexTrustEntry): string {
}
export function computeTrustKey(entry: CodexTrustEntry): string {
return `${entry.sourcePath}:${entry.eventLabel}:${entry.groupIndex}:${entry.handlerIndex}`
return `${getCodexCanonicalTrustPath(entry.sourcePath)}:${entry.eventLabel}:${entry.groupIndex}:${entry.handlerIndex}`
}
export function getCodexCanonicalTrustPath(sourcePath: string): string {
try {
// Why: Codex canonicalizes trust paths before building config keys. On
// macOS, /var is a symlink to /private/var; trusting the raw path still
// leaves the TUI in review/trust prompts.
return realpathSync.native(sourcePath)
} catch {
return sourcePath
}
}
export function parseTrustKey(key: string): {
@@ -232,13 +244,14 @@ export function upsertProjectTrustLevelInContent(
): string {
const existing =
existingContent.charCodeAt(0) === 0xfeff ? existingContent.slice(1) : existingContent
const headerPattern = buildProjectHeaderPattern(projectPath)
const trustedProjectPath = getCodexCanonicalTrustPath(projectPath)
const headerPattern = buildProjectHeaderPattern(trustedProjectPath)
const match = headerPattern.exec(existing)
const eol = existing.includes('\r\n') ? '\r\n' : '\n'
const trustLine = `trust_level = "${trustLevel}"`
if (!match) {
const block = [`[projects."${escapeTomlString(projectPath)}"]`, trustLine].join(eol)
const block = [`[projects."${escapeTomlString(trustedProjectPath)}"]`, trustLine].join(eol)
if (existing.length === 0) {
return `${block}${eol}`
}
+724 -56
View File
@@ -1,8 +1,20 @@
/* eslint-disable max-lines -- Why: this suite shares mocked homedir/userData setup across local/system Codex hook install, trust, and legacy-cleanup regressions. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync
} from 'fs'
import { tmpdir } from 'os'
import type * as Os from 'os'
import { join } from 'path'
import { wrapPosixHookCommand } from '../agent-hooks/installer-utils'
import { upsertHookTrustEntriesInContent } from './config-toml-trust'
const { getPathMock, homedirMock } = vi.hoisted(() => ({
getPathMock: vi.fn<(name: string) => string>(),
@@ -27,10 +39,13 @@ import { CodexHookService } from './hook-service'
let tmpHome: string
let userDataDir: string
let previousUserDataPath: string | undefined
beforeEach(() => {
tmpHome = mkdtempSync(join(tmpdir(), 'orca-codex-home-'))
userDataDir = mkdtempSync(join(tmpdir(), 'orca-codex-user-data-'))
previousUserDataPath = process.env.ORCA_USER_DATA_PATH
process.env.ORCA_USER_DATA_PATH = userDataDir
homedirMock.mockReturnValue(tmpHome)
getPathMock.mockImplementation((name: string) => {
if (name === 'userData') {
@@ -43,18 +58,53 @@ beforeEach(() => {
afterEach(() => {
rmSync(tmpHome, { recursive: true, force: true })
rmSync(userDataDir, { recursive: true, force: true })
if (previousUserDataPath === undefined) {
delete process.env.ORCA_USER_DATA_PATH
} else {
process.env.ORCA_USER_DATA_PATH = previousUserDataPath
}
vi.clearAllMocks()
})
function escapeTomlBasicString(value: string): string {
return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')
}
function hookTrustHeader(key: string): string {
return `[hooks.state."${escapeTomlBasicString(canonicalizeHookTrustKeyForTest(key))}"]`
}
function canonicalizeHookTrustKeyForTest(key: string): string {
const lastColon = key.lastIndexOf(':')
const secondLast = lastColon === -1 ? -1 : key.lastIndexOf(':', lastColon - 1)
const thirdLast = secondLast === -1 ? -1 : key.lastIndexOf(':', secondLast - 1)
if (thirdLast === -1) {
return key
}
const sourcePath = key.slice(0, thirdLast)
try {
return `${realpathSync.native(sourcePath)}${key.slice(thirdLast)}`
} catch {
return key
}
}
describe('CodexHookService', () => {
it('installs PermissionRequest with trust so Codex approval prompts reach Orca', () => {
const systemCodexHome = join(tmpHome, '.codex')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
join(systemCodexHome, 'config.toml'),
'model = "gpt-5.2-codex"\napproval_policy = "on-request"\n',
'utf-8'
)
const status = new CodexHookService().install()
expect(status.state).toBe('installed')
const hooksConfig = JSON.parse(
readFileSync(join(tmpHome, '.codex', 'hooks.json'), 'utf-8')
) as {
const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home')
const hooksConfig = JSON.parse(readFileSync(join(managedCodexHome, 'hooks.json'), 'utf-8')) as {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}
@@ -71,78 +121,696 @@ describe('CodexHookService', () => {
expect(hooksConfig.hooks.PermissionRequest?.[0]?.hooks?.[0]?.command).toContain('agent-hooks')
expect(hooksConfig.hooks.PermissionRequest?.[0]?.hooks?.[0]?.command).toContain('codex-hook')
const trustConfig = readFileSync(join(tmpHome, '.codex', 'config.toml'), 'utf-8')
const trustConfig = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')
expect(trustConfig).toContain('model = "gpt-5.2-codex"')
expect(trustConfig).toContain('approval_policy = "on-request"')
expect(trustConfig).toContain(':permission_request:0:0')
})
it('installs Orca status hooks in the Codex profile instead of global hooks.json', () => {
const service = new CodexHookService()
const status = service.installProfile()
it('keeps hooks isolated by Orca userData instead of mutating system ~/.codex', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
const existingSystemHooks = '{"hooks":{"Stop":[{"hooks":[{"command":"user-hook"}]}]}}\n'
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(systemHooksPath, existingSystemHooks, 'utf-8')
expect(status.state).toBe('installed')
const devUserDataDir = mkdtempSync(join(tmpdir(), 'orca-dev-codex-user-data-'))
const prodUserDataDir = mkdtempSync(join(tmpdir(), 'orca-prod-codex-user-data-'))
try {
getPathMock.mockImplementation((name: string) => {
if (name === 'userData') {
return devUserDataDir
}
throw new Error(`unexpected app.getPath(${name})`)
})
process.env.ORCA_USER_DATA_PATH = devUserDataDir
expect(new CodexHookService().install().state).toBe('installed')
const profileConfig = readFileSync(
join(tmpHome, '.codex', 'orca-agent-status.config.toml'),
'utf-8'
)
expect(profileConfig).toContain('# BEGIN ORCA AGENT STATUS HOOKS')
expect(profileConfig).toContain('[[hooks.PermissionRequest]]')
expect(profileConfig).toContain(':permission_request:0:0')
expect(profileConfig).toContain('codex-hook')
expect(service.getStatus().state).toBe('not_installed')
getPathMock.mockImplementation((name: string) => {
if (name === 'userData') {
return prodUserDataDir
}
throw new Error(`unexpected app.getPath(${name})`)
})
process.env.ORCA_USER_DATA_PATH = prodUserDataDir
expect(new CodexHookService().install().state).toBe('installed')
const devHooksPath = join(devUserDataDir, 'codex-runtime-home', 'home', 'hooks.json')
const prodHooksPath = join(prodUserDataDir, 'codex-runtime-home', 'home', 'hooks.json')
expect(existsSync(devHooksPath)).toBe(true)
expect(existsSync(prodHooksPath)).toBe(true)
const devHooks = JSON.parse(readFileSync(devHooksPath, 'utf-8')) as {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}
const prodHooks = JSON.parse(readFileSync(prodHooksPath, 'utf-8')) as {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}
expect(devHooks.hooks.Stop?.[0]?.hooks?.[0]?.command).toBe('user-hook')
expect(prodHooks.hooks.Stop?.[0]?.hooks?.[0]?.command).toBe('user-hook')
expect(
devHooks.hooks.Stop?.some((definition) =>
definition.hooks?.[0]?.command?.includes('codex-hook')
)
).toBe(true)
expect(
prodHooks.hooks.Stop?.some((definition) =>
definition.hooks?.[0]?.command?.includes('codex-hook')
)
).toBe(true)
expect(readFileSync(systemHooksPath, 'utf-8')).toBe(existingSystemHooks)
} finally {
process.env.ORCA_USER_DATA_PATH = userDataDir
rmSync(devUserDataDir, { recursive: true, force: true })
rmSync(prodUserDataDir, { recursive: true, force: true })
}
})
it('keeps the Codex profile hook-only and preserves user provider config', () => {
const service = new CodexHookService()
const baseConfigPath = join(tmpHome, '.codex', 'config.toml')
mkdirSync(join(tmpHome, '.codex'), { recursive: true })
const baseConfig = [
'model_provider = "amazon-bedrock"',
'',
'[model_providers.amazon-bedrock]',
'name = "Amazon Bedrock"',
'base_url = "https://bedrock-runtime.us-west-2.amazonaws.com"',
'env_key = "AWS_BEARER_TOKEN_BEDROCK"',
''
].join('\n')
writeFileSync(baseConfigPath, baseConfig)
const status = service.installProfile()
expect(status.state).toBe('installed')
expect(readFileSync(baseConfigPath, 'utf-8')).toBe(baseConfig)
const profileConfig = readFileSync(
join(tmpHome, '.codex', 'orca-agent-status.config.toml'),
it('mirrors trusted system user hook approvals into the runtime CODEX_HOME', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify(
{
hooks: {
Stop: [
{
matcher: '*',
hooks: [
{
type: 'command',
command: 'user-hook',
timeout: 12,
async: true,
statusMessage: 'Running user hook'
}
]
}
]
}
},
null,
2
)}\n`,
'utf-8'
)
expect(profileConfig).toContain('# BEGIN ORCA AGENT STATUS HOOKS')
expect(profileConfig).not.toContain('model_provider')
expect(profileConfig).not.toContain('model_providers')
expect(profileConfig).not.toContain('env_key')
writeFileSync(
join(systemCodexHome, 'config.toml'),
upsertHookTrustEntriesInContent('model = "system-model"\n', [
{
sourcePath: systemHooksPath,
eventLabel: 'stop',
groupIndex: 0,
handlerIndex: 0,
command: 'user-hook',
timeoutSec: 12,
async: true,
matcher: '*',
statusMessage: 'Running user hook'
}
]),
'utf-8'
)
expect(new CodexHookService().install().state).toBe('installed')
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<
string,
{ matcher?: string; hooks?: { command?: string; statusMessage?: string }[] }[]
>
}
expect(runtimeHooks.hooks.Stop?.[0]?.matcher).toBe('*')
expect(runtimeHooks.hooks.Stop?.[0]?.hooks?.[0]?.command).toBe('user-hook')
expect(runtimeHooks.hooks.Stop?.[0]?.hooks?.[0]?.statusMessage).toBe('Running user hook')
const runtimeToml = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')
expect(runtimeToml).toContain(hookTrustHeader(`${managedHooksPath}:stop:0:0`))
expect(runtimeToml).not.toContain(hookTrustHeader(`${systemHooksPath}:stop:0:0`))
})
it('removes only the Orca-managed Codex profile block', () => {
const service = new CodexHookService()
service.installProfile()
const profilePath = join(tmpHome, '.codex', 'orca-agent-status.config.toml')
const withUserConfig = `${readFileSync(profilePath, 'utf-8')}\nmodel = "gpt-5.5"\n`
writeFileSync(profilePath, withUserConfig)
it('mirrors compact-event user hook approvals and disabled trust entries', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify(
{
hooks: {
PreCompact: [{ hooks: [{ type: 'command', command: 'pre-compact-user' }] }],
PostCompact: [{ hooks: [{ type: 'command', command: 'post-compact-disabled' }] }]
}
},
null,
2
)}\n`,
'utf-8'
)
const disabledPostCompactHeader = hookTrustHeader(`${systemHooksPath}:post_compact:0:0`)
writeFileSync(
join(systemCodexHome, 'config.toml'),
upsertHookTrustEntriesInContent('model = "system-model"\n', [
{
sourcePath: systemHooksPath,
eventLabel: 'pre_compact',
groupIndex: 0,
handlerIndex: 0,
command: 'pre-compact-user'
},
{
sourcePath: systemHooksPath,
eventLabel: 'post_compact',
groupIndex: 0,
handlerIndex: 0,
command: 'post-compact-disabled'
}
]).replace(
`${disabledPostCompactHeader}\nenabled = true`,
`${disabledPostCompactHeader}\nenabled = false`
),
'utf-8'
)
const status = service.removeProfile()
expect(new CodexHookService().install().state).toBe('installed')
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<string, { hooks?: { command?: string }[] }[]>
}
expect(runtimeHooks.hooks.PreCompact?.[0]?.hooks?.[0]?.command).toBe('pre-compact-user')
expect(runtimeHooks.hooks.PostCompact?.[0]?.hooks?.[0]?.command).toBe('post-compact-disabled')
const runtimeToml = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')
expect(runtimeToml).toContain(
`${hookTrustHeader(`${managedHooksPath}:pre_compact:0:0`)}\nenabled = true`
)
expect(runtimeToml).toContain(
`${hookTrustHeader(`${managedHooksPath}:post_compact:0:0`)}\nenabled = false`
)
expect(runtimeToml).not.toContain(hookTrustHeader(`${systemHooksPath}:pre_compact:0:0`))
expect(runtimeToml).not.toContain(hookTrustHeader(`${systemHooksPath}:post_compact:0:0`))
})
it('removes runtime user hook trust after system approval is revoked', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify({
hooks: { Stop: [{ hooks: [{ type: 'command', command: 'user-hook' }] }] }
})}\n`,
'utf-8'
)
writeFileSync(
join(systemCodexHome, 'config.toml'),
upsertHookTrustEntriesInContent('model = "system-model"\n', [
{
sourcePath: systemHooksPath,
eventLabel: 'stop',
groupIndex: 0,
handlerIndex: 0,
command: 'user-hook'
}
]),
'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 runtimeUserTrustHeader = hookTrustHeader(`${managedHooksPath}:stop:0:0`)
expect(readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')).toContain(
runtimeUserTrustHeader
)
writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "system-model"\n', 'utf-8')
expect(service.install().state).toBe('installed')
const runtimeToml = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')
expect(runtimeToml).not.toContain(runtimeUserTrustHeader)
expect(runtimeToml).toContain(hookTrustHeader(`${managedHooksPath}:stop:1:0`))
})
it('refreshes mirrored system user hooks when the system hooks file changes', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify({
hooks: { Stop: [{ hooks: [{ type: 'command', command: 'user-hook-old' }] }] }
})}\n`,
'utf-8'
)
const service = new CodexHookService()
expect(service.install().state).toBe('installed')
writeFileSync(
systemHooksPath,
`${JSON.stringify({
hooks: { Stop: [{ hooks: [{ type: 'command', command: 'user-hook-new' }] }] }
})}\n`,
'utf-8'
)
expect(service.install().state).toBe('installed')
const managedHooksPath = join(userDataDir, 'codex-runtime-home', 'home', 'hooks.json')
const runtimeHooks = JSON.parse(readFileSync(managedHooksPath, 'utf-8')) as {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}
const stopCommands =
runtimeHooks.hooks.Stop?.flatMap(
(definition) => definition.hooks?.map((hook) => hook.command ?? '') ?? []
) ?? []
expect(stopCommands).toContain('user-hook-new')
expect(stopCommands).not.toContain('user-hook-old')
})
it('refreshes runtime user hooks without installing Orca-managed hooks', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify({
hooks: { Stop: [{ hooks: [{ type: 'command', command: 'user-stop-hook' }] }] }
})}\n`,
'utf-8'
)
const disabledStopHeader = hookTrustHeader(`${systemHooksPath}:stop:0:0`)
writeFileSync(
join(systemCodexHome, 'config.toml'),
upsertHookTrustEntriesInContent('model = "system-model"\n', [
{
sourcePath: systemHooksPath,
eventLabel: 'stop',
groupIndex: 0,
handlerIndex: 0,
command: 'user-stop-hook'
}
]).replace(`${disabledStopHeader}\nenabled = true`, `${disabledStopHeader}\nenabled = false`),
'utf-8'
)
const service = new CodexHookService()
expect(service.install().state).toBe('installed')
const status = service.refreshRuntimeUserHooks()
expect(status.state).toBe('not_installed')
const remaining = readFileSync(profilePath, 'utf-8')
expect(remaining).not.toContain('ORCA AGENT STATUS HOOKS')
expect(remaining).toContain('model = "gpt-5.5"')
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<string, { hooks?: { command?: string }[] }[]>
}
const runtimeCommands = Object.values(runtimeHooks.hooks).flatMap((definitions) =>
definitions.flatMap((definition) => definition.hooks?.map((hook) => hook.command ?? '') ?? [])
)
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')
expect(runtimeToml).toContain(
`${hookTrustHeader(`${managedHooksPath}:stop:0:0`)}\nenabled = false`
)
expect(runtimeToml).not.toContain(':permission_request:0:0')
})
it('does not create legacy global hooks.json when profile migration cleanup has nothing to remove', () => {
it('removes legacy Orca-managed hooks from system ~/.codex during install', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
const legacyScriptPath = join(
tmpHome,
'.orca',
'agent-hooks',
process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh'
)
const legacyCommand =
process.platform === 'win32' ? legacyScriptPath : wrapPosixHookCommand(legacyScriptPath)
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify(
{
hooks: {
Stop: [
{ hooks: [{ type: 'command', command: 'user-hook' }] },
{ hooks: [{ type: 'command', command: legacyCommand }] }
],
SessionStart: [{ hooks: [{ type: 'command', command: legacyCommand }] }]
}
},
null,
2
)}\n`,
'utf-8'
)
writeFileSync(
join(systemCodexHome, 'config.toml'),
upsertHookTrustEntriesInContent('model = "system-model"\n', [
{
sourcePath: systemHooksPath,
eventLabel: 'stop',
groupIndex: 1,
handlerIndex: 0,
command: legacyCommand
},
{
sourcePath: systemHooksPath,
eventLabel: 'session_start',
groupIndex: 0,
handlerIndex: 0,
command: legacyCommand
}
]),
'utf-8'
)
expect(new CodexHookService().install().state).toBe('installed')
const systemHooks = JSON.parse(readFileSync(systemHooksPath, 'utf-8')) as {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}
expect(systemHooks.hooks.Stop).toEqual([{ hooks: [{ type: 'command', command: 'user-hook' }] }])
expect(systemHooks.hooks.SessionStart).toBeUndefined()
const systemToml = readFileSync(join(systemCodexHome, 'config.toml'), 'utf-8')
expect(systemToml).toContain('model = "system-model"')
expect(systemToml).not.toContain(':stop:1:0')
expect(systemToml).not.toContain(':session_start:0:0')
})
it('removes the legacy Orca Codex profile file when it only contains managed hooks', () => {
const systemCodexHome = join(tmpHome, '.codex')
const profilePath = join(systemCodexHome, 'orca-agent-status.config.toml')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
profilePath,
[
'# BEGIN ORCA AGENT STATUS HOOKS',
'[[hooks.PermissionRequest]]',
'[[hooks.PermissionRequest.hooks]]',
'type = "command"',
'command = "codex-hook"',
'# END ORCA AGENT STATUS HOOKS',
''
].join('\n'),
'utf-8'
)
expect(new CodexHookService().install().state).toBe('installed')
expect(existsSync(profilePath)).toBe(false)
})
it('removes only the legacy Orca block from a user-edited Codex profile file', () => {
const systemCodexHome = join(tmpHome, '.codex')
const profilePath = join(systemCodexHome, 'orca-agent-status.config.toml')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
profilePath,
[
'model = "gpt-5.5"',
'',
'# BEGIN ORCA AGENT STATUS HOOKS',
'[[hooks.PermissionRequest]]',
'[[hooks.PermissionRequest.hooks]]',
'type = "command"',
'command = "codex-hook"',
'# END ORCA AGENT STATUS HOOKS',
''
].join('\n'),
'utf-8'
)
expect(new CodexHookService().install().state).toBe('installed')
const profileConfig = readFileSync(profilePath, 'utf-8')
expect(profileConfig).toContain('model = "gpt-5.5"')
expect(profileConfig).not.toContain('ORCA AGENT STATUS HOOKS')
expect(profileConfig).not.toContain('codex-hook')
})
it('cleans legacy system and profile hooks when runtime hooks.json is malformed during remove', () => {
const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home')
mkdirSync(managedCodexHome, { recursive: true })
writeFileSync(join(managedCodexHome, 'hooks.json'), '{not json', 'utf-8')
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
const profilePath = join(systemCodexHome, 'orca-agent-status.config.toml')
const legacyScriptPath = join(
tmpHome,
'.orca',
'agent-hooks',
process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh'
)
const legacyCommand =
process.platform === 'win32' ? legacyScriptPath : wrapPosixHookCommand(legacyScriptPath)
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify(
{
hooks: {
Stop: [
{ hooks: [{ type: 'command', command: 'user-hook' }] },
{ hooks: [{ type: 'command', command: legacyCommand }] }
],
SessionStart: [{ hooks: [{ type: 'command', command: legacyCommand }] }]
}
},
null,
2
)}\n`,
'utf-8'
)
writeFileSync(
profilePath,
[
'# BEGIN ORCA AGENT STATUS HOOKS',
'[[hooks.PermissionRequest]]',
'[[hooks.PermissionRequest.hooks]]',
'type = "command"',
'command = "codex-hook"',
'# END ORCA AGENT STATUS HOOKS',
''
].join('\n'),
'utf-8'
)
const status = new CodexHookService().remove()
expect(status.state).toBe('error')
expect(status.detail).toBe('Could not parse Codex hooks.json')
const systemHooks = JSON.parse(readFileSync(systemHooksPath, 'utf-8')) as {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}
expect(systemHooks.hooks.Stop).toEqual([{ hooks: [{ type: 'command', command: 'user-hook' }] }])
expect(systemHooks.hooks.SessionStart).toBeUndefined()
expect(existsSync(profilePath)).toBe(false)
})
it('cleans duplicate Codex hook representations while keeping status hooks in runtime CODEX_HOME', () => {
const systemCodexHome = join(tmpHome, '.codex')
const systemHooksPath = join(systemCodexHome, 'hooks.json')
const systemTomlPath = join(systemCodexHome, 'config.toml')
const legacyProfilePath = join(systemCodexHome, 'orca-agent-status.config.toml')
const legacyScriptPath = join(
tmpHome,
'.orca',
'agent-hooks',
process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh'
)
const legacyCommand =
process.platform === 'win32' ? legacyScriptPath : wrapPosixHookCommand(legacyScriptPath)
const userCommand = 'user-stop-hook'
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
systemHooksPath,
`${JSON.stringify(
{
hooks: {
Stop: [
{ hooks: [{ type: 'command', command: userCommand }] },
{ hooks: [{ type: 'command', command: legacyCommand }] }
],
SessionStart: [{ hooks: [{ type: 'command', command: legacyCommand }] }]
}
},
null,
2
)}\n`,
'utf-8'
)
writeFileSync(
systemTomlPath,
upsertHookTrustEntriesInContent(
['model = "system-model"', '', '[features]', 'codex_hooks = true', ''].join('\n'),
[
{
sourcePath: systemHooksPath,
eventLabel: 'stop',
groupIndex: 0,
handlerIndex: 0,
command: userCommand
},
{
sourcePath: systemHooksPath,
eventLabel: 'session_start',
groupIndex: 0,
handlerIndex: 0,
command: legacyCommand
}
]
),
'utf-8'
)
writeFileSync(
legacyProfilePath,
[
'# BEGIN ORCA AGENT STATUS HOOKS',
'[[hooks.PermissionRequest]]',
'[[hooks.PermissionRequest.hooks]]',
'type = "command"',
'command = "codex-hook"',
'# END ORCA AGENT STATUS HOOKS',
''
].join('\n'),
'utf-8'
)
const service = new CodexHookService()
service.installProfile()
expect(service.install().state).toBe('installed')
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<string, { hooks?: { command?: string }[] }[]>
}
const stopCommands =
runtimeHooks.hooks.Stop?.flatMap(
(definition) => definition.hooks?.map((hook) => hook.command ?? '') ?? []
) ?? []
expect(stopCommands).toContain(userCommand)
expect(stopCommands.some((command) => command.includes('codex-hook'))).toBe(true)
expect(runtimeHooks.hooks.PermissionRequest?.[0]?.hooks?.[0]?.command).toContain('codex-hook')
const runtimeToml = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')
expect(runtimeToml).toContain('[features]\nhooks = true')
expect(runtimeToml).not.toContain('codex_hooks')
expect(runtimeToml).toContain(hookTrustHeader(`${managedHooksPath}:stop:0:0`))
expect(runtimeToml).toContain(hookTrustHeader(`${managedHooksPath}:permission_request:0:0`))
const systemHooks = JSON.parse(readFileSync(systemHooksPath, 'utf-8')) as {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}
expect(systemHooks.hooks.Stop).toEqual([{ hooks: [{ type: 'command', command: userCommand }] }])
expect(systemHooks.hooks.SessionStart).toBeUndefined()
const systemToml = readFileSync(systemTomlPath, 'utf-8')
expect(systemToml).toContain('codex_hooks = true')
expect(systemToml).not.toContain(':session_start:0:0')
expect(existsSync(legacyProfilePath)).toBe(false)
expect(service.getStatus().state).toBe('installed')
})
it('removes managed trust entries when userData resolves through a symlink', () => {
const linkedUserDataDir = join(tmpHome, 'linked-user-data')
symlinkSync(userDataDir, linkedUserDataDir, process.platform === 'win32' ? 'junction' : 'dir')
process.env.ORCA_USER_DATA_PATH = linkedUserDataDir
const service = new CodexHookService()
expect(service.install().state).toBe('installed')
const linkedManagedCodexHome = join(linkedUserDataDir, 'codex-runtime-home', 'home')
const linkedHooksPath = join(linkedManagedCodexHome, 'hooks.json')
let runtimeToml = readFileSync(join(linkedManagedCodexHome, 'config.toml'), 'utf-8')
expect(runtimeToml).toContain(hookTrustHeader(`${linkedHooksPath}:permission_request:0:0`))
const status = service.remove()
expect(status.state).toBe('not_installed')
expect(existsSync(join(tmpHome, '.codex', 'hooks.json'))).toBe(false)
runtimeToml = readFileSync(join(linkedManagedCodexHome, 'config.toml'), 'utf-8')
expect(runtimeToml).not.toContain(':permission_request:0:0')
expect(runtimeToml).not.toContain(':stop:0:0')
})
it('mirrors system Codex config while preserving runtime hook trust on hook install', () => {
const systemCodexHome = join(tmpHome, '.codex')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "system-model"\n', 'utf-8')
const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home')
mkdirSync(managedCodexHome, { recursive: true })
writeFileSync(
join(managedCodexHome, 'config.toml'),
[
'model = "runtime-model"',
'',
'[hooks.state."runtime-hook"]',
'enabled = false',
'trusted_hash = "sha256:runtime"',
''
].join('\n'),
'utf-8'
)
const status = new CodexHookService().install()
expect(status.state).toBe('installed')
const trustConfig = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')
expect(trustConfig).toContain('model = "system-model"')
expect(trustConfig).toContain('[hooks.state."runtime-hook"]')
expect(trustConfig).toContain('enabled = false')
expect(trustConfig).toContain('trusted_hash = "sha256:runtime"')
expect(trustConfig).toContain(':permission_request:0:0')
expect(trustConfig).not.toContain('model = "runtime-model"')
})
it('preserves runtime-only project trust while honoring system project untrust', () => {
const systemCodexHome = join(tmpHome, '.codex')
mkdirSync(systemCodexHome, { recursive: true })
writeFileSync(
join(systemCodexHome, 'config.toml'),
['model = "system-model"', '', '[projects."/repo"]', 'trust_level = "untrusted"', ''].join(
'\n'
),
'utf-8'
)
const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home')
mkdirSync(managedCodexHome, { recursive: true })
writeFileSync(
join(managedCodexHome, 'config.toml'),
[
'model = "runtime-model"',
'',
'[projects."/repo"]',
'trust_level = "trusted"',
'',
'[projects."/runtime-only"]',
'trust_level = "trusted"',
''
].join('\n'),
'utf-8'
)
const status = new CodexHookService().install()
expect(status.state).toBe('installed')
const trustConfig = readFileSync(join(managedCodexHome, 'config.toml'), 'utf-8')
expect(trustConfig).toContain('model = "system-model"')
expect(trustConfig).toContain('[projects."/repo"]\ntrust_level = "untrusted"')
expect(trustConfig).toContain('[projects."/runtime-only"]\ntrust_level = "trusted"')
expect(trustConfig).not.toContain('model = "runtime-model"')
})
})
+529 -315
View File
@@ -1,19 +1,19 @@
/* eslint-disable max-lines -- Why: getStatus + install + remove all share the managed-command and trust-key derivation. Splitting would hide that the three operations must agree on group index, event label, and command bytes. */
import { existsSync, readFileSync, unlinkSync } from 'fs'
import { homedir } from 'os'
import { join } from 'path'
import type { SFTPWrapper } from 'ssh2'
import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types'
import { ORCA_CODEX_AGENT_STATUS_PROFILE } from '../../shared/codex-profile'
import {
createManagedCommandMatcher,
buildWindowsAgentHookPostCommand,
getSharedManagedScriptPath,
hookDefinitionHasManagedCommand,
readHooksJson,
removeManagedCommands,
wrapPosixHookCommand,
writeHooksJson,
writeManagedScript,
type HookCommandConfig,
type HookDefinition
} from '../agent-hooks/installer-utils'
import {
@@ -26,17 +26,20 @@ import {
import {
computeTrustKey,
computeTrustedHash,
escapeTomlString,
getCodexCanonicalTrustPath,
parseTrustKey,
readHookTrustEntries,
removeHookTrustEntries,
upsertHookTrustEntriesInContent,
upsertHookTrustEntries,
escapeTomlString,
writeConfigAtomically,
type CodexEventLabel,
type CodexHookTrustState,
type CodexTrustEntry
} from './config-toml-trust'
import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths'
import { syncSystemConfigIntoManagedCodexHome } from './codex-config-mirror'
// Why: PreToolUse/PostToolUse give the dashboard a live readout of the
// in-flight tool (name + input preview) between UserPromptSubmit and Stop.
@@ -53,15 +56,11 @@ const CODEX_EVENTS = [
] as const
function getConfigPath(): string {
return join(homedir(), '.codex', 'hooks.json')
return join(getOrcaManagedCodexHomePath(), 'hooks.json')
}
function getCodexConfigTomlPath(): string {
return join(homedir(), '.codex', 'config.toml')
}
function getCodexProfileTomlPath(): string {
return join(homedir(), '.codex', `${ORCA_CODEX_AGENT_STATUS_PROFILE}.config.toml`)
return join(getOrcaManagedCodexHomePath(), 'config.toml')
}
// Why: Codex's hash key uses the snake_case event label (see
@@ -77,8 +76,20 @@ const CODEX_EVENT_LABEL: Record<(typeof CODEX_EVENTS)[number], CodexEventLabel>
Stop: 'stop'
}
const ORCA_PROFILE_BLOCK_START = '# BEGIN ORCA AGENT STATUS HOOKS'
const ORCA_PROFILE_BLOCK_END = '# END ORCA AGENT STATUS HOOKS'
const CODEX_HOOK_EVENT_LABEL: Record<string, CodexEventLabel> = {
...CODEX_EVENT_LABEL,
PreCompact: 'pre_compact',
PostCompact: 'post_compact'
}
const LEGACY_ORCA_PROFILE_NAME = 'orca-agent-status'
const LEGACY_ORCA_PROFILE_BLOCK_START = '# BEGIN ORCA AGENT STATUS HOOKS'
const LEGACY_ORCA_PROFILE_BLOCK_END = '# END ORCA AGENT STATUS HOOKS'
type MirroredRuntimeUserHookTrustEntry = {
entry: CodexTrustEntry
enabled: boolean
}
function getManagedScriptFileName(): string {
return process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh'
@@ -92,6 +103,451 @@ function getManagedCommand(scriptPath: string): string {
return process.platform === 'win32' ? scriptPath : wrapPosixHookCommand(scriptPath)
}
function getSystemConfigPath(): string {
return join(getSystemCodexHomePath(), 'hooks.json')
}
function getSystemCodexConfigTomlPath(): string {
return join(getSystemCodexHomePath(), 'config.toml')
}
function getLegacyCodexProfileTomlPath(): string {
return join(getSystemCodexHomePath(), `${LEGACY_ORCA_PROFILE_NAME}.config.toml`)
}
function collectManagedTrustEntries(
sourcePath: string,
eventName: string,
definitions: readonly HookDefinition[],
isManagedCommand: (command: string | undefined) => boolean
): CodexTrustEntry[] {
const entries: CodexTrustEntry[] = []
definitions.forEach((definition, groupIndex) => {
const hooks = Array.isArray(definition.hooks) ? definition.hooks : []
hooks.forEach((hook, handlerIndex) => {
if (!isManagedCommand(hook.command)) {
return
}
const entry = createHookTrustEntry(
sourcePath,
eventName,
groupIndex,
handlerIndex,
definition,
hook
)
if (entry) {
entries.push(entry)
}
})
})
return entries
}
function createHookTrustEntry(
sourcePath: string,
eventName: string,
groupIndex: number,
handlerIndex: number,
definition: HookDefinition,
hook: HookCommandConfig
): CodexTrustEntry | null {
const eventLabel = CODEX_HOOK_EVENT_LABEL[eventName]
if (!eventLabel || !hook.command) {
return null
}
return {
sourcePath,
eventLabel,
groupIndex,
handlerIndex,
command: hook.command,
...(typeof hook.timeout === 'number' ? { timeoutSec: hook.timeout } : {}),
...(typeof hook.async === 'boolean' ? { async: hook.async } : {}),
...(typeof definition.matcher === 'string' ? { matcher: definition.matcher } : {}),
...(typeof hook.statusMessage === 'string' ? { statusMessage: hook.statusMessage } : {})
}
}
function removeMatchingTrustEntries(configPath: string, entries: readonly CodexTrustEntry[]): void {
if (entries.length === 0) {
return
}
const existingEntries = readHookTrustEntries(configPath)
const ownedKeys = entries
.map((entry) => {
const key = computeTrustKey(entry)
return existingEntries.get(key)?.trustedHash === computeTrustedHash(entry) ? key : null
})
.filter((key): key is string => key !== null)
if (ownedKeys.length > 0) {
removeHookTrustEntries(configPath, ownedKeys)
}
}
function removeStaleRuntimeHookTrustEntries(
tomlPath: string,
runtimeHooksPath: string,
expectedEntries: readonly CodexTrustEntry[]
): void {
const expectedHashes = new Map(
expectedEntries.map((entry) => [computeTrustKey(entry), computeTrustedHash(entry)])
)
const canonicalRuntimeHooksPath = getCodexCanonicalTrustPath(runtimeHooksPath)
const staleKeys: string[] = []
for (const [key, state] of readHookTrustEntries(tomlPath)) {
const parsed = parseTrustKey(key)
if (!parsed || getCodexCanonicalTrustPath(parsed.sourcePath) !== canonicalRuntimeHooksPath) {
continue
}
if (expectedHashes.get(key) === state.trustedHash) {
continue
}
staleKeys.push(key)
}
if (staleKeys.length > 0) {
removeHookTrustEntries(tomlPath, staleKeys)
}
}
function getTrustSignature(entry: CodexTrustEntry): string {
return JSON.stringify({
eventLabel: entry.eventLabel,
command: entry.command,
timeoutSec: Math.max(1, entry.timeoutSec ?? 600),
async: entry.async ?? false,
matcher: entry.matcher ?? null,
statusMessage: entry.statusMessage ?? null
})
}
function getRuntimeHooksWithSystemUserHooks(
runtimeHooks: Record<string, HookDefinition[]> | undefined,
isManagedCommand: (command: string | undefined) => boolean
): {
hooks: Record<string, HookDefinition[]>
trustEntries: MirroredRuntimeUserHookTrustEntry[]
} {
const systemConfigPath = getSystemConfigPath()
const runtimeConfigPath = getConfigPath()
if (systemConfigPath === getConfigPath()) {
return { hooks: { ...runtimeHooks }, trustEntries: [] }
}
const systemConfig = readHooksJson(systemConfigPath)
if (!systemConfig?.hooks) {
return { hooks: {}, trustEntries: [] }
}
const nextHooks: Record<string, HookDefinition[]> = {}
const trustedSystemHookSignatures = getTrustedSystemUserHookSignatures(
systemConfigPath,
systemConfig.hooks,
isManagedCommand
)
for (const [eventName, systemDefinitions] of Object.entries(systemConfig.hooks)) {
if (!Array.isArray(systemDefinitions)) {
continue
}
const systemUserDefinitions = removeManagedCommands(systemDefinitions, isManagedCommand)
if (systemUserDefinitions.length === 0) {
continue
}
// Why: runtime hooks are derived from the user's system hooks plus Orca's
// managed hooks. Reusing old runtime user-hook copies would keep deleted or
// edited ~/.codex/hooks.json entries alive for new Orca-launched sessions.
nextHooks[eventName] = dedupeHookDefinitions(systemUserDefinitions)
}
return {
hooks: nextHooks,
trustEntries: collectMirroredRuntimeUserHookTrustEntries(
runtimeConfigPath,
nextHooks,
trustedSystemHookSignatures,
isManagedCommand
)
}
}
function getTrustedSystemUserHookSignatures(
systemConfigPath: string,
systemHooks: Record<string, HookDefinition[]>,
isManagedCommand: (command: string | undefined) => boolean
): Map<string, boolean> {
const signatures = new Map<string, boolean>()
let trustEntries: Map<string, CodexHookTrustState>
try {
trustEntries = readHookTrustEntries(getSystemCodexConfigTomlPath())
} catch (error) {
// Why: a hand-broken system config.toml should only disable user-hook
// trust mirroring; Orca's managed runtime hooks can still be installed.
console.warn('[codex-hook-service] failed to read system hook trust entries', error)
return signatures
}
for (const [eventName, definitions] of Object.entries(systemHooks)) {
if (!Array.isArray(definitions)) {
continue
}
definitions.forEach((definition, groupIndex) => {
const hooks = Array.isArray(definition.hooks) ? definition.hooks : []
hooks.forEach((hook, handlerIndex) => {
if (isManagedCommand(hook.command)) {
return
}
const entry = createHookTrustEntry(
systemConfigPath,
eventName,
groupIndex,
handlerIndex,
definition,
hook
)
if (!entry) {
return
}
const state = trustEntries.get(computeTrustKey(entry))
if (state?.trustedHash === computeTrustedHash(entry)) {
const signature = getTrustSignature(entry)
const enabled = state.enabled !== false
// Why: runtime deduping collapses identical system hook definitions;
// if any duplicate remains enabled, keep the mirrored hook enabled.
if (enabled || !signatures.has(signature)) {
signatures.set(signature, enabled)
}
}
})
})
}
return signatures
}
function collectMirroredRuntimeUserHookTrustEntries(
runtimeConfigPath: string,
runtimeHooks: Record<string, HookDefinition[]>,
trustedSystemHookSignatures: ReadonlyMap<string, boolean>,
isManagedCommand: (command: string | undefined) => boolean
): MirroredRuntimeUserHookTrustEntry[] {
if (trustedSystemHookSignatures.size === 0) {
return []
}
const entries: MirroredRuntimeUserHookTrustEntry[] = []
for (const [eventName, definitions] of Object.entries(runtimeHooks)) {
if (!Array.isArray(definitions)) {
continue
}
definitions.forEach((definition, groupIndex) => {
const hooks = Array.isArray(definition.hooks) ? definition.hooks : []
hooks.forEach((hook, handlerIndex) => {
if (isManagedCommand(hook.command)) {
return
}
const entry = createHookTrustEntry(
runtimeConfigPath,
eventName,
groupIndex,
handlerIndex,
definition,
hook
)
if (!entry) {
return
}
const signature = getTrustSignature(entry)
const enabled = trustedSystemHookSignatures.get(signature)
if (enabled !== undefined) {
entries.push({ entry, enabled })
}
})
})
}
return entries
}
function escapeRegex(value: string): string {
return value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
function applyMirroredRuntimeUserHookTrustStates(
tomlPath: string,
entries: readonly MirroredRuntimeUserHookTrustEntry[]
): void {
if (entries.length === 0 || !existsSync(tomlPath)) {
return
}
const existing = readFileSync(tomlPath, 'utf-8')
let updated = existing
for (const { entry, enabled } of entries) {
const escapedKey = escapeRegex(escapeTomlString(computeTrustKey(entry)))
const pattern = new RegExp(
`(\\[hooks\\.state\\."${escapedKey}"\\]\\r?\\n[ \\t]*enabled[ \\t]*=[ \\t]*)(true|false)`
)
updated = updated.replace(pattern, `$1${enabled}`)
}
if (updated !== existing) {
writeConfigAtomically(tomlPath, updated)
}
}
function dedupeHookDefinitions(definitions: readonly HookDefinition[]): HookDefinition[] {
const seen = new Set<string>()
return definitions.filter((definition) => {
const key = JSON.stringify(definition)
if (seen.has(key)) {
return false
}
seen.add(key)
return true
})
}
function cleanupLegacySystemManagedHooks(): void {
const legacyConfigPath = getSystemConfigPath()
const runtimeConfigPath = getConfigPath()
if (legacyConfigPath === runtimeConfigPath) {
return
}
const config = readHooksJson(legacyConfigPath)
if (!config?.hooks) {
return
}
const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName())
const nextHooks = { ...config.hooks }
const trustEntries: CodexTrustEntry[] = []
let removedManagedHook = false
for (const [eventName, definitions] of Object.entries(nextHooks)) {
if (!Array.isArray(definitions)) {
continue
}
const eventTrustEntries = collectManagedTrustEntries(
legacyConfigPath,
eventName,
definitions,
isManagedCommand
)
trustEntries.push(...eventTrustEntries)
const cleaned = removeManagedCommands(definitions, isManagedCommand)
removedManagedHook ||= definitions.some((definition) =>
hookDefinitionHasManagedCommand(definition, isManagedCommand)
)
if (cleaned.length === 0) {
delete nextHooks[eventName]
} else {
nextHooks[eventName] = cleaned
}
}
// Why: Codex hooks moved to Orca's managed CODEX_HOME; old entries in
// ~/.codex would keep external Codex sessions reporting into Orca.
if (removedManagedHook) {
writeHooksJson(legacyConfigPath, { ...config, hooks: nextHooks })
}
removeMatchingTrustEntries(getSystemCodexConfigTomlPath(), trustEntries)
}
function stripLegacyManagedProfileBlock(content: string): string {
const start = content.indexOf(LEGACY_ORCA_PROFILE_BLOCK_START)
if (start === -1) {
return content
}
const endMarker = content.indexOf(LEGACY_ORCA_PROFILE_BLOCK_END, start)
const end = endMarker === -1 ? content.length : endMarker + LEGACY_ORCA_PROFILE_BLOCK_END.length
const before = content.slice(0, start).replace(/[ \t]*(?:\r?\n)*$/, '')
const after = content.slice(end).replace(/^(?:\r?\n)+/, '')
if (!before) {
return after
}
if (!after) {
return before.endsWith('\n') ? before : `${before}\n`
}
return `${before}\n\n${after}`
}
function cleanupLegacyCodexProfileHooks(): void {
const profilePath = getLegacyCodexProfileTomlPath()
if (!existsSync(profilePath)) {
return
}
const existing = readFileSync(profilePath, 'utf-8')
const next = stripLegacyManagedProfileBlock(existing)
if (next === existing) {
return
}
// Why: #2778 wrote Orca hooks into a Codex profile file. Runtime CODEX_HOME
// supersedes that representation, so remove only Orca's marked block.
if (next.trim().length === 0) {
unlinkSync(profilePath)
} else {
writeConfigAtomically(profilePath, next)
}
}
function cleanupLegacyManagedHookRepresentations(): void {
try {
cleanupLegacySystemManagedHooks()
cleanupLegacyCodexProfileHooks()
} catch (error) {
console.warn('[codex-hook-service] failed to clean legacy Codex hooks', error)
}
}
function removeRuntimeManagedHookTrustEntries(configPath: string): void {
try {
const tomlPath = getCodexConfigTomlPath()
const existingEntries = readHookTrustEntries(tomlPath)
const scriptPath = getManagedScriptPath()
const command = getManagedCommand(scriptPath)
const managedEventLabels = new Set<CodexEventLabel>(
CODEX_EVENTS.map((event) => CODEX_EVENT_LABEL[event])
)
// Why: only drop entries WE wrote. The same config.toml can contain
// user-approved trust entries for non-Orca commands, so match by hash
// equivalence to our managed command — a sourcePath-only filter would
// wipe the user's manually-approved entries.
const ourKeys: string[] = []
const canonicalConfigPath = getCodexCanonicalTrustPath(configPath)
for (const [key, state] of existingEntries) {
const parts = parseTrustKey(key)
if (parts === null) {
continue
}
if (getCodexCanonicalTrustPath(parts.sourcePath) !== canonicalConfigPath) {
continue
}
if (!managedEventLabels.has(parts.eventLabel)) {
continue
}
const expectedHash = computeTrustedHash({
sourcePath: configPath,
eventLabel: parts.eventLabel,
groupIndex: parts.groupIndex,
handlerIndex: parts.handlerIndex,
command
})
if (state.trustedHash !== expectedHash) {
continue
}
ourKeys.push(key)
}
if (ourKeys.length > 0) {
removeHookTrustEntries(tomlPath, ourKeys)
}
} catch (error) {
// Best effort — stale trust entries are harmless once hooks.json no
// longer references the hook. Log so a programmer error doesn't disappear silently.
console.warn('[codex-hook-service] failed to clean trust entries', error)
}
}
function getManagedScript(target: 'local' | 'posix' = 'local'): string {
if (target === 'local' && process.platform === 'win32') {
return [
@@ -143,198 +599,7 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string {
].join('\n')
}
function findManagedProfileBlock(content: string): string | null {
const start = content.indexOf(ORCA_PROFILE_BLOCK_START)
if (start === -1) {
return null
}
const endMarker = content.indexOf(ORCA_PROFILE_BLOCK_END, start)
const end = endMarker === -1 ? content.length : endMarker + ORCA_PROFILE_BLOCK_END.length
return content.slice(start, end)
}
function stripManagedProfileBlock(content: string): string {
const start = content.indexOf(ORCA_PROFILE_BLOCK_START)
if (start === -1) {
return content
}
const endMarker = content.indexOf(ORCA_PROFILE_BLOCK_END, start)
const end = endMarker === -1 ? content.length : endMarker + ORCA_PROFILE_BLOCK_END.length
const before = content.slice(0, start).replace(/[ \t]*(?:\r?\n)*$/, '')
const after = content.slice(end).replace(/^(?:\r?\n)+/, '')
if (!before) {
return after
}
if (!after) {
return before.endsWith('\n') ? before : `${before}\n`
}
return `${before}\n\n${after}`
}
function appendManagedProfileBlock(existing: string, block: string): string {
const trimmedExisting = stripManagedProfileBlock(existing).replace(/[ \t]*(?:\r?\n)*$/, '')
if (!trimmedExisting) {
return `${block}\n`
}
return `${trimmedExisting}\n\n${block}\n`
}
function buildProfileTrustEntry(
profilePath: string,
eventName: (typeof CODEX_EVENTS)[number],
command: string
): CodexTrustEntry {
return {
sourcePath: profilePath,
eventLabel: CODEX_EVENT_LABEL[eventName],
groupIndex: 0,
handlerIndex: 0,
command
}
}
function buildManagedProfileBlock(profilePath: string, command: string): string {
const lines = [
ORCA_PROFILE_BLOCK_START,
'# Managed by Orca so only Codex sessions launched from Orca load agent-status hooks.'
]
for (const eventName of CODEX_EVENTS) {
const entry = buildProfileTrustEntry(profilePath, eventName, command)
lines.push(
`[hooks.state."${escapeTomlString(computeTrustKey(entry))}"]`,
'enabled = true',
`trusted_hash = "${escapeTomlString(computeTrustedHash(entry))}"`,
'',
`[[hooks.${eventName}]]`,
`[[hooks.${eventName}.hooks]]`,
'type = "command"',
`command = "${escapeTomlString(command)}"`,
''
)
}
lines.push(ORCA_PROFILE_BLOCK_END)
return lines.join('\n')
}
export class CodexHookService {
getProfileStatus(): AgentHookInstallStatus {
const configPath = getCodexProfileTomlPath()
if (!existsSync(configPath)) {
return {
agent: 'codex',
state: 'not_installed',
configPath,
managedHooksPresent: false,
detail: null
}
}
const scriptPath = getManagedScriptPath()
const command = getManagedCommand(scriptPath)
const content = readFileSync(configPath, 'utf-8')
const block = findManagedProfileBlock(content)
if (!block) {
return {
agent: 'codex',
state: 'not_installed',
configPath,
managedHooksPresent: false,
detail: null
}
}
const escapedCommandLine = `command = "${escapeTomlString(command)}"`
const missing = CODEX_EVENTS.filter(
(eventName) =>
!block.includes(`[[hooks.${eventName}]]`) || !block.includes(escapedCommandLine)
)
let trustEntries: Map<string, CodexHookTrustState>
let trustReadError: string | null = null
try {
trustEntries = readHookTrustEntries(configPath)
} catch (error) {
trustEntries = new Map()
trustReadError = error instanceof Error ? error.message : String(error)
}
const trustMissing: string[] = []
const disabled: string[] = []
for (const eventName of CODEX_EVENTS) {
const entry = buildProfileTrustEntry(configPath, eventName, command)
const actualState = trustEntries.get(computeTrustKey(entry))
if (actualState?.trustedHash !== computeTrustedHash(entry)) {
trustMissing.push(eventName)
} else if (actualState.enabled === false) {
disabled.push(eventName)
}
}
if (
missing.length === 0 &&
trustMissing.length === 0 &&
disabled.length === 0 &&
!trustReadError
) {
return {
agent: 'codex',
state: 'installed',
configPath,
managedHooksPresent: true,
detail: null
}
}
const parts: string[] = []
if (missing.length > 0) {
parts.push(`Profile hook missing for events: ${missing.join(', ')}`)
}
if (trustReadError) {
parts.push(`Trust entries unverifiable: ${trustReadError}`)
} else if (trustMissing.length > 0) {
parts.push(`Trust entry missing or stale for events: ${trustMissing.join(', ')}`)
}
if (disabled.length > 0) {
parts.push(`Managed hook disabled for events: ${disabled.join(', ')}`)
}
return {
agent: 'codex',
state: 'partial',
configPath,
managedHooksPresent: true,
detail: parts.join('; ')
}
}
installProfile(): AgentHookInstallStatus {
const configPath = getCodexProfileTomlPath()
const scriptPath = getManagedScriptPath()
const command = getManagedCommand(scriptPath)
const existing = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : ''
const next = appendManagedProfileBlock(existing, buildManagedProfileBlock(configPath, command))
writeManagedScript(scriptPath, getManagedScript())
writeConfigAtomically(configPath, next)
return this.getProfileStatus()
}
removeProfile(): AgentHookInstallStatus {
const configPath = getCodexProfileTomlPath()
if (!existsSync(configPath)) {
return this.getProfileStatus()
}
const existing = readFileSync(configPath, 'utf-8')
const next = stripManagedProfileBlock(existing)
if (next === existing) {
return this.getProfileStatus()
}
if (next.trim().length === 0) {
unlinkSync(configPath)
} else {
writeConfigAtomically(configPath, next)
}
return this.getProfileStatus()
}
getStatus(): AgentHookInstallStatus {
const configPath = getConfigPath()
const scriptPath = getManagedScriptPath()
@@ -463,15 +728,15 @@ export class CodexHookService {
}
}
const command = getManagedCommand(scriptPath)
const nextHooks = { ...config.hooks }
const managedEvents = new Set<string>(CODEX_EVENTS)
// Why: match by script filename (not exact command string) so a fresh
// install sweeps stale entries left by older builds or a different
// Electron userData path (dev vs. prod). Without this, repeated installs
// accumulate duplicate hook entries pointing at defunct scripts.
const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName())
const command = getManagedCommand(scriptPath)
const hookPlan = getRuntimeHooksWithSystemUserHooks(config.hooks, isManagedCommand)
const nextHooks = hookPlan.hooks
const managedEvents = new Set<string>(CODEX_EVENTS)
// Why: sweep managed entries out of events we no longer subscribe to
// (e.g., PreToolUse from a prior install). Without this, users who
@@ -500,7 +765,8 @@ export class CodexHookService {
// hook sits in the "review required" pile. We compute the trust hash for
// each managed entry as we install it and persist it alongside hooks.json
// so the user does not have to /hooks-approve after every install.
const trustEntries: CodexTrustEntry[] = []
const mirroredUserTrustEntries = hookPlan.trustEntries
const trustEntries: CodexTrustEntry[] = mirroredUserTrustEntries.map(({ entry }) => entry)
for (const eventName of CODEX_EVENTS) {
const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : []
const cleaned = removeManagedCommands(current, isManagedCommand)
@@ -528,7 +794,14 @@ export class CodexHookService {
// pointing at a hook that doesn't exist. Surface failures — without this,
// getStatus would report green for a hook Codex won't actually fire.
try {
upsertHookTrustEntries(getCodexConfigTomlPath(), trustEntries)
const tomlPath = getCodexConfigTomlPath()
syncSystemConfigIntoManagedCodexHome()
// 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)
upsertHookTrustEntries(tomlPath, trustEntries)
applyMirroredRuntimeUserHookTrustStates(tomlPath, mirroredUserTrustEntries)
} catch (error) {
return {
agent: 'codex',
@@ -538,6 +811,12 @@ export class CodexHookService {
detail: `Hooks installed but trust entries could not be written: ${error instanceof Error ? error.message : String(error)}. Run /hooks in Codex to approve.`
}
}
try {
cleanupLegacySystemManagedHooks()
cleanupLegacyCodexProfileHooks()
} catch (error) {
console.warn('[codex-hook-service] failed to clean legacy Codex hooks', error)
}
return this.getStatus()
}
@@ -634,74 +913,48 @@ export class CodexHookService {
}
}
async installRemoteProfile(
sftp: SFTPWrapper,
remoteHome: string
): Promise<AgentHookInstallStatus> {
const normalizedHome = remoteHome.replace(/\/$/, '')
const remoteProfilePath = `${normalizedHome}/.codex/${ORCA_CODEX_AGENT_STATUS_PROFILE}.config.toml`
const remoteScriptPath = `${normalizedHome}/.orca/agent-hooks/codex-hook.sh`
const remoteGlobalConfigPath = `${normalizedHome}/.codex/hooks.json`
try {
const command = wrapPosixHookCommand(remoteScriptPath)
const existingProfile = (await readTextFileRemote(sftp, remoteProfilePath)) ?? ''
const nextProfile = appendManagedProfileBlock(
existingProfile,
buildManagedProfileBlock(remoteProfilePath, command)
)
await writeManagedScriptRemote(sftp, remoteScriptPath, getManagedScript('posix'))
if (nextProfile !== existingProfile) {
await writeTextFileRemoteAtomic(sftp, remoteProfilePath, nextProfile)
}
// Why: profile-scoped Codex hooks keep Orca out of external remote
// `codex` sessions. Sweep legacy global Orca entries left by older
// remote installers so the profile is the only active Codex hook source.
const existingGlobalConfig = await readTextFileRemote(sftp, remoteGlobalConfigPath)
if (existingGlobalConfig !== null) {
const globalConfig = await readHooksJsonRemote(sftp, remoteGlobalConfigPath)
if (globalConfig) {
let removedGlobalHooks = false
const nextHooks = { ...globalConfig.hooks }
const isManagedCommand = createManagedCommandMatcher('codex-hook.sh')
for (const [eventName, definitions] of Object.entries(nextHooks)) {
if (!Array.isArray(definitions)) {
continue
}
const cleaned = removeManagedCommands(definitions, isManagedCommand)
if (JSON.stringify(cleaned) !== JSON.stringify(definitions)) {
removedGlobalHooks = true
}
if (cleaned.length === 0) {
delete nextHooks[eventName]
} else {
nextHooks[eventName] = cleaned
}
}
if (removedGlobalHooks) {
globalConfig.hooks = nextHooks
await writeHooksJsonRemote(sftp, remoteGlobalConfigPath, globalConfig)
}
}
}
return {
agent: 'codex',
state: 'installed',
configPath: remoteProfilePath,
managedHooksPresent: true,
detail: null
}
} catch (err) {
refreshRuntimeUserHooks(): AgentHookInstallStatus {
const configPath = getConfigPath()
const config = readHooksJson(configPath)
if (!config) {
// Why: disabled launch prep used to call remove(); preserve its legacy
// cleanup behavior even when runtime hooks.json is malformed.
cleanupLegacyManagedHookRepresentations()
return {
agent: 'codex',
state: 'error',
configPath: remoteProfilePath,
configPath,
managedHooksPresent: false,
detail: err instanceof Error ? err.message : String(err)
detail: 'Could not parse Codex hooks.json'
}
}
const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName())
const hookPlan = getRuntimeHooksWithSystemUserHooks(config.hooks, isManagedCommand)
config.hooks = hookPlan.hooks
writeHooksJson(configPath, config)
try {
const tomlPath = getCodexConfigTomlPath()
const trustEntries = hookPlan.trustEntries.map(({ entry }) => entry)
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)
upsertHookTrustEntries(tomlPath, trustEntries)
applyMirroredRuntimeUserHookTrustStates(tomlPath, hookPlan.trustEntries)
} catch (error) {
return {
agent: 'codex',
state: 'error',
configPath,
managedHooksPresent: false,
detail: `User hooks refreshed but trust entries could not be written: ${error instanceof Error ? error.message : String(error)}. Run /hooks in Codex to approve.`
}
}
cleanupLegacyManagedHookRepresentations()
return this.getStatus()
}
remove(): AgentHookInstallStatus {
@@ -709,6 +962,9 @@ export class CodexHookService {
const configExists = existsSync(configPath)
const config = readHooksJson(configPath)
if (!config) {
// Why: a malformed runtime hooks.json should not strand old hooks in
// ~/.codex or the legacy profile after the user disables Codex hooks.
cleanupLegacyManagedHookRepresentations()
return {
agent: 'codex',
state: 'error',
@@ -748,51 +1004,9 @@ export class CodexHookService {
// Why: also drop our trust entries so config.toml doesn't accumulate dead
// [hooks.state."..."] blocks across install/remove cycles. Best-effort —
// a stale entry is harmless once hooks.json no longer references it.
try {
const tomlPath = getCodexConfigTomlPath()
const existingEntries = readHookTrustEntries(tomlPath)
const scriptPath = getManagedScriptPath()
const command = getManagedCommand(scriptPath)
const managedEventLabels = new Set<CodexEventLabel>(
CODEX_EVENTS.map((event) => CODEX_EVENT_LABEL[event])
)
// Why: only drop entries WE wrote. configPath (~/.codex/hooks.json) is
// shared with Codex CLI, so user-approved trust entries for non-Orca
// commands live in the same `[hooks.state.*]` namespace. Match by hash
// equivalence to our managed command — a sourcePath-only filter would
// wipe the user's manually-approved entries.
const ourKeys: string[] = []
for (const [key, state] of existingEntries) {
const parts = parseTrustKey(key)
if (parts === null) {
continue
}
if (parts.sourcePath !== configPath) {
continue
}
if (!managedEventLabels.has(parts.eventLabel)) {
continue
}
const expectedHash = computeTrustedHash({
sourcePath: configPath,
eventLabel: parts.eventLabel,
groupIndex: parts.groupIndex,
handlerIndex: parts.handlerIndex,
command
})
if (state.trustedHash !== expectedHash) {
continue
}
ourKeys.push(key)
}
if (ourKeys.length > 0) {
removeHookTrustEntries(tomlPath, ourKeys)
}
} catch (error) {
// Best effort — stale trust entries are harmless once hooks.json no
// longer references the hook. Log so a programmer error doesn't disappear silently.
console.warn('[codex-hook-service] failed to clean trust entries', error)
}
removeRuntimeManagedHookTrustEntries(configPath)
cleanupLegacyManagedHookRepresentations()
return this.getStatus()
}