Revert "fix(memory): bound OOM-prone accumulators (#10179)" (#10255)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-23 18:35:31 -07:00
committed by GitHub
co-authored by Orca
parent 6eb70d8370
commit aab112933e
1577 changed files with 15167 additions and 91655 deletions
@@ -1,96 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { pathState, ownershipMock } = vi.hoisted(() => ({
pathState: { userData: '' },
ownershipMock: vi.fn()
}))
vi.mock('./codex-home-paths', () => ({
getOrcaUserDataPath: () => pathState.userData,
getSystemCodexHomePath: () => join(pathState.userData, 'system-codex')
}))
vi.mock('../codex-accounts/host-codex-managed-home-ownership', () => ({
assertOwnedHostCodexManagedHomePath: ownershipMock
}))
import { getCodexAccountHomeSessionDirectories } from './codex-account-home-discovery'
let root = ''
let accountsRoot = ''
async function createAccount(accountId: string): Promise<string> {
const sessionsPath = join(accountsRoot, accountId, 'home', 'sessions')
await mkdir(sessionsPath, { recursive: true })
return sessionsPath
}
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-codex-account-discovery-'))
pathState.userData = root
accountsRoot = join(root, 'codex-accounts')
await mkdir(accountsRoot)
ownershipMock.mockReset()
})
afterEach(async () => {
vi.restoreAllMocks()
await rm(root, { recursive: true, force: true })
})
describe('Codex account-home discovery limits', () => {
it('preserves sorted valid account homes below every limit', async () => {
const later = await createAccount('z-account')
const earlier = await createAccount('a-account')
await writeFile(join(accountsRoot, 'not-an-account'), 'x')
expect(getCodexAccountHomeSessionDirectories()).toEqual([earlier, later])
})
it('accepts the exact entry limit and fails closed on the next entry', async () => {
const sessionsPath = await createAccount('account-1')
await writeFile(join(accountsRoot, 'ignored'), 'x')
expect(getCodexAccountHomeSessionDirectories({ maxEntries: 2 })).toEqual([sessionsPath])
await writeFile(join(accountsRoot, 'overflow'), 'x')
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
expect(getCodexAccountHomeSessionDirectories({ maxEntries: 2 })).toEqual([])
expect(warnSpy).toHaveBeenCalledWith(
'[codex-usage] Account-home discovery exceeded 2 entries; skipping homes'
)
})
it('accepts the exact home limit and fails closed on the next valid home', async () => {
await createAccount('account-1')
await createAccount('account-2')
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
expect(getCodexAccountHomeSessionDirectories({ maxHomes: 2 })).toHaveLength(2)
expect(getCodexAccountHomeSessionDirectories({ maxHomes: 1 })).toEqual([])
expect(warnSpy).toHaveBeenCalledWith(
'[codex-usage] Account-home discovery exceeded 1 homes; skipping homes'
)
})
it('bounds retained account and session path strings at the exact code-unit limit', async () => {
const accountId = 'account-1'
const sessionsPath = await createAccount(accountId)
const accountHome = join(accountsRoot, accountId, 'home')
const exactPathCodeUnits = accountId.length + accountHome.length + sessionsPath.length
expect(getCodexAccountHomeSessionDirectories({ maxPathCodeUnits: exactPathCodeUnits })).toEqual(
[sessionsPath]
)
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
expect(
getCodexAccountHomeSessionDirectories({ maxPathCodeUnits: exactPathCodeUnits - 1 })
).toEqual([])
expect(warnSpy).toHaveBeenCalledWith(
`[codex-usage] Account-home discovery exceeded ${exactPathCodeUnits - 1} path code units; skipping homes`
)
})
})
+19 -87
View File
@@ -1,102 +1,34 @@
import { lstatSync, opendirSync } from 'node:fs'
import { lstatSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
import { getOrcaUserDataPath, getSystemCodexHomePath } from './codex-home-paths'
import { assertOwnedHostCodexManagedHomePath } from '../codex-accounts/host-codex-managed-home-ownership'
export const CODEX_ACCOUNT_HOME_DISCOVERY_MAX_ENTRIES = 4096
export const CODEX_ACCOUNT_HOME_DISCOVERY_MAX_HOMES = 256
export const CODEX_ACCOUNT_HOME_DISCOVERY_MAX_PATH_CODE_UNITS = 1024 * 1024
export type CodexAccountHomeDiscoveryLimits = {
maxEntries: number
maxHomes: number
maxPathCodeUnits: number
}
/** Session roots of per-account self-contained host Codex homes present on disk.
* Why disk-enumerated, not settings-driven: rollouts retained after an account
* change must still be counted, and CLI callers have no settings store. WSL
* account homes live inside their distro and are scanned by their own lane. */
export function getCodexAccountHomeSessionDirectories(
limitOverrides: Partial<CodexAccountHomeDiscoveryLimits> = {}
): string[] {
const limits: CodexAccountHomeDiscoveryLimits = {
maxEntries: CODEX_ACCOUNT_HOME_DISCOVERY_MAX_ENTRIES,
maxHomes: CODEX_ACCOUNT_HOME_DISCOVERY_MAX_HOMES,
maxPathCodeUnits: CODEX_ACCOUNT_HOME_DISCOVERY_MAX_PATH_CODE_UNITS,
...limitOverrides
}
for (const [name, value] of Object.entries(limits)) {
if (!Number.isSafeInteger(value) || value < 0) {
throw new RangeError(`${name} must be a non-negative safe integer`)
}
}
export function getCodexAccountHomeSessionDirectories(): string[] {
const accountsRoot = join(getOrcaUserDataPath(), 'codex-accounts')
try {
const accountIds: string[] = []
let entryCount = 0
let pathCodeUnits = 0
const directory = opendirSync(accountsRoot)
try {
for (let entry = directory.readSync(); entry !== null; entry = directory.readSync()) {
entryCount += 1
if (entryCount > limits.maxEntries) {
return failCodexAccountHomeDiscovery('entries', limits.maxEntries)
return readdirSync(accountsRoot, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.flatMap((entry) => {
const accountHome = join(accountsRoot, entry.name, 'home')
try {
assertOwnedHostCodexManagedHomePath({
candidatePath: accountHome,
managedAccountsRoot: accountsRoot,
systemCodexHomePath: getSystemCodexHomePath(),
expectedAccountId: entry.name
})
const sessionsPath = join(accountHome, 'sessions')
// Why: a redirected sessions root could make usage scan unrelated, unbounded trees.
return lstatSync(sessionsPath).isDirectory() ? [sessionsPath] : []
} catch {
return []
}
pathCodeUnits += entry.name.length
if (pathCodeUnits > limits.maxPathCodeUnits) {
return failCodexAccountHomeDiscovery('path code units', limits.maxPathCodeUnits)
}
if (entry.isDirectory()) {
accountIds.push(entry.name)
}
}
} finally {
closeCodexAccountDirectory(directory)
}
const sessionDirectories: string[] = []
for (const accountId of accountIds.sort()) {
const accountHome = join(accountsRoot, accountId, 'home')
const sessionsPath = join(accountHome, 'sessions')
pathCodeUnits += accountHome.length + sessionsPath.length
if (pathCodeUnits > limits.maxPathCodeUnits) {
return failCodexAccountHomeDiscovery('path code units', limits.maxPathCodeUnits)
}
try {
assertOwnedHostCodexManagedHomePath({
candidatePath: accountHome,
managedAccountsRoot: accountsRoot,
systemCodexHomePath: getSystemCodexHomePath(),
expectedAccountId: accountId
})
// Why: a redirected sessions root could make usage scan unrelated, unbounded trees.
if (lstatSync(sessionsPath).isDirectory()) {
sessionDirectories.push(sessionsPath)
if (sessionDirectories.length > limits.maxHomes) {
return failCodexAccountHomeDiscovery('homes', limits.maxHomes)
}
}
} catch {
// A missing, redirected, or invalid account home is not a usage source.
}
}
return sessionDirectories
})
} catch {
return []
}
}
function closeCodexAccountDirectory(directory: ReturnType<typeof opendirSync>): void {
try {
directory.closeSync()
} catch {
// The OS may have already closed a failed directory stream.
}
}
function failCodexAccountHomeDiscovery(resource: string, limit: number): [] {
console.warn(`[codex-usage] Account-home discovery exceeded ${limit} ${resource}; skipping homes`)
return []
}
@@ -2,10 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import {
CODEX_APP_SERVER_CAPABILITY_RETRY_INTERVAL_MS,
CodexAppServerCapabilityCache,
getCodexAppServerHostKey,
MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS,
MAX_CODEX_APP_SERVER_HOST_KEY_CODE_UNITS,
type CodexAppServerHostKey
getCodexAppServerHostKey
} from './codex-app-server-capability-cache'
const unsupportedError = new Error('unsupported')
@@ -117,48 +114,4 @@ describe('CodexAppServerCapabilityCache', () => {
expect(getCodexAppServerHostKey({ kind: 'wsl', distro: 'Ubuntu' })).toBe('wsl:Ubuntu')
expect(getCodexAppServerHostKey({ kind: 'wsl', distro: 'Debian' })).toBe('wsl:Debian')
})
it('retains exactly the host limit and LRU-evicts on the next host', () => {
const cache = new CodexAppServerCapabilityCache()
const hostKeys = Array.from(
{ length: MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS },
(_, index): CodexAppServerHostKey => `wsl:distro-${index}`
)
hostKeys.forEach((hostKey) => cache.rememberUnsupported(hostKey, 0))
expect(cache.shouldTry(hostKeys[0], 1)).toBe(false)
cache.rememberUnsupported('wsl:overflow', 0)
expect(cache.shouldTry(hostKeys[0], 1)).toBe(false)
expect(cache.shouldTry(hostKeys[1], 1)).toBe(true)
expect(cache.shouldTry('wsl:overflow', 1)).toBe(false)
})
it('bounds oversized generated and direct host keys', () => {
const exactDistro = 'x'.repeat(MAX_CODEX_APP_SERVER_HOST_KEY_CODE_UNITS - 'wsl:'.length)
const oversizedDistro = `${exactDistro}x`
expect(getCodexAppServerHostKey({ kind: 'wsl', distro: exactDistro })).toBe(
`wsl:${exactDistro}`
)
const firstDigest = getCodexAppServerHostKey({ kind: 'wsl', distro: oversizedDistro })
expect(firstDigest).toMatch(/^wsl:sha256:[a-f0-9]{64}$/)
expect(getCodexAppServerHostKey({ kind: 'wsl', distro: oversizedDistro })).toBe(firstDigest)
const directOversized = `wsl:${oversizedDistro}` as CodexAppServerHostKey
const cache = new CodexAppServerCapabilityCache()
cache.rememberUnsupported(directOversized, 0)
expect(cache.shouldTry(directOversized, 1)).toBe(false)
})
it('clear forgets supported and unsupported host state', () => {
const cache = new CodexAppServerCapabilityCache()
cache.rememberSupported('native')
cache.rememberUnsupported('wsl:Ubuntu', 0)
cache.clear()
expect(cache.isKnownSupported('native')).toBe(false)
expect(cache.shouldTry('wsl:Ubuntu', 1)).toBe(true)
})
})
@@ -1,36 +1,18 @@
import { createHash } from 'node:crypto'
// Why: suppress a known-missing RPC surface without pinning it forever — an
// in-place codex upgrade during a long Orca session self-heals after the
// interval, mirroring GitCapabilityCache's rationale.
export const CODEX_APP_SERVER_CAPABILITY_RETRY_INTERVAL_MS = 30 * 60_000
export const MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS = 64
export const MAX_CODEX_APP_SERVER_HOST_KEY_CODE_UNITS = 4 * 1024
/** Execution host that runs the codex binary. WSL distros are isolated from
* the native host and from each other — each can carry a different codex. */
export type CodexAppServerHostKey = 'native' | `wsl:${string}`
function boundHostKey(hostKey: CodexAppServerHostKey): CodexAppServerHostKey {
if (hostKey.length <= MAX_CODEX_APP_SERVER_HOST_KEY_CODE_UNITS) {
return hostKey
}
return `wsl:sha256:${createHash('sha256').update(hostKey.slice('wsl:'.length)).digest('hex')}`
}
export function getCodexAppServerHostKey(
host: { kind: 'native' } | { kind: 'wsl'; distro: string }
): CodexAppServerHostKey {
if (host.kind === 'native') {
return 'native'
}
return boundHostKey(`wsl:${host.distro}`)
return host.kind === 'wsl' ? `wsl:${host.distro}` : 'native'
}
type CodexAppServerCapabilityState =
| { kind: 'supported' }
| { kind: 'unsupported'; retryAfterMs: number }
/**
* Capability cache for the codex app-server trust-grant RPC pair, modeled on
* GitCapabilityCache but with a synchronous runner: the grant client blocks
@@ -38,56 +20,33 @@ type CodexAppServerCapabilityState =
* unsupported mark alone is what keeps later installs off the dead probe.
*/
export class CodexAppServerCapabilityCache {
private readonly stateByHost = new Map<CodexAppServerHostKey, CodexAppServerCapabilityState>()
private getState(hostKey: CodexAppServerHostKey): CodexAppServerCapabilityState | undefined {
const retainedHostKey = boundHostKey(hostKey)
const state = this.stateByHost.get(retainedHostKey)
if (state) {
this.stateByHost.delete(retainedHostKey)
this.stateByHost.set(retainedHostKey, state)
}
return state
}
private remember(hostKey: CodexAppServerHostKey, state: CodexAppServerCapabilityState): void {
const retainedHostKey = boundHostKey(hostKey)
this.stateByHost.delete(retainedHostKey)
this.stateByHost.set(retainedHostKey, state)
while (this.stateByHost.size > MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS) {
const oldestHost = this.stateByHost.keys().next().value
if (oldestHost === undefined) {
return
}
this.stateByHost.delete(oldestHost)
}
}
private readonly retryAfterByHost = new Map<CodexAppServerHostKey, number>()
private readonly supportedHosts = new Set<CodexAppServerHostKey>()
shouldTry(hostKey: CodexAppServerHostKey, nowMs = Date.now()): boolean {
const state = this.getState(hostKey)
if (!state || state.kind === 'supported') {
const retryAfterMs = this.retryAfterByHost.get(hostKey)
if (retryAfterMs === undefined) {
return true
}
if (nowMs < state.retryAfterMs) {
if (nowMs < retryAfterMs) {
return false
}
this.stateByHost.delete(boundHostKey(hostKey))
this.retryAfterByHost.delete(hostKey)
return true
}
isKnownSupported(hostKey: CodexAppServerHostKey): boolean {
return this.getState(hostKey)?.kind === 'supported'
return this.supportedHosts.has(hostKey)
}
rememberUnsupported(hostKey: CodexAppServerHostKey, nowMs = Date.now()): void {
this.remember(hostKey, {
kind: 'unsupported',
retryAfterMs: nowMs + CODEX_APP_SERVER_CAPABILITY_RETRY_INTERVAL_MS
})
this.supportedHosts.delete(hostKey)
this.retryAfterByHost.set(hostKey, nowMs + CODEX_APP_SERVER_CAPABILITY_RETRY_INTERVAL_MS)
}
rememberSupported(hostKey: CodexAppServerHostKey): void {
this.remember(hostKey, { kind: 'supported' })
this.retryAfterByHost.delete(hostKey)
this.supportedHosts.add(hostKey)
}
runWithFallbackSync<T>(
@@ -97,7 +56,7 @@ export class CodexAppServerCapabilityCache {
isUnsupportedError: (error: unknown) => boolean,
nowMs = Date.now()
): T {
if (!this.shouldTry(hostKey, nowMs)) {
if (!this.supportedHosts.has(hostKey) && !this.shouldTry(hostKey, nowMs)) {
return runFallback()
}
try {
@@ -117,7 +76,8 @@ export class CodexAppServerCapabilityCache {
}
clear(): void {
this.stateByHost.clear()
this.retryAfterByHost.clear()
this.supportedHosts.clear()
}
}
@@ -1,45 +0,0 @@
import type { ChildProcess, ChildProcessWithoutNullStreams, spawn } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import { describe, expect, it, vi } from 'vitest'
import { runCodexAppServerSession } from './codex-app-server-session'
describe('runCodexAppServerSession fragmented output', () => {
it('parses a response delivered as 100,000 one-byte fragments', async () => {
const child = new EventEmitter() as ChildProcessWithoutNullStreams
child.stdin = new PassThrough()
child.stdout = new PassThrough()
child.stderr = new PassThrough()
child.kill = vi.fn(() => true) as ChildProcess['kill']
child.stdin.on('data', (bytes: Buffer) => {
const request = JSON.parse(bytes.toString()) as { id?: number; method: string }
if (request.id === undefined) {
return
}
const response = Buffer.from(
`${request.method === 'fragment/get' ? ' '.repeat(99_950) : ''}${JSON.stringify({
id: request.id,
result: request.method === 'fragment/get' ? { value: 'complete' } : {}
})}\n`
)
for (let index = 0; index < response.byteLength; index += 1) {
child.stdout.emit('data', response.subarray(index, index + 1))
}
})
child.stdin.once('finish', () => {
queueMicrotask(() => {
child.emit('exit', 0, null)
child.emit('close', 0, null)
})
})
const spawnImpl = vi.fn(() => child) as unknown as typeof spawn
const result = await runCodexAppServerSession(
{ command: 'codex', args: ['app-server'], timeoutMs: 5_000 },
({ request }) => request('fragment/get'),
spawnImpl
)
expect(result).toEqual({ value: 'complete' })
})
})
@@ -16,10 +16,6 @@ import type {
CodexUserHookTrustRebaseRequest,
CodexUserHookTrustRebaseResult
} from './codex-user-hook-trust-rebase-client'
import {
findLastNonEmptyCodexAppServerGrantLine,
parseCodexAppServerGrantJson
} from './codex-app-server-grant-json'
// Why: hook install/refresh is synchronous launch prep — a Codex pane must
// not start before its trust is settled — but a stdio JSON-RPC session needs
@@ -118,11 +114,12 @@ function runCodexAppServerEntrySync(
`codex trust-grant entry killed by ${spawned.signal} after ${request.invocation.timeoutMs}ms deadline`
)
}
const lastLine = findLastNonEmptyCodexAppServerGrantLine(spawned.stdout ?? '')
const lines = (spawned.stdout ?? '').split('\n').filter((line) => line.trim().length > 0)
const lastLine = lines.at(-1)
let envelope: GrantEntryEnvelope | null = null
if (lastLine) {
try {
envelope = parseCodexAppServerGrantJson<GrantEntryEnvelope>(lastLine)
envelope = JSON.parse(lastLine) as GrantEntryEnvelope
} catch {
envelope = null
}
@@ -11,21 +11,22 @@ import {
import { writeSync } from 'node:fs'
import { runCodexHookTrustGrantSession } from './codex-app-server-client'
import { runCodexUserHookTrustRebaseSession } from './codex-user-hook-trust-rebase-client'
import { readNodeReadableTextWithinLimit } from '../../shared/node-readable-text'
import { parseCodexAppServerGrantJson } from './codex-app-server-grant-json'
const HARD_EXIT_MARGIN_MS = 2_000
const GRANT_ENTRY_MAX_INPUT_BYTES = 16 * 1024 * 1024
async function readStdin(): Promise<string> {
return await readNodeReadableTextWithinLimit(process.stdin, GRANT_ENTRY_MAX_INPUT_BYTES)
const chunks: Buffer[] = []
for await (const chunk of process.stdin) {
chunks.push(chunk as Buffer)
}
return Buffer.concat(chunks).toString('utf8')
}
async function main(): Promise<void> {
const raw = await readStdin()
let request: CodexAppServerEntryRequest
try {
request = parseCodexAppServerGrantJson<CodexAppServerEntryRequest>(raw)
request = JSON.parse(raw) as CodexAppServerEntryRequest
} catch (error) {
process.stdout.write(
`${JSON.stringify({
@@ -1,26 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
CODEX_APP_SERVER_GRANT_JSON_MAX_STRUCTURAL_TOKENS,
findLastNonEmptyCodexAppServerGrantLine,
parseCodexAppServerGrantJson
} from './codex-app-server-grant-json'
describe('Codex app-server grant JSON admission', () => {
it('preserves the last non-empty output line without splitting all output', () => {
expect(findLastNonEmptyCodexAppServerGrantLine('diagnostic\n\n{"ok":true}\n \t\r')).toBe(
'{"ok":true}'
)
expect(findLastNonEmptyCodexAppServerGrantLine('\n \t\r')).toBeNull()
})
it('rejects structurally amplified grant JSON before parsing', () => {
const text = `{"values":[${'0,'.repeat(CODEX_APP_SERVER_GRANT_JSON_MAX_STRUCTURAL_TOKENS)}0]}`
const parseSpy = vi.spyOn(JSON, 'parse')
try {
expect(() => parseCodexAppServerGrantJson(text)).toThrow(/JSON structure exceeds/)
expect(parseSpy).not.toHaveBeenCalled()
} finally {
parseSpy.mockRestore()
}
})
})
@@ -1,51 +0,0 @@
import { assertJsonTextStructureWithinLimits } from '../../shared/json-text-structure-limit'
export const CODEX_APP_SERVER_GRANT_JSON_MAX_STRUCTURAL_TOKENS = 1_000_000
export const CODEX_APP_SERVER_GRANT_JSON_MAX_NESTING_DEPTH = 128
export function parseCodexAppServerGrantJson<T>(text: string): T {
assertJsonTextStructureWithinLimits(text, {
structuralTokens: CODEX_APP_SERVER_GRANT_JSON_MAX_STRUCTURAL_TOKENS,
nestingDepth: CODEX_APP_SERVER_GRANT_JSON_MAX_NESTING_DEPTH
})
return JSON.parse(text) as T
}
export function findLastNonEmptyCodexAppServerGrantLine(output: string): string | null {
let end = output.length
while (end > 0) {
const newline = output.lastIndexOf('\n', end - 1)
const start = newline + 1
const line = output.slice(start, end)
if (hasNonWhitespace(line)) {
return line
}
end = newline === -1 ? 0 : newline
}
return null
}
function hasNonWhitespace(value: string): boolean {
for (let index = 0; index < value.length; index += 1) {
if (!isEcmaWhitespace(value.charCodeAt(index))) {
return true
}
}
return false
}
function isEcmaWhitespace(code: number): boolean {
return (
code === 0x20 ||
(code >= 0x09 && code <= 0x0d) ||
code === 0xa0 ||
code === 0x1680 ||
(code >= 0x2000 && code <= 0x200a) ||
code === 0x2028 ||
code === 0x2029 ||
code === 0x202f ||
code === 0x205f ||
code === 0x3000 ||
code === 0xfeff
)
}
+18 -32
View File
@@ -1,5 +1,4 @@
import { spawn, type ChildProcess, type ChildProcessWithoutNullStreams } from 'node:child_process'
import { GrowingByteBuffer } from '../../shared/growing-byte-buffer'
import { waitForProcessExitUntil } from './codex-process-exit-deadline'
import { stderrIndicatesMissingAppServer } from './codex-app-server-capability-signal'
@@ -118,7 +117,7 @@ export async function runCodexAppServerSession<T>(
windowsHide: true
}) as ChildProcessWithoutNullStreams
const stderrTail = new GrowingByteBuffer()
let stderrTail = ''
let exited = false
let nextRequestId = 1
let timedOut = false
@@ -146,15 +145,10 @@ export async function runCodexAppServerSession<T>(
child.on('close', () => {
failPending(buildEarlyExitError())
})
// Why: retain raw bytes so split UTF-8 code points decode only after a full line arrives.
child.stderr.on('data', (chunk: Buffer) => {
if (chunk.byteLength >= STDERR_TAIL_MAX_BYTES) {
stderrTail.clear()
stderrTail.append(chunk.subarray(chunk.byteLength - STDERR_TAIL_MAX_BYTES))
return
}
stderrTail.append(chunk)
stderrTail.retainSuffix(STDERR_TAIL_MAX_BYTES)
// Why: JSONL can contain non-ASCII hook paths. Stream decoding must retain a
// multibyte character split across pipe chunks or the response becomes invalid JSON.
child.stderr.setEncoding('utf8').on('data', (chunk: string) => {
stderrTail = (stderrTail + chunk).slice(-STDERR_TAIL_MAX_BYTES)
})
// Why: a child can exit between the liveness check and stdin.write(); an
// EPIPE must reject the RPC instead of becoming an unhandled stream error.
@@ -162,25 +156,21 @@ export async function runCodexAppServerSession<T>(
failPending(error)
})
const stdoutBuffer = new GrowingByteBuffer()
child.stdout.on('data', (chunk: Buffer) => {
stdoutBuffer.append(chunk)
if (stdoutBuffer.byteLength > STDOUT_LINE_MAX_BYTES) {
let stdoutBuffer = ''
child.stdout.setEncoding('utf8').on('data', (chunk: string) => {
stdoutBuffer += chunk
if (Buffer.byteLength(stdoutBuffer) > STDOUT_LINE_MAX_BYTES) {
// Why: Windows process-tree termination is asynchronous; stop buffered
// chunks from spawning another taskkill for the same oversized response.
child.stdout.destroy()
stdoutBuffer.clear()
killCodexAppServerProcessTree(child)
failPending(new Error('codex app-server emitted an oversized JSONL response'))
return
}
while (true) {
const newlineIndex = stdoutBuffer.indexOfByte(0x0a)
if (newlineIndex === -1) {
break
}
const line = stdoutBuffer.takePrefixString(newlineIndex).trim()
stdoutBuffer.discardPrefix(1)
let newlineIndex
while ((newlineIndex = stdoutBuffer.indexOf('\n')) !== -1) {
const line = stdoutBuffer.slice(0, newlineIndex).trim()
stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1)
if (!line) {
continue
}
@@ -273,14 +263,13 @@ export async function runCodexAppServerSession<T>(
}
function buildEarlyExitError(): Error {
const stderr = stderrTail.toString()
if (stderrIndicatesMissingAppServer(stderr)) {
if (stderrIndicatesMissingAppServer(stderrTail)) {
return new CodexAppServerUnsupportedError(
`codex CLI does not support the app-server subcommand: ${stderr.trim().slice(0, 400)}`
`codex CLI does not support the app-server subcommand: ${stderrTail.trim().slice(0, 400)}`
)
}
return new Error(
`codex app-server exited before completing the session${stderr ? `: ${stderr.trim().slice(0, 400)}` : ''}`
`codex app-server exited before completing the session${stderrTail ? `: ${stderrTail.trim().slice(0, 400)}` : ''}`
)
}
@@ -300,11 +289,10 @@ export async function runCodexAppServerSession<T>(
error instanceof Error &&
!(error instanceof CodexAppServerUnsupportedError) &&
!(error instanceof CodexAppServerTimeoutError) &&
stderrIndicatesMissingAppServer(stderrTail.toString())
stderrIndicatesMissingAppServer(stderrTail)
) {
const stderr = stderrTail.toString()
throw new CodexAppServerUnsupportedError(
`codex CLI does not support the app-server subcommand: ${stderr.trim().slice(0, 400)}`
`codex CLI does not support the app-server subcommand: ${stderrTail.trim().slice(0, 400)}`
)
}
throw error
@@ -324,7 +312,5 @@ export async function runCodexAppServerSession<T>(
}
}
clearTimeout(deadline)
stdoutBuffer.clear()
stderrTail.clear()
}
}
+16 -8
View File
@@ -3,6 +3,7 @@ import {
existsSync,
lstatSync,
mkdirSync,
readFileSync,
readlinkSync,
rmdirSync,
rmSync,
@@ -13,11 +14,8 @@ import {
} from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { nodeSourceAndCopyContentsEqualSync } from '../../shared/node-source-copy-content-equality'
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
const CODEX_GLOBAL_INSTRUCTIONS_ENTRY = 'AGENTS.md'
const CODEX_RESOURCE_COPY_MARKER_MAX_BYTES = 64 * 1024
const CODEX_SYSTEM_RESOURCE_ENTRIES = [
'skills',
@@ -126,7 +124,7 @@ function linkSystemCodexResource(
// rewriting an unchanged file across the UNC boundary on every launch.
if (
entryName === CODEX_GLOBAL_INSTRUCTIONS_ENTRY &&
nodeSourceAndCopyContentsEqualSync(sourcePath, targetPath)
copiedFileContentsMatch(sourcePath, targetPath)
) {
return
}
@@ -215,6 +213,19 @@ function pathEntryExists(entryPath: string): boolean {
}
}
function copiedFileContentsMatch(sourcePath: string, targetPath: string): boolean {
try {
// Why: reading a FIFO or device synchronously can block Codex launch.
// Follow source symlinks, but only compare two regular files.
if (!statSync(sourcePath).isFile() || !lstatSync(targetPath).isFile()) {
return false
}
return readFileSync(sourcePath).equals(readFileSync(targetPath))
} catch {
return false
}
}
function targetAlreadyPointsToSource(targetPath: string, sourcePath: string): boolean {
try {
return (
@@ -253,10 +264,7 @@ function markCopiedResource(managedHomePath: string, entryName: string, sourcePa
function readCopiedResourceSourcePath(managedHomePath: string, entryName: string): string | null {
try {
const parsed: unknown = JSON.parse(
readNodeFileSyncWithinLimit(
getResourceCopyMarkerPath(managedHomePath, entryName),
CODEX_RESOURCE_COPY_MARKER_MAX_BYTES
).buffer.toString('utf8')
readFileSync(getResourceCopyMarkerPath(managedHomePath, entryName), 'utf-8')
)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null
+1 -2
View File
@@ -15,7 +15,6 @@ import {
codexAppServerCapabilityCache,
getCodexAppServerHostKey
} from './codex-app-server-capability-cache'
import { CodexHostRetryDeadlines } from './codex-host-retry-deadlines'
import {
writeCodexTrustGrantLedgerHome,
type CodexTrustGrantBinaryStamp,
@@ -73,7 +72,7 @@ const diagnostics = {
lastFallbackReason: null as CodexTrustGrantFallbackReason | null
}
export type CodexTrustGrantDiagnostics = typeof diagnostics
const transientRetryAfterByHost = new CodexHostRetryDeadlines()
const transientRetryAfterByHost = new Map<string, number>()
export function getCodexTrustGrantDiagnostics(): CodexTrustGrantDiagnostics {
return { ...diagnostics }
@@ -1,39 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS,
type CodexAppServerHostKey
} from './codex-app-server-capability-cache'
import { CodexHostRetryDeadlines } from './codex-host-retry-deadlines'
function host(index: number): CodexAppServerHostKey {
return `wsl:distro-${index}`
}
describe('CodexHostRetryDeadlines', () => {
it('preserves every deadline through the exact host limit', () => {
const deadlines = new CodexHostRetryDeadlines()
for (let index = 0; index < MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS; index += 1) {
deadlines.set(host(index), index + 1)
}
expect(deadlines.sizeForTest()).toBe(MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS)
for (let index = 0; index < MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS; index += 1) {
expect(deadlines.get(host(index))).toBe(index + 1)
}
})
it('evicts the least recently used host above the limit', () => {
const deadlines = new CodexHostRetryDeadlines()
for (let index = 0; index < MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS; index += 1) {
deadlines.set(host(index), index + 1)
}
expect(deadlines.get(host(0))).toBe(1)
deadlines.set(host(MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS), 999)
expect(deadlines.sizeForTest()).toBe(MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS)
expect(deadlines.get(host(0))).toBe(1)
expect(deadlines.get(host(1))).toBeUndefined()
expect(deadlines.get(host(MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS))).toBe(999)
})
})
@@ -1,41 +0,0 @@
import {
MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS,
type CodexAppServerHostKey
} from './codex-app-server-capability-cache'
export class CodexHostRetryDeadlines {
private readonly deadlineByHost = new Map<CodexAppServerHostKey, number>()
get(hostKey: CodexAppServerHostKey): number | undefined {
const deadline = this.deadlineByHost.get(hostKey)
if (deadline !== undefined) {
this.deadlineByHost.delete(hostKey)
this.deadlineByHost.set(hostKey, deadline)
}
return deadline
}
set(hostKey: CodexAppServerHostKey, deadline: number): void {
this.deadlineByHost.delete(hostKey)
this.deadlineByHost.set(hostKey, deadline)
while (this.deadlineByHost.size > MAX_CODEX_APP_SERVER_CAPABILITY_HOSTS) {
const oldestHost = this.deadlineByHost.keys().next().value
if (oldestHost === undefined) {
return
}
this.deadlineByHost.delete(oldestHost)
}
}
delete(hostKey: CodexAppServerHostKey): void {
this.deadlineByHost.delete(hostKey)
}
clear(): void {
this.deadlineByHost.clear()
}
sizeForTest(): number {
return this.deadlineByHost.size
}
}
@@ -1,11 +1,10 @@
import { existsSync, mkdirSync, statSync, unlinkSync } from 'node:fs'
import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
import { writeFileAtomically } from '../codex-accounts/fs-utils'
import {
buildManagedCommandHook,
createManagedCommandMatcher,
MANAGED_HOOK_TIMEOUT_SECONDS,
readHooksJsonRawForGenerationCheck,
readHooksJsonWithRaw,
removeManagedCommands,
writeHooksJson,
@@ -75,9 +74,7 @@ function assertHooksJsonGeneration(
hooksWritePath: string,
expectedRaw: string | null
): void {
const currentRaw = existsSync(hooksJsonPath)
? readHooksJsonRawForGenerationCheck(hooksJsonPath)
: null
const currentRaw = existsSync(hooksJsonPath) ? readFileSync(hooksJsonPath, 'utf-8') : null
if (currentRaw !== expectedRaw || resolveHooksJsonWritePath(hooksJsonPath) !== hooksWritePath) {
// Why: the pre-mutation RPC can overlap a user's editor save. Abort rather
// than atomically replacing a newer file with the stale parsed snapshot.
@@ -1,6 +1,5 @@
import { mkdirSync, rmSync } from 'node:fs'
import { mkdirSync, readFileSync, rmSync } from 'node:fs'
import { dirname } from 'node:path'
import { readAgentStateJsonFileSync } from '../agent-state-file-reader'
import { writeFileAtomically } from '../codex-accounts/fs-utils'
import type { CodexSessionBackfillSummary } from './codex-session-backfill-types'
@@ -13,7 +12,7 @@ export function hasCompletedCodexSessionBackfillMarker(
systemSessionsRoot: string
): boolean {
try {
const parsed = readAgentStateJsonFileSync(markerPath)
const parsed: unknown = JSON.parse(readFileSync(markerPath, 'utf-8'))
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return false
}
+2 -2
View File
@@ -3,13 +3,13 @@ import {
linkSync,
lstatSync,
mkdirSync,
readFileSync,
readlinkSync,
renameSync,
rmSync,
symlinkSync
} from 'node:fs'
import { dirname, isAbsolute, join, relative, sep } from 'node:path'
import { readAgentStateFileSync } from '../agent-state-file-reader'
import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths'
import {
listCodexSessionJsonlFiles,
@@ -334,7 +334,7 @@ function getLegacySessionCopyMarkerPath(relativePath: string): string {
function readLegacyCopiedSessionMarker(relativePath: string): LegacyCopiedSessionMarker | null {
try {
const parsed: unknown = JSON.parse(
readAgentStateFileSync(getLegacySessionCopyMarkerPath(relativePath))
readFileSync(getLegacySessionCopyMarkerPath(relativePath), 'utf-8')
)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null
@@ -1,112 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
CodexSessionListingCapacityError,
listCodexSessionJsonlFilesIncrementally,
listCodexSessionJsonlFilesWithinLimits
} from './codex-session-file-listing'
const tempRoots: string[] = []
async function makeRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-codex-session-listing-'))
tempRoots.push(root)
return root
}
async function collect(files: AsyncIterable<string>): Promise<string[]> {
const collected: string[] = []
for await (const file of files) {
collected.push(file)
}
return collected
}
afterEach(async () => {
vi.restoreAllMocks()
await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('Codex session file-listing limits', () => {
it('preserves sorted JSONL discovery below every limit', async () => {
const root = await makeRoot()
await mkdir(join(root, '2026', '01', '02'), { recursive: true })
const later = join(root, '2026', '01', '02', 'z.jsonl')
const earlier = join(root, '2026', '01', '02', 'a.jsonl')
await writeFile(later, '{}')
await writeFile(earlier, '{}')
await writeFile(join(root, '2026', '01', '02', 'ignored.txt'), 'x')
expect(listCodexSessionJsonlFilesWithinLimits(root)).toEqual([earlier, later])
})
it('accepts exact entry and file limits, then rejects the next file', async () => {
const root = await makeRoot()
await writeFile(join(root, 'a.jsonl'), '{}')
await writeFile(join(root, 'b.jsonl'), '{}')
expect(
listCodexSessionJsonlFilesWithinLimits(root, { maxEntries: 2, maxFiles: 2 })
).toHaveLength(2)
await writeFile(join(root, 'c.jsonl'), '{}')
expect(() =>
listCodexSessionJsonlFilesWithinLimits(root, { maxEntries: 3, maxFiles: 2 })
).toThrow('Codex session listing exceeded 2 files')
})
it('bounds a zero-file directory tree by entries and depth', async () => {
const root = await makeRoot()
await mkdir(join(root, 'a', 'b'), { recursive: true })
expect(listCodexSessionJsonlFilesWithinLimits(root, { maxEntries: 2, maxDepth: 2 })).toEqual([])
expect(() =>
listCodexSessionJsonlFilesWithinLimits(root, { maxEntries: 1, maxDepth: 2 })
).toThrow('Codex session listing exceeded 1 entries')
expect(() =>
listCodexSessionJsonlFilesWithinLimits(root, { maxEntries: 2, maxDepth: 1 })
).toThrow('Codex session listing exceeded 1 depth')
})
it('accepts the exact aggregate path limit and rejects one code unit less', async () => {
const root = await makeRoot()
const filePath = join(root, 'a.jsonl')
await writeFile(filePath, '{}')
const exactPathCodeUnits = root.length + filePath.length
expect(
listCodexSessionJsonlFilesWithinLimits(root, {
maxPathCodeUnits: exactPathCodeUnits
})
).toEqual([filePath])
expect(() =>
listCodexSessionJsonlFilesWithinLimits(root, {
maxPathCodeUnits: exactPathCodeUnits - 1
})
).toThrow(`Codex session listing exceeded ${exactPathCodeUnits - 1} path code units`)
})
it('stops an incremental scan at capacity and reports it as a failed directory', async () => {
const root = await makeRoot()
await writeFile(join(root, 'a.jsonl'), '{}')
await writeFile(join(root, 'b.jsonl'), '{}')
const onDirectoryError = vi.fn()
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const files = await collect(
listCodexSessionJsonlFilesIncrementally(
root,
{ batchSize: 1, limits: { maxFiles: 1 }, yieldMs: 0 },
onDirectoryError
)
)
expect(files).toHaveLength(1)
expect(onDirectoryError).toHaveBeenCalledWith(
root,
expect.any(CodexSessionListingCapacityError)
)
expect(warnSpy).toHaveBeenCalledTimes(1)
})
})
+29 -83
View File
@@ -1,25 +1,10 @@
import { opendirSync } from 'node:fs'
import { readdirSync } from 'node:fs'
import { opendir } from 'node:fs/promises'
import { join } from 'node:path'
import {
CodexSessionListingBudget,
CodexSessionListingCapacityError,
type CodexSessionListingLimits
} from './codex-session-listing-budget'
export {
CODEX_SESSION_LISTING_MAX_DEPTH,
CODEX_SESSION_LISTING_MAX_ENTRIES,
CODEX_SESSION_LISTING_MAX_FILES,
CODEX_SESSION_LISTING_MAX_PATH_CODE_UNITS,
CodexSessionListingCapacityError
} from './codex-session-listing-budget'
export type CodexSessionBridgeIncrementalOptions = {
/** Directory entries to process before yielding back to the event loop. */
batchSize?: number
/** Optional lower limits for tests or constrained callers. */
limits?: Partial<CodexSessionListingLimits>
/** Delay after each processed batch; zero still yields on a timer turn. */
yieldMs?: number
}
@@ -34,59 +19,32 @@ const INCREMENTAL_BRIDGE_YIELD_MS = 10
* that run outside the CLI launch path.
*/
export function listCodexSessionJsonlFiles(rootPath: string): string[] {
return listCodexSessionJsonlFilesWithinLimits(rootPath)
}
export function listCodexSessionJsonlFilesWithinLimits(
rootPath: string,
limits: Partial<CodexSessionListingLimits> = {}
): string[] {
const budget = new CodexSessionListingBudget(limits)
budget.claimDepth(0)
budget.claimPath(rootPath)
const files: string[] = []
const pendingDirectories = [{ depth: 0, path: rootPath }]
while (pendingDirectories.length > 0) {
const current = pendingDirectories.pop()!
let directory: ReturnType<typeof opendirSync>
try {
directory = opendirSync(current.path)
} catch (error) {
warnAboutCodexSessionListingError(error)
continue
}
try {
for (let entry = directory.readSync(); entry !== null; entry = directory.readSync()) {
budget.claimEntry()
const childPath = join(current.path, entry.name)
budget.claimPath(childPath)
if (entry.isDirectory()) {
const depth = current.depth + 1
budget.claimDepth(depth)
pendingDirectories.push({ depth, path: childPath })
} else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
budget.claimFile()
files.push(childPath)
}
try {
for (const entry of readdirSync(rootPath, { withFileTypes: true })) {
const childPath = join(rootPath, entry.name)
if (entry.isDirectory()) {
appendSessionFilePaths(files, listCodexSessionJsonlFiles(childPath))
continue
}
} catch (error) {
if (error instanceof CodexSessionListingCapacityError) {
throw error
if (entry.isFile() && entry.name.endsWith('.jsonl')) {
files.push(childPath)
}
warnAboutCodexSessionListingError(error)
} finally {
closeCodexSessionDirectory(directory)
}
} catch (error) {
console.warn('[codex-session-bridge] Failed to list system Codex sessions:', error)
}
return files.sort()
}
function closeCodexSessionDirectory(directory: ReturnType<typeof opendirSync>): void {
try {
directory.closeSync()
} catch {
// The OS may have already closed a failed directory stream.
/**
* Appends session paths without spreading large arrays into a single call.
*/
function appendSessionFilePaths(target: string[], source: readonly string[]): void {
// Why: existing Codex homes can accumulate enough nested sessions to exceed
// V8's argument limit if child arrays are spread into push().
for (const filePath of source) {
target.push(filePath)
}
}
@@ -131,26 +89,21 @@ async function* listCodexSessionFilesIncrementally(
): AsyncGenerator<string> {
const batchSize = Math.max(1, options.batchSize ?? INCREMENTAL_BRIDGE_BATCH_SIZE)
const yieldMs = Math.max(0, options.yieldMs ?? INCREMENTAL_BRIDGE_YIELD_MS)
const budget = new CodexSessionListingBudget(options.limits)
budget.claimDepth(0)
budget.claimPath(rootPath)
const pendingDirectories = [{ depth: 0, path: rootPath }]
const pendingDirectories = [rootPath]
let entriesSinceYield = 0
while (pendingDirectories.length > 0) {
const currentDirectory = pendingDirectories.pop()!
const currentDirectory = pendingDirectories.pop()
if (!currentDirectory) {
continue
}
try {
const directory = await opendir(currentDirectory.path)
const directory = await opendir(currentDirectory)
for await (const entry of directory) {
budget.claimEntry()
const childPath = join(currentDirectory.path, entry.name)
budget.claimPath(childPath)
const childPath = join(currentDirectory, entry.name)
if (entry.isDirectory()) {
const depth = currentDirectory.depth + 1
budget.claimDepth(depth)
pendingDirectories.push({ depth, path: childPath })
pendingDirectories.push(childPath)
} else if (entry.isFile() && isSessionFile(entry.name)) {
budget.claimFile()
yield childPath
}
entriesSinceYield += 1
@@ -160,19 +113,12 @@ async function* listCodexSessionFilesIncrementally(
}
}
} catch (error) {
await onDirectoryError?.(currentDirectory.path, error)
warnAboutCodexSessionListingError(error)
if (error instanceof CodexSessionListingCapacityError) {
return
}
await onDirectoryError?.(currentDirectory, error)
console.warn('[codex-session-bridge] Failed to list system Codex sessions:', error)
}
}
}
function warnAboutCodexSessionListingError(error: unknown): void {
console.warn('[codex-session-bridge] Failed to list system Codex sessions:', error)
}
/**
* Defers incremental bridge work to a later timer turn.
*/
@@ -1,45 +0,0 @@
import { appendFileSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES,
readCodexSessionIndexHealJsonlRecords
} from './codex-session-index-heal-jsonl'
describe('Codex session index heal JSONL reader', () => {
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
function makePath(): string {
const root = mkdtempSync(join(tmpdir(), 'orca-heal-jsonl-'))
roots.push(root)
return join(root, 'ledger.jsonl')
}
it('accepts a valid record exactly at the per-line byte limit', () => {
const path = makePath()
const prefix = '{"padding":"'
const suffix = '"}'
const padding = 'x'.repeat(
MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES - prefix.length - suffix.length
)
writeFileSync(path, `${prefix}${padding}${suffix}\n`)
expect([...readCodexSessionIndexHealJsonlRecords(path)]).toEqual([{ padding }])
})
it('skips an oversized sparse line and resumes at the next record', () => {
const path = makePath()
writeFileSync(path, '{"ignored":"')
truncateSync(path, MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES + 8 * 1024 * 1024)
appendFileSync(path, '\n{"kept":true}\n')
expect([...readCodexSessionIndexHealJsonlRecords(path)]).toEqual([{ kept: true }])
})
})
@@ -1,102 +0,0 @@
import { closeSync, openSync, readSync } from 'node:fs'
export const MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES = 1024 * 1024
const HEAL_JSONL_READ_CHUNK_BYTES = 64 * 1024
function isNotFoundError(error: unknown): boolean {
return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
}
function parseJsonlRecord(raw: string): Record<string, unknown> | null {
if (!raw.trim()) {
return null
}
try {
const parsed: unknown = JSON.parse(raw)
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: null
} catch {
return null
}
}
export function* readCodexSessionIndexHealJsonlRecords(
filePath: string
): Generator<Record<string, unknown>> {
let descriptor: number
try {
descriptor = openSync(filePath, 'r')
} catch (error) {
if (isNotFoundError(error)) {
return
}
throw error
}
const readBuffer = Buffer.allocUnsafe(HEAL_JSONL_READ_CHUNK_BYTES)
let lineParts: Buffer[] = []
let lineBytes = 0
let skippingOversizedLine = false
const resetLine = (): void => {
lineParts = []
lineBytes = 0
skippingOversizedLine = false
}
const appendSegment = (start: number, end: number): void => {
if (skippingOversizedLine || start === end) {
return
}
const nextBytes = lineBytes + end - start
if (nextBytes > MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES) {
// Why: a corrupt line may span an arbitrarily large sparse file; discard until its newline.
lineParts = []
lineBytes = 0
skippingOversizedLine = true
return
}
lineParts.push(Buffer.from(readBuffer.subarray(start, end)))
lineBytes = nextBytes
}
const takeRecord = (): Record<string, unknown> | null => {
const raw =
lineParts.length === 1
? lineParts[0].toString('utf8')
: Buffer.concat(lineParts, lineBytes).toString('utf8')
return parseJsonlRecord(raw)
}
try {
while (true) {
const bytesRead = readSync(descriptor, readBuffer, 0, readBuffer.length, null)
if (bytesRead === 0) {
break
}
let start = 0
for (let index = 0; index < bytesRead; index += 1) {
if (readBuffer[index] !== 0x0a) {
continue
}
appendSegment(start, index)
if (!skippingOversizedLine) {
const record = takeRecord()
if (record) {
yield record
}
}
resetLine()
start = index + 1
}
appendSegment(start, bytesRead)
}
if (!skippingOversizedLine && lineBytes > 0) {
const record = takeRecord()
if (record) {
yield record
}
}
} finally {
closeSync(descriptor)
}
}
@@ -1,81 +0,0 @@
import {
closeSync,
mkdtempSync,
openSync,
rmSync,
truncateSync,
writeFileSync,
writeSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
CODEX_SESSION_INDEX_HEAL_VERSION,
CodexSessionIndexHealCapacityError,
collectPendingHealThreads,
isHealMarkerCurrent,
MAX_CODEX_SESSION_INDEX_HEAL_MARKER_FILE_BYTES,
MAX_CODEX_SESSION_INDEX_HEAL_TRACKED_THREADS,
type CodexSessionIndexHealPaths
} from './codex-session-index-heal-state'
describe('Codex session index heal state memory bounds', () => {
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
function makePaths(): CodexSessionIndexHealPaths {
const root = mkdtempSync(join(tmpdir(), 'orca-heal-state-memory-'))
roots.push(root)
return {
auditLogPath: join(root, 'audit.jsonl'),
systemSessionsRoot: '/sessions',
healLedgerPath: join(root, 'heal.jsonl'),
healMarkerPath: join(root, 'marker.json')
}
}
it('fails closed when processed state exceeds the retained-thread ceiling', () => {
const paths = makePaths()
const descriptor = openSync(paths.healLedgerPath, 'w')
try {
for (let start = 0; start <= MAX_CODEX_SESSION_INDEX_HEAL_TRACKED_THREADS; start += 1000) {
const count = Math.min(1000, MAX_CODEX_SESSION_INDEX_HEAL_TRACKED_THREADS + 1 - start)
const lines = Array.from({ length: count }, (_, offset) => {
const suffix = (start + offset).toString(16).padStart(12, '0')
return JSON.stringify({
v: CODEX_SESSION_INDEX_HEAL_VERSION,
systemSessionsRoot: paths.systemSessionsRoot,
threadId: `00000000-0000-0000-0000-${suffix}`,
outcome: 'healed'
})
})
writeSync(descriptor, `${lines.join('\n')}\n`)
}
} finally {
closeSync(descriptor)
}
expect(() => collectPendingHealThreads(paths)).toThrow(CodexSessionIndexHealCapacityError)
})
it('rejects an oversized sparse completion marker', () => {
const paths = makePaths()
writeFileSync(
paths.healMarkerPath,
JSON.stringify({
version: CODEX_SESSION_INDEX_HEAL_VERSION,
systemSessionsRoot: paths.systemSessionsRoot,
auditBytes: 0
})
)
truncateSync(paths.healMarkerPath, MAX_CODEX_SESSION_INDEX_HEAL_MARKER_FILE_BYTES + 1)
expect(isHealMarkerCurrent(paths, 0)).toBe(false)
})
})
@@ -1,17 +1,10 @@
import { appendFileSync, mkdirSync, statSync } from 'node:fs'
import { appendFileSync, mkdirSync, readFileSync, statSync } from 'node:fs'
import { dirname } from 'node:path'
import {
isPathInsideOrEqual,
normalizeRuntimePathForComparison
} from '../../shared/cross-platform-path'
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
import { writeFileAtomically } from '../codex-accounts/fs-utils'
import {
MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES,
readCodexSessionIndexHealJsonlRecords
} from './codex-session-index-heal-jsonl'
export { MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES }
// State files for the session index heal: which backfilled rollouts exist
// (the backfill audit ledger), which thread ids this pass already processed
@@ -21,22 +14,6 @@ export { MAX_CODEX_SESSION_INDEX_HEAL_JSONL_LINE_BYTES }
// Bump to re-drive the heal for every host after a semantics change; already
// processed thread ids are re-read because ledger lines are version-scoped.
export const CODEX_SESSION_INDEX_HEAL_VERSION = 3
export const MAX_CODEX_SESSION_INDEX_HEAL_TRACKED_THREADS = 100_000
export const MAX_CODEX_SESSION_INDEX_HEAL_MARKER_FILE_BYTES = 64 * 1024
const MAX_AUDIT_TARGET_LENGTH = 64 * 1024
const MAX_AUDIT_RECORD_ID_LENGTH = 128
const MAX_ROLLOUT_STAMP_LENGTH = 512
const CODEX_THREAD_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export class CodexSessionIndexHealCapacityError extends Error {
constructor(kind: 'pending' | 'processed') {
super(
`Codex session index heal ${kind} state exceeds ${MAX_CODEX_SESSION_INDEX_HEAL_TRACKED_THREADS} entries`
)
this.name = 'CodexSessionIndexHealCapacityError'
}
}
// Why: an unsupported CLI stays unsupported until upgraded; re-probing once a
// day is enough to notice an upgrade without a per-startup spawn.
@@ -76,11 +53,11 @@ export type HealMarkerSummary = {
export function collectPendingHealThreads(paths: CodexSessionIndexHealPaths): PendingHealThread[] {
const processed = readProcessedHealThreads(paths)
const pendingByThreadId = new Map<string, PendingHealThread>()
for (const line of readCodexSessionIndexHealJsonlRecords(paths.auditLogPath)) {
for (const line of readJsonlLines(paths.auditLogPath, true)) {
if (line.action !== 'hardlink' && line.action !== 'copy' && line.action !== 'existing') {
continue
}
if (typeof line.target !== 'string' || line.target.length > MAX_AUDIT_TARGET_LENGTH) {
if (typeof line.target !== 'string') {
continue
}
// Why: the append-only audit can contain runs for several custom Codex
@@ -89,13 +66,10 @@ export function collectPendingHealThreads(paths: CodexSessionIndexHealPaths): Pe
continue
}
const match = CODEX_ROLLOUT_THREAD_ID_PATTERN.exec(lastPathSegment(line.target))
if (!match || match[1].length > MAX_ROLLOUT_STAMP_LENGTH) {
if (!match) {
continue
}
const threadId = match[2].toLowerCase()
if (typeof line.recordId === 'string' && line.recordId.length > MAX_AUDIT_RECORD_ID_LENGTH) {
continue
}
const auditRecordId = typeof line.recordId === 'string' ? line.recordId : null
if (
processed.healedThreadIds.has(threadId) ||
@@ -108,12 +82,6 @@ export function collectPendingHealThreads(paths: CodexSessionIndexHealPaths): Pe
pendingByThreadId.delete(threadId)
continue
}
if (
!pendingByThreadId.has(threadId) &&
pendingByThreadId.size >= MAX_CODEX_SESSION_INDEX_HEAL_TRACKED_THREADS
) {
throw new CodexSessionIndexHealCapacityError('pending')
}
pendingByThreadId.set(threadId, { threadId, rolloutStamp: match[1], auditRecordId })
}
return [...pendingByThreadId.values()].sort((left, right) =>
@@ -134,49 +102,23 @@ function readProcessedHealThreads(paths: CodexSessionIndexHealPaths): {
const missingAuditRecords = new Set<string>()
const legacyMissingThreadIds = new Set<string>()
const expectedRoot = normalizeRuntimePathForComparison(paths.systemSessionsRoot)
let trackedEntries = 0
const addTrackedEntry = (entries: Set<string>, key: string): void => {
if (entries.has(key)) {
return
}
if (trackedEntries >= MAX_CODEX_SESSION_INDEX_HEAL_TRACKED_THREADS) {
throw new CodexSessionIndexHealCapacityError('processed')
}
entries.add(key)
trackedEntries += 1
}
try {
for (const line of readCodexSessionIndexHealJsonlRecords(paths.healLedgerPath)) {
if (
line.v === CODEX_SESSION_INDEX_HEAL_VERSION &&
typeof line.threadId === 'string' &&
CODEX_THREAD_ID_PATTERN.test(line.threadId) &&
typeof line.systemSessionsRoot === 'string' &&
(line.outcome === 'healed' || line.outcome === 'missing') &&
normalizeRuntimePathForComparison(line.systemSessionsRoot) === expectedRoot
) {
const threadId = line.threadId.toLowerCase()
if (line.outcome === 'healed') {
addTrackedEntry(healedThreadIds, threadId)
} else if (
typeof line.auditRecordId === 'string' &&
line.auditRecordId.length <= MAX_AUDIT_RECORD_ID_LENGTH
) {
addTrackedEntry(missingAuditRecords, `${threadId}\0${line.auditRecordId}`)
} else if (line.auditRecordId === undefined) {
addTrackedEntry(legacyMissingThreadIds, threadId)
}
for (const line of readJsonlLines(paths.healLedgerPath)) {
if (
line.v === CODEX_SESSION_INDEX_HEAL_VERSION &&
typeof line.threadId === 'string' &&
typeof line.systemSessionsRoot === 'string' &&
(line.outcome === 'healed' || line.outcome === 'missing') &&
normalizeRuntimePathForComparison(line.systemSessionsRoot) === expectedRoot
) {
const threadId = line.threadId.toLowerCase()
if (line.outcome === 'healed') {
healedThreadIds.add(threadId)
} else if (typeof line.auditRecordId === 'string') {
missingAuditRecords.add(`${threadId}\0${line.auditRecordId}`)
} else {
legacyMissingThreadIds.add(threadId)
}
}
} catch (error) {
if (error instanceof CodexSessionIndexHealCapacityError) {
throw error
}
return {
healedThreadIds: new Set(),
missingAuditRecords: new Set(),
legacyMissingThreadIds: new Set()
}
}
return { healedThreadIds, missingAuditRecords, legacyMissingThreadIds }
}
@@ -211,6 +153,35 @@ export function appendHealLedgerRecord(
}
}
function readJsonlLines(filePath: string, throwOnReadFailure = false): Record<string, unknown>[] {
let contents: string
try {
contents = readFileSync(filePath, 'utf-8')
} catch (error) {
if (throwOnReadFailure && !isNotFoundError(error)) {
// Why: the audit is the heal work queue. Treating EACCES/EIO as empty
// would write a completion marker that permanently skips every session.
throw error
}
return []
}
const lines: Record<string, unknown>[] = []
for (const raw of contents.split('\n')) {
if (!raw.trim()) {
continue
}
try {
const parsed: unknown = JSON.parse(raw)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
lines.push(parsed as Record<string, unknown>)
}
} catch {
// Skip torn/corrupt lines; both ledgers are append-only diagnostics.
}
}
return lines
}
export function readAuditLogSize(auditLogPath: string): number {
try {
return statSync(auditLogPath).size
@@ -231,12 +202,7 @@ export function isHealMarkerCurrent(
auditBytes: number
): boolean {
try {
const parsed: unknown = JSON.parse(
readNodeFileSyncWithinLimit(
paths.healMarkerPath,
MAX_CODEX_SESSION_INDEX_HEAL_MARKER_FILE_BYTES
).buffer.toString('utf8')
)
const parsed: unknown = JSON.parse(readFileSync(paths.healMarkerPath, 'utf-8'))
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return false
}
@@ -1,81 +0,0 @@
export const CODEX_SESSION_LISTING_MAX_DEPTH = 32
export const CODEX_SESSION_LISTING_MAX_ENTRIES = 200_000
export const CODEX_SESSION_LISTING_MAX_FILES = 100_000
export const CODEX_SESSION_LISTING_MAX_PATH_CODE_UNITS = 32 * 1024 * 1024
export type CodexSessionListingLimits = {
maxDepth: number
maxEntries: number
maxFiles: number
maxPathCodeUnits: number
}
const DEFAULT_LIMITS: CodexSessionListingLimits = {
maxDepth: CODEX_SESSION_LISTING_MAX_DEPTH,
maxEntries: CODEX_SESSION_LISTING_MAX_ENTRIES,
maxFiles: CODEX_SESSION_LISTING_MAX_FILES,
maxPathCodeUnits: CODEX_SESSION_LISTING_MAX_PATH_CODE_UNITS
}
export type CodexSessionListingCapacityResource = 'depth' | 'entries' | 'files' | 'path code units'
export class CodexSessionListingCapacityError extends Error {
constructor(
readonly resource: CodexSessionListingCapacityResource,
readonly observed: number,
readonly limit: number
) {
super(`Codex session listing exceeded ${limit} ${resource}`)
this.name = 'CodexSessionListingCapacityError'
}
}
export class CodexSessionListingBudget {
readonly limits: CodexSessionListingLimits
private entries = 0
private files = 0
private pathCodeUnits = 0
constructor(limits: Partial<CodexSessionListingLimits> = {}) {
this.limits = { ...DEFAULT_LIMITS, ...limits }
for (const [name, value] of Object.entries(this.limits)) {
if (!Number.isSafeInteger(value) || value < 0) {
throw new RangeError(`${name} must be a non-negative safe integer`)
}
}
}
claimDepth(depth: number): void {
if (depth > this.limits.maxDepth) {
throw new CodexSessionListingCapacityError('depth', depth, this.limits.maxDepth)
}
}
claimEntry(): void {
this.entries += 1
if (this.entries > this.limits.maxEntries) {
throw new CodexSessionListingCapacityError('entries', this.entries, this.limits.maxEntries)
}
}
claimFile(): void {
this.files += 1
if (this.files > this.limits.maxFiles) {
throw new CodexSessionListingCapacityError('files', this.files, this.limits.maxFiles)
}
}
claimPath(path: string): void {
this.pathCodeUnits += path.length
if (
!Number.isSafeInteger(this.pathCodeUnits) ||
this.pathCodeUnits > this.limits.maxPathCodeUnits
) {
throw new CodexSessionListingCapacityError(
'path code units',
this.pathCodeUnits,
this.limits.maxPathCodeUnits
)
}
}
}
@@ -8,13 +8,10 @@ import {
rmSync,
statSync,
symlinkSync,
truncateSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { NodeFileReadTooLargeError } from '../../shared/node-bounded-file-reader'
import { MAX_AGENT_STATE_FILE_BYTES } from '../agent-state-file-reader'
import { captureCodexTrustConfig, restoreCodexTrustConfig } from './codex-trust-config-rollback'
const roots: string[] = []
@@ -32,15 +29,6 @@ function tempConfigPath(): string {
}
describe('Codex trust config rollback', () => {
it('rejects a sparse config above 4 MiB without changing it', () => {
const configPath = tempConfigPath()
writeFileSync(configPath, '')
truncateSync(configPath, MAX_AGENT_STATE_FILE_BYTES + 1)
expect(() => captureCodexTrustConfig(configPath)).toThrow(NodeFileReadTooLargeError)
expect(statSync(configPath).size).toBe(MAX_AGENT_STATE_FILE_BYTES + 1)
})
it('treats a missing config as absent and tolerates it remaining absent', () => {
const configPath = tempConfigPath()
const snapshot = captureCodexTrustConfig(configPath)
+19 -16
View File
@@ -1,6 +1,10 @@
import {
chmodSync,
closeSync,
fstatSync,
lstatSync,
openSync,
readFileSync,
readlinkSync,
realpathSync,
unlinkSync,
@@ -8,8 +12,6 @@ import {
} from 'node:fs'
import { randomUUID } from 'node:crypto'
import { dirname, resolve } from 'node:path'
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
import { MAX_AGENT_STATE_FILE_BYTES } from '../agent-state-file-reader'
import { renameFileWithWindowsRetry } from '../codex-accounts/fs-utils'
export type CodexTrustConfigSnapshot =
@@ -41,22 +43,27 @@ function resolveConfigRestorePath(tomlPath: string): string {
export function captureCodexTrustConfig(tomlPath: string): CodexTrustConfigSnapshot {
const restorePath = resolveConfigRestorePath(tomlPath)
let descriptor: number
try {
// Why: contents and mode come from one descriptor, so a path replacement
// cannot pair one file's bytes with another file's permissions.
const { buffer, stats } = readNodeFileSyncWithinLimit(restorePath, MAX_AGENT_STATE_FILE_BYTES)
return {
existed: true,
contents: buffer,
mode: stats.mode,
restorePath
}
descriptor = openSync(restorePath, 'r')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return restorePath === tomlPath ? { existed: false } : { existed: false, restorePath }
}
throw error
}
try {
// Why: read and stat the same open file so replacement between two path
// lookups cannot pair one file's contents with another file's mode.
return {
existed: true,
contents: readFileSync(descriptor),
mode: fstatSync(descriptor).mode,
restorePath
}
} finally {
closeSync(descriptor)
}
}
export function restoreCodexTrustConfig(
@@ -75,11 +82,7 @@ export function restoreCodexTrustConfig(
}
const { restorePath } = snapshot
try {
if (
readNodeFileSyncWithinLimit(restorePath, MAX_AGENT_STATE_FILE_BYTES).buffer.equals(
snapshot.contents
)
) {
if (readFileSync(restorePath).equals(snapshot.contents)) {
// Why: the RPC may change permissions without changing bytes; rollback
// restores the complete captured file state, not only its contents.
chmodSync(restorePath, snapshot.mode)
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
@@ -9,7 +9,6 @@ import {
removeCodexTrustGrantLedgerHome,
writeCodexTrustGrantLedgerHome
} from './codex-trust-grant-ledger'
import { MAX_AGENT_STATE_FILE_BYTES } from '../agent-state-file-reader'
let userDataDir: string
let previousUserDataPath: string | undefined
@@ -82,26 +81,6 @@ describe('codex trust grant ledger', () => {
expect(readCodexTrustGrantLedgerHome(home)).not.toBeNull()
})
it('preserves the prior ledger when a grant exceeds its read ceiling', () => {
const home = join(userDataDir, 'codex-runtime-home', 'home')
const ledgerPath = getCodexTrustGrantLedgerPath()
writeCodexTrustGrantLedgerHome(home, { binary: null, entries: {} })
const before = readFileSync(ledgerPath, 'utf8')
expect(() =>
writeCodexTrustGrantLedgerHome(home, {
binary: null,
entries: {
oversized: {
signature: 'x'.repeat(MAX_AGENT_STATE_FILE_BYTES),
trustedHash: 'sha256:test'
}
}
})
).toThrow('JSON output exceeds')
expect(readFileSync(ledgerPath, 'utf8')).toBe(before)
})
it('matches binary stamps only on identical identity', () => {
const stamp = { kind: 'native' as const, path: '/bin/codex', size: 1, mtimeMs: 2 }
const wslStamp = {
+3 -6
View File
@@ -1,7 +1,5 @@
import { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs'
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { MAX_AGENT_STATE_FILE_BYTES, readAgentStateJsonFileSync } from '../agent-state-file-reader'
import { stringifyJsonWithinByteLimit } from '../../shared/node-bounded-json-stringify'
import { getOrcaManagedCodexHomePath } from './codex-home-paths'
import { normalizeCodexProjectPathForLookup } from './config-toml-trust'
@@ -48,7 +46,7 @@ function readLedgerFile(ledgerPath: string): CodexTrustGrantLedgerFile {
return empty
}
try {
const parsed = readAgentStateJsonFileSync(ledgerPath)
const parsed: unknown = JSON.parse(readFileSync(ledgerPath, 'utf-8'))
if (
!parsed ||
typeof parsed !== 'object' ||
@@ -71,8 +69,7 @@ function readLedgerFile(ledgerPath: string): CodexTrustGrantLedgerFile {
function persistLedgerFile(ledgerPath: string, file: CodexTrustGrantLedgerFile): void {
mkdirSync(dirname(ledgerPath), { recursive: true, mode: 0o700 })
const { serialized } = stringifyJsonWithinByteLimit(file, MAX_AGENT_STATE_FILE_BYTES - 1, 2)
writeFileSync(ledgerPath, `${serialized}\n`, {
writeFileSync(ledgerPath, `${JSON.stringify(file, null, 2)}\n`, {
encoding: 'utf-8',
mode: 0o600
})
@@ -7,7 +7,6 @@ import {
import { runCodexUserHookTrustRebaseSessionSync } from './codex-app-server-grant-bridge'
import { isCodexAppServerUnsupportedError } from './codex-app-server-session'
import { CODEX_TRUST_GRANT_TRANSIENT_RETRY_INTERVAL_MS } from './codex-hook-trust-grant'
import { CodexHostRetryDeadlines } from './codex-host-retry-deadlines'
import { createCodexHookTrustEntry } from './codex-hook-identity'
import { resolveCodexTrustGrantHost } from './codex-trust-grant-host'
import {
@@ -33,7 +32,7 @@ let runSessionSync: RebaseSessionRunnerSync = runCodexUserHookTrustRebaseSession
// Why: launch prep re-runs the callers on every pane spawn. A host stuck
// without a usable rebase lane (old CLI, unmatched keys) must not pay a codex
// session each time — bound retries like the grant lane does.
const rebaseRetryAfterByHost = new CodexHostRetryDeadlines()
const rebaseRetryAfterByHost = new Map<CodexAppServerHostKey, number>()
function rememberRebaseSessionFailure(hostKey: CodexAppServerHostKey, error: unknown): void {
if (isCodexAppServerUnsupportedError(error)) {
@@ -6,12 +6,7 @@ vi.mock('node:child_process', () => ({
execFile: execFileMock
}))
import {
_internals,
createCodexWslRuntimeHookInstallPlan,
WSL_CANONICAL_PATH_CACHE_MAX_ENTRIES,
WSL_CANONICAL_PATH_CACHE_MAX_UTF8_BYTES
} from './codex-wsl-hook-install-plan'
import { _internals, createCodexWslRuntimeHookInstallPlan } from './codex-wsl-hook-install-plan'
const originalPlatform = process.platform
@@ -130,17 +125,6 @@ describe('canonicalizeWslLinuxPath', () => {
expect(execFileMock).toHaveBeenCalledTimes(2)
})
it('clears in-flight ownership when spawning wsl.exe throws synchronously', () => {
setPlatform('win32')
execFileMock.mockImplementationOnce(() => {
throw new Error('invalid WSL argv')
})
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull()
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull()
expect(execFileMock).toHaveBeenCalledTimes(2)
})
it('keeps the last known-good cache when revalidation later fails', () => {
setPlatform('win32')
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')
@@ -224,48 +208,4 @@ describe('canonicalizeWslLinuxPath', () => {
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull()
})
it('LRU-evicts canonical identities beyond the entry cap', () => {
setPlatform('win32')
for (let index = 0; index <= WSL_CANONICAL_PATH_CACHE_MAX_ENTRIES; index += 1) {
const logicalPath = `/home/runtime-${index}`
_internals.canonicalizeWslLinuxPath('Ubuntu', logicalPath)
const callback = execFileMock.mock.calls[index][3] as (
error: Error | null,
stdout: string
) => void
callback(null, `/canonical/runtime-${index}\n`)
}
expect(_internals.getWslCanonicalPathCacheSize()).toBe(WSL_CANONICAL_PATH_CACHE_MAX_ENTRIES)
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/runtime-0')).toBeNull()
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/runtime-1')).toBe(
'/canonical/runtime-1'
)
})
it('does not retain a canonical identity larger than the aggregate byte budget', () => {
setPlatform('win32')
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/oversized')
const callback = execFileMock.mock.calls[0][3] as (error: Error | null, stdout: string) => void
callback(null, `/${'x'.repeat(WSL_CANONICAL_PATH_CACHE_MAX_UTF8_BYTES)}\n`)
expect(_internals.getWslCanonicalPathCacheSize()).toBe(0)
expect(_internals.getWslCanonicalPathCacheBytes()).toBe(0)
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/oversized')).toBeNull()
})
it('retains a canonical identity at the exact aggregate byte budget', () => {
setPlatform('win32')
const logicalPath = '/home/exact-limit'
const keyBytes = Buffer.byteLength(`Ubuntu\0${logicalPath}`, 'utf8')
const canonicalPath = `/${'x'.repeat(WSL_CANONICAL_PATH_CACHE_MAX_UTF8_BYTES - keyBytes - 1)}`
_internals.canonicalizeWslLinuxPath('Ubuntu', logicalPath)
const callback = execFileMock.mock.calls[0][3] as (error: Error | null, stdout: string) => void
callback(null, canonicalPath)
expect(_internals.getWslCanonicalPathCacheSize()).toBe(1)
expect(_internals.getWslCanonicalPathCacheBytes()).toBe(WSL_CANONICAL_PATH_CACHE_MAX_UTF8_BYTES)
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', logicalPath)).toBe(canonicalPath)
})
})
+35 -94
View File
@@ -48,81 +48,17 @@ function toDefaultWslLinuxPath(windowsPath: string): string {
const WSL_CANONICALIZE_TIMEOUT_MS = 5000
const WSL_PATH_MISSING_OUTPUT = '__ORCA_WSL_PATH_MISSING__'
export const WSL_CANONICAL_PATH_CACHE_MAX_ENTRIES = 256
export const WSL_CANONICAL_PATH_CACHE_MAX_UTF8_BYTES = 2 * 1024 * 1024
// Why: `readlink -f` over wsl.exe stalls up to the timeout on a cold or wedged
// distro. Running it synchronously on the Electron main process froze the UI on
// every Codex WSL launch, so resolve it off-thread and cache the latest result.
const canonicalWslPathCache = new Map<string, { canonicalPath: string; retainedBytes: number }>()
let canonicalWslPathCacheBytes = 0
const canonicalWslPathCache = new Map<string, string>()
const inFlightWslCanonicalizations = new Map<string, Set<WslCanonicalPathSettled>>()
function wslCanonicalizeCacheKey(distro: string, linuxPath: string): string {
return `${distro}\x00${linuxPath}`
}
function getCachedWslCanonicalPath(key: string): string | null {
const cached = canonicalWslPathCache.get(key)
if (!cached) {
return null
}
canonicalWslPathCache.delete(key)
canonicalWslPathCache.set(key, cached)
return cached.canonicalPath
}
function deleteCachedWslCanonicalPath(key: string): void {
const cached = canonicalWslPathCache.get(key)
if (!cached) {
return
}
canonicalWslPathCache.delete(key)
canonicalWslPathCacheBytes -= cached.retainedBytes
}
function cacheWslCanonicalPath(key: string, canonicalPath: string): void {
deleteCachedWslCanonicalPath(key)
const retainedBytes = Buffer.byteLength(key, 'utf8') + Buffer.byteLength(canonicalPath, 'utf8')
if (retainedBytes > WSL_CANONICAL_PATH_CACHE_MAX_UTF8_BYTES) {
return
}
while (
canonicalWslPathCache.size >= WSL_CANONICAL_PATH_CACHE_MAX_ENTRIES ||
canonicalWslPathCacheBytes + retainedBytes > WSL_CANONICAL_PATH_CACHE_MAX_UTF8_BYTES
) {
const oldestKey = canonicalWslPathCache.keys().next().value as string | undefined
if (oldestKey === undefined) {
break
}
deleteCachedWslCanonicalPath(oldestKey)
}
canonicalWslPathCache.set(key, { canonicalPath, retainedBytes })
canonicalWslPathCacheBytes += retainedBytes
}
function settleWslCanonicalization(key: string, settlement: WslCanonicalPathSettlement): void {
if (settlement.status === 'resolved') {
cacheWslCanonicalPath(key, settlement.canonicalPath)
} else if (settlement.status === 'missing') {
// Why: a successful directory probe is stronger than a transport error;
// clear the identity so stale trust can be revoked and later rediscovered.
deleteCachedWslCanonicalPath(key)
}
// Why: keep the last known-good cache on timeout/transient WSL failures.
// Dropping it forces the next launch onto the logical `/mnt/...` guess,
// which is wrong under custom automount roots and rewrites trust keys.
const settledListeners = inFlightWslCanonicalizations.get(key) ?? new Set()
inFlightWslCanonicalizations.delete(key)
for (const listener of settledListeners) {
try {
listener(settlement)
} catch (listenerError) {
console.warn('[codex-wsl-hook-path] failed to reconcile canonical path', listenerError)
}
}
}
function scheduleWslLinuxPathCanonicalization(
distro: string,
linuxPath: string,
@@ -166,28 +102,40 @@ function scheduleWslLinuxPathCanonicalization(
'sh',
linuxPath
]
try {
execFile(
'wsl.exe',
args,
{ encoding: 'utf-8', timeout: WSL_CANONICALIZE_TIMEOUT_MS, windowsHide: true },
(error, stdout) => {
const canonicalPath = stdout.trim()
const resolvedPath = !error && canonicalPath.startsWith('/') ? canonicalPath : null
const pathMissing = !error && canonicalPath === WSL_PATH_MISSING_OUTPUT
settleWslCanonicalization(
key,
resolvedPath
? { status: 'resolved', canonicalPath: resolvedPath }
: pathMissing
? { status: 'missing' }
: { status: 'unavailable' }
)
execFile(
'wsl.exe',
args,
{ encoding: 'utf-8', timeout: WSL_CANONICALIZE_TIMEOUT_MS, windowsHide: true },
(error, stdout) => {
const canonicalPath = stdout.trim()
const resolvedPath = !error && canonicalPath.startsWith('/') ? canonicalPath : null
const pathMissing = !error && canonicalPath === WSL_PATH_MISSING_OUTPUT
const settlement: WslCanonicalPathSettlement = resolvedPath
? { status: 'resolved', canonicalPath: resolvedPath }
: pathMissing
? { status: 'missing' }
: { status: 'unavailable' }
if (settlement.status === 'resolved') {
canonicalWslPathCache.set(key, canonicalPath)
} else if (settlement.status === 'missing') {
// Why: a successful directory probe is stronger than a transport error;
// clear the identity so stale trust can be revoked and later rediscovered.
canonicalWslPathCache.delete(key)
}
)
} catch {
settleWslCanonicalization(key, { status: 'unavailable' })
}
// Why: keep the last known-good cache on timeout/transient WSL failures.
// Dropping it forces the next launch onto the logical `/mnt/...` guess,
// which is wrong under custom automount roots and rewrites trust keys.
const settledListeners = inFlightWslCanonicalizations.get(key) ?? new Set()
inFlightWslCanonicalizations.delete(key)
for (const listener of settledListeners) {
try {
listener(settlement)
} catch (listenerError) {
console.warn('[codex-wsl-hook-path] failed to reconcile canonical path', listenerError)
}
}
}
)
}
function canonicalizeWslLinuxPath(
@@ -199,7 +147,7 @@ function canonicalizeWslLinuxPath(
if (process.platform !== 'win32') {
return linuxPath
}
const cached = getCachedWslCanonicalPath(wslCanonicalizeCacheKey(distro, linuxPath))
const cached = canonicalWslPathCache.get(wslCanonicalizeCacheKey(distro, linuxPath))
// Why: every launch revalidates asynchronously. Returning the cache keeps
// launch prep synchronous while settlement repairs or revokes trust in-place.
scheduleWslLinuxPathCanonicalization(distro, linuxPath, windowsPath, onSettled)
@@ -251,13 +199,6 @@ export const _internals = {
canonicalizeWslLinuxPath,
resetWslCanonicalPathCache(): void {
canonicalWslPathCache.clear()
canonicalWslPathCacheBytes = 0
inFlightWslCanonicalizations.clear()
},
getWslCanonicalPathCacheSize(): number {
return canonicalWslPathCache.size
},
getWslCanonicalPathCacheBytes(): number {
return canonicalWslPathCacheBytes
}
}
@@ -1,37 +0,0 @@
import { describe, expect, it } from 'vitest'
import { CodexWslReconciliationGenerations } from './codex-wsl-reconciliation-generations'
const BOUNDS = {
maxEntries: 2,
maxKeyBytes: 4,
maxTotalKeyBytes: 6
}
describe('CodexWslReconciliationGenerations', () => {
it('invalidates an older reconciliation for the same runtime home', () => {
const generations = new CodexWslReconciliationGenerations(BOUNDS)
const stale = generations.advance('a')
const current = generations.advance('a')
expect(generations.isCurrent('a', stale)).toBe(false)
expect(generations.isCurrent('a', current)).toBe(true)
})
it('bounds retained homes and fails closed for an evicted callback', () => {
const generations = new CodexWslReconciliationGenerations(BOUNDS)
const evicted = generations.advance('a')
generations.advance('bb')
generations.advance('ccc')
expect(generations.isCurrent('a', evicted)).toBe(false)
expect(generations.evidence()).toEqual({ entries: 2, keyBytes: 5 })
})
it('does not retain an oversized home key', () => {
const generations = new CodexWslReconciliationGenerations(BOUNDS)
const generation = generations.advance('oversized')
expect(generations.isCurrent('oversized', generation)).toBe(false)
expect(generations.evidence()).toEqual({ entries: 0, keyBytes: 0 })
})
})
@@ -1,76 +0,0 @@
import { measureUtf8ByteLength } from '../../shared/utf8-byte-limits'
export type CodexWslReconciliationGenerationBounds = {
maxEntries: number
maxKeyBytes: number
maxTotalKeyBytes: number
}
export const DEFAULT_CODEX_WSL_RECONCILIATION_GENERATION_BOUNDS: CodexWslReconciliationGenerationBounds =
{
maxEntries: 256,
maxKeyBytes: 64 * 1024,
maxTotalKeyBytes: 1024 * 1024
}
type RetainedGeneration = {
generation: number
keyBytes: number
}
export class CodexWslReconciliationGenerations {
private readonly generations = new Map<string, RetainedGeneration>()
private nextGeneration = 0
private retainedKeyBytes = 0
constructor(
private readonly bounds: CodexWslReconciliationGenerationBounds = DEFAULT_CODEX_WSL_RECONCILIATION_GENERATION_BOUNDS
) {
for (const value of Object.values(bounds)) {
if (!Number.isSafeInteger(value) || value < 1) {
throw new RangeError('Codex WSL reconciliation bounds must be positive integers')
}
}
}
advance(key: string): number {
const generation = ++this.nextGeneration
const keyBytes = measureUtf8ByteLength(key, {
stopAfterBytes: this.bounds.maxKeyBytes
})
this.delete(key)
if (keyBytes.exceededLimit || keyBytes.byteLength > this.bounds.maxTotalKeyBytes) {
return generation
}
while (
this.generations.size >= this.bounds.maxEntries ||
this.retainedKeyBytes + keyBytes.byteLength > this.bounds.maxTotalKeyBytes
) {
const oldest = this.generations.keys().next().value
if (oldest === undefined) {
return generation
}
this.delete(oldest)
}
this.generations.set(key, { generation, keyBytes: keyBytes.byteLength })
this.retainedKeyBytes += keyBytes.byteLength
return generation
}
isCurrent(key: string, generation: number): boolean {
return this.generations.get(key)?.generation === generation
}
evidence(): { entries: number; keyBytes: number } {
return { entries: this.generations.size, keyBytes: this.retainedKeyBytes }
}
private delete(key: string): void {
const retained = this.generations.get(key)
if (!retained) {
return
}
this.generations.delete(key)
this.retainedKeyBytes -= retained.keyBytes
}
}
+2 -2
View File
@@ -3,6 +3,7 @@ import {
existsSync,
lstatSync,
mkdirSync,
readFileSync,
realpathSync,
statSync,
unlinkSync,
@@ -11,7 +12,6 @@ import {
import { basename, dirname, join, posix as pathPosix, win32 as pathWin32 } from 'node:path'
import { createHash, randomUUID } from 'node:crypto'
import { renameFileWithWindowsRetry } from '../codex-accounts/fs-utils'
import { readAgentStateFileSync } from '../agent-state-file-reader'
import { foldWslUncPathCaseInsensitiveParts } from '../../shared/wsl-paths'
import { writeRollingFileBackup } from '../rolling-file-backup'
import {
@@ -327,7 +327,7 @@ function isCodexEventLabel(value: string): value is CodexEventLabel {
// Why: strip a leading BOM (some Windows editors write one) so header regexes anchored at `^[ \t]*\[` still match.
function readTomlFile(configPath: string): string {
const raw = readAgentStateFileSync(configPath)
const raw = readFileSync(configPath, 'utf-8')
return raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw
}
+9 -10
View File
@@ -1,9 +1,8 @@
/* 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, statSync, unlinkSync } from 'node:fs'
import { existsSync, readFileSync, statSync, unlinkSync } from 'node:fs'
import { join, win32 as pathWin32 } from 'node:path'
import type { SFTPWrapper } from 'ssh2'
import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types'
import { readAgentStateFileSync } from '../agent-state-file-reader'
import {
buildManagedCommandHook,
createManagedCommandMatcher,
@@ -12,7 +11,6 @@ import {
hookDefinitionHasManagedCommand,
MANAGED_HOOK_TIMEOUT_SECONDS,
readHooksJson,
readHooksJsonRawForGenerationCheck,
readHooksJsonWithRaw,
removeManagedCommands,
wrapPosixHookCommand,
@@ -83,7 +81,6 @@ import {
} from './codex-managed-trust-reconciliation'
import type { CodexTrustGrantLedgerHome } from './codex-trust-grant-ledger'
import { mutateRealHomeHooksPreservingUserTrust } from './codex-user-hook-trust-rebase'
import { CodexWslReconciliationGenerations } from './codex-wsl-reconciliation-generations'
// Why: Pre/PostToolUse feed the live in-flight-tool readout; PermissionRequest exits with no decision so Codex still shows its approval UI while Orca flips the pane to waiting.
const CODEX_EVENTS = [
@@ -544,7 +541,7 @@ function applyMirroredRuntimeUserHookTrustStates(
return
}
const existing = readAgentStateFileSync(tomlPath)
const existing = readFileSync(tomlPath, 'utf-8')
let updated = existing
for (const { entry, enabled } of entries) {
const headerKeyPattern = buildHookTrustHeaderKeyPattern(computeTrustKey(entry))
@@ -648,7 +645,7 @@ function cleanupLegacySystemManagedHooks(): void {
afterHooks: nextHooks,
writeHooks: () => {
if (
readHooksJsonRawForGenerationCheck(legacyConfigPath) !== previousRaw ||
readFileSync(legacyConfigPath, 'utf-8') !== previousRaw ||
resolveHooksJsonWritePath(legacyConfigPath) !== hooksWritePath
) {
// Why: the pre-mutation RPC may overlap a user save; downgrade must
@@ -694,7 +691,7 @@ function cleanupLegacyCodexProfileHooks(): void {
return
}
const existing = readAgentStateFileSync(profilePath)
const existing = readFileSync(profilePath, 'utf-8')
const next = stripLegacyManagedProfileBlock(existing)
if (next === existing) {
return
@@ -1024,14 +1021,16 @@ function getWslReconciliationKey(runtimeHomePath: string): string {
}
export class CodexHookService {
private readonly wslReconciliationGenerations = new CodexWslReconciliationGenerations()
private readonly wslReconciliationGeneration = new Map<string, number>()
private supersedeWslReconciliation(runtimeHomePath: string | null | undefined): number {
if (!runtimeHomePath) {
return 0
}
const key = getWslReconciliationKey(runtimeHomePath)
return this.wslReconciliationGenerations.advance(key)
const generation = (this.wslReconciliationGeneration.get(key) ?? 0) + 1
this.wslReconciliationGeneration.set(key, generation)
return generation
}
installForRuntimeHome(
@@ -1059,7 +1058,7 @@ export class CodexHookService {
: null
const action = getWslHookReconciliationAction({
settlement,
isCurrentGeneration: this.wslReconciliationGenerations.isCurrent(key, generation),
isCurrentGeneration: this.wslReconciliationGeneration.get(key) === generation,
installedTrustConfigPath,
resolvedTrustConfigPath: resolvedPlan?.trustConfigPath ?? null,
installSucceeded
+3 -6
View File
@@ -1,7 +1,5 @@
import { existsSync, writeFileSync } from 'node:fs'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { MAX_AGENT_STATE_FILE_BYTES, readAgentStateJsonFileSync } from '../agent-state-file-reader'
import { stringifyJsonWithinByteLimit } from '../../shared/node-bounded-json-stringify'
import {
createManagedCommandMatcher,
readHooksJson,
@@ -53,7 +51,7 @@ function readHookTrustProvenance(
return null
}
try {
const parsed = readAgentStateJsonFileSync(provenancePath)
const parsed: unknown = JSON.parse(readFileSync(provenancePath, 'utf-8'))
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null
}
@@ -99,8 +97,7 @@ export function snapshotCodexRuntimeHookTrustProvenance(
}
}
const file: HookTrustProvenanceFile = { version: 1, entries }
const { serialized } = stringifyJsonWithinByteLimit(file, MAX_AGENT_STATE_FILE_BYTES - 1, 2)
writeFileSync(getProvenancePath(runtimeHomePath), `${serialized}\n`, {
writeFileSync(getProvenancePath(runtimeHomePath), `${JSON.stringify(file, null, 2)}\n`, {
encoding: 'utf-8',
mode: 0o600
})