diff --git a/docs/codex-skill-runtime.md b/docs/codex-skill-runtime.md index 109674b6..8933c336 100644 --- a/docs/codex-skill-runtime.md +++ b/docs/codex-skill-runtime.md @@ -16,7 +16,7 @@ New Codex runs default to a native team with capacity for four members including The `--resume` command continues solo runs and native teams with their saved research mode, Skill loading, provider and environment. The host checks the frozen identities before resuming the thread. New runs save `researchSkillWorkflow: full` and an execution plan. Historical single-researcher checkpoints without that marker keep their original workflow. Inspect older host-scheduled archives with the current CLI and use the original pinned runtime to resume them. A new strategy can start a separate run from the saved artifacts. -For Codex sessions metered by upstream request receipts, the host sends `excludeTurns: true` on resume. Codex restores the thread internally and returns metadata without sending the full transcript over stdio. Direct providers whose budget gate uses native thread totals still request turn history so Codex can replay saved usage. +For Codex sessions metered by upstream request receipts, the host sends `excludeTurns: true` on resume. Codex restores the thread internally and returns metadata without sending the full transcript over stdio. Direct providers whose budget gate uses native thread totals still request turn history so Codex can replay saved usage. If that reply exceeds the 8 MiB stdio frame limit, the host reopens the thread once with `excludeTurns: true`; the next turn's cumulative total still includes the skipped replay. In continuous cooling, an oversized frame that recurs after one cooldown stops the run instead of cooling again. The default `--skill-loading native` checks Codex discovery and sends native skill input on ordinary host turns. `--skill-loading file` explicitly directs Codex to read the same pinned file. Native child communication carries the host's frozen context and explicit pinned-file reading instructions; its execution plan records file loading because Codex's typed input cannot combine an inter-agent communication with a skill input. Discovery and an accepted request do not prove that a provider followed the skill; that requires separate execution evidence. diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 7f68f387..2bde04ad 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -313,7 +313,19 @@ class CodexRpc { } } +const RESUME_HISTORY_TOO_LARGE = 'math_codex_resume_history_too_large'; + export async function createCodexMathSession(options: MathAgentOptions): Promise { + try { return await openCodexMathSession(options, false); } + catch (error) { + // The usage replay is optional; a thread whose history no longer fits one frame resumes from metadata. + if (!(error instanceof Error) || error.message !== RESUME_HISTORY_TOO_LARGE) throw error; + options.signal?.throwIfAborted(); + return openCodexMathSession(options, true); + } +} + +async function openCodexMathSession(options: MathAgentOptions, forceMetadataOnlyResume: boolean): Promise { options.signal?.throwIfAborted(); const skills = options.skills?.map(skill => ({ ...skill })) ?? []; assertMathAgentSkillsCurrent(skills); @@ -890,15 +902,21 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise ...(tools ? { dynamicTools: tools.definitions } : {}), } } : undefined; // Codex restores history internally. Echoing it can exceed the stdio frame limit. - // Retain historical usage replay for sessions that depend on native thread totals. - const metadataOnlyResume = usesRequestReceipts || (nativeControl && !options.requestGate); + // Retain historical usage replay for sessions that depend on native thread totals, unless the history + // already failed to fit one frame; cumulative totals of the next turn still include the skipped replay. + const metadataOnlyResume = forceMetadataOnlyResume || usesRequestReceipts || (nativeControl && !options.requestGate); const threadSettings = { ...settings, ...(options.threadId ? { threadId: options.threadId, ...(metadataOnlyResume ? { excludeTurns: true } : {}) } : {}), ...(!options.threadId && tools?.definitions.length ? { dynamicTools: tools.definitions } : {}), }; const result = await rpc.request(bootstrap ? 'theoremos/agentControl/start' : options.threadId ? 'thread/resume' : 'thread/start', - bootstrap ? { version: 1, bootstrap, [options.threadId ? 'resume' : 'thread']: threadSettings } : threadSettings); + bootstrap ? { version: 1, bootstrap, [options.threadId ? 'resume' : 'thread']: threadSettings } : threadSettings) + .catch(error => { + if (options.threadId && !metadataOnlyResume && error instanceof Error && + error.message === 'math_codex_transport_closed:frame_too_large') throw new Error(RESUME_HISTORY_TOO_LARGE, { cause: error }); + throw error; + }); const startedThreadId = object(result.thread).id; if (typeof startedThreadId !== 'string' || !startedThreadId) throw new Error('math_codex_thread_missing'); threadId = startedThreadId; diff --git a/src/runtime/harnessProcess.ts b/src/runtime/harnessProcess.ts index 0d81483c..3d20a267 100644 --- a/src/runtime/harnessProcess.ts +++ b/src/runtime/harnessProcess.ts @@ -90,7 +90,6 @@ const READ_ROOT_FILES = ['DEEPSCIENTIST_LEAN_EVAL_TOOL_MANIFEST', 'DEEPSCIENTIST const READ_ROOT_LISTS = ['PATH', 'LEAN_PATH', 'DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS', 'DEEPSCIENTIST_MATH_TRUSTED_ELAN_ROOTS', HARNESS_READ_ROOTS_ENV] as const; const READ_ROOT_DESCRIPTORS = ['DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT', 'DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT_SANDBOX'] as const; -const LINK_SCAN_DEPTH = 5, LINK_SCAN_ENTRIES = 20_000; function hostHomes(): string[] { const homes = [os.homedir()]; @@ -143,33 +142,24 @@ function scriptInterpreter(file: string): string | undefined { } catch { return undefined; } finally { if (descriptor !== undefined) fs.closeSync(descriptor); } } -/** Targets of symlinks in a launch directory, such as `.lake/packages` or a git worktree's metadata. */ -function linkedTargets(directory: string): string[] { - const targets: string[] = []; - let budget = LINK_SCAN_ENTRIES; - const visit = (current: string, depth: number) => { - let entries: fs.Dirent[]; - try { entries = fs.readdirSync(current, { withFileTypes: true }); } catch { return; } - for (const entry of entries) { - if (--budget < 0) return; - const child = path.join(current, entry.name); - if (entry.isSymbolicLink()) { - try { const real = fs.realpathSync(child); if (!isMathPathWithin(directory, real)) targets.push(real); } catch { /* dangling */ } - } else if (entry.isDirectory() && depth < LINK_SCAN_DEPTH && !['.git', '.scratch', 'node_modules'].includes(entry.name)) { - visit(child, depth + 1); - } else if (entry.isFile() && entry.name === '.git' && depth === 0) { - // A git worktree names its metadata directory; that directory names the shared repository. - try { - const gitdir = path.resolve(current, /^gitdir: (.+)$/mu.exec(fs.readFileSync(child, 'utf8'))![1]!.trim()); - targets.push(gitdir); - const common = fs.readFileSync(path.join(gitdir, 'commondir'), 'utf8').trim(); - targets.push(path.resolve(gitdir, common)); - } catch { /* not a worktree link */ } - } - } - }; - visit(directory, 0); - return targets; +/** + * Metadata of the git worktree a launch directory checks out. The directory is writable by the harness, so + * its own symlinks and `.git` file never widen the home allowlist: a link target is readable only through a + * host-declared root. A `.git` file is followed only when its metadata directory, which the harness cannot + * write, names this checkout back and lies under the shared repository's `worktrees`. + */ +function worktreeMetadata(directory: string): string[] { + const marker = path.join(directory, '.git'); + try { + if (!fs.lstatSync(marker).isFile()) return []; + const gitdir = realOrResolved(path.resolve(directory, /^gitdir: (.+)$/mu.exec(fs.readFileSync(marker, 'utf8'))![1]!.trim())); + if (isMathPathWithin(directory, gitdir)) return []; + const back = fs.readFileSync(path.join(gitdir, 'gitdir'), 'utf8').trim(); + if (realOrResolved(path.resolve(gitdir, back)) !== realOrResolved(marker)) return []; + const common = realOrResolved(path.resolve(gitdir, fs.readFileSync(path.join(gitdir, 'commondir'), 'utf8').trim())); + if (path.dirname(gitdir) !== path.join(common, 'worktrees')) return []; + return [gitdir, common]; + } catch { return []; /* not a worktree checkout */ } } // A granted read root such as an app worktree links its dependencies (`node_modules`) from its top level. @@ -185,8 +175,8 @@ function rootLinks(root: string): string[] { /** * Home paths a harness launch may read: its PATH (with the installation prefix of each `bin`), the Lean, - * cache and tool roots its environment names, the launcher's package, the targets of symlinks in its - * workspace and profile and of top-level symlinks in its extra read roots. Everything else in a home is masked. + * cache and tool roots its environment names, the launcher's package, the verified git worktree metadata of its + * workspace and profile and the targets of top-level symlinks in its extra read roots. Everything else in a home is masked. */ export function harnessReadRoots(environment: NodeJS.ProcessEnv, directories: readonly string[] = [], executable?: string, extra: readonly string[] = [], homes: readonly string[] = hostHomes()): string[] { @@ -247,7 +237,7 @@ export function harnessReadRoots(environment: NodeJS.ProcessEnv, directories: re const interpreter = scriptInterpreter(addProgram(executable)); if (interpreter) addProgram(interpreter); } - for (const directory of directories) for (const target of linkedTargets(directory)) add(target); + for (const directory of directories) for (const target of worktreeMetadata(directory)) add(target); return [...roots].sort(); } diff --git a/src/solver/modules/search.ts b/src/solver/modules/search.ts index 409a5214..23f0e639 100644 --- a/src/solver/modules/search.ts +++ b/src/solver/modules/search.ts @@ -528,5 +528,7 @@ export function planResearchCooldown(error: string | undefined, cycles: number, if (budget.maxTurns !== Infinity || budget.remainingMs !== Infinity || budget.aborted || !['math_model_concurrency_limit', 'math_model_request_failed', 'math_model_request_timeout', 'math_codex_transport_closed'].includes(reason)) return undefined; + // An oversized frame recurs while the same history is replayed; after one cooldown it is not transient. + if (error === 'math_codex_transport_closed:frame_too_large' && cycles > 0) return undefined; return { cycle: cycles + 1, delayMs: Math.min(300_000, 60_000 * 2 ** Math.min(cycles, 3)), reason }; } diff --git a/tests/codexSessionAgentControl.test.ts b/tests/codexSessionAgentControl.test.ts index a882c2d3..165a7761 100644 --- a/tests/codexSessionAgentControl.test.ts +++ b/tests/codexSessionAgentControl.test.ts @@ -276,6 +276,17 @@ describe('native AgentControl stdio integration without model calls', () => { expect(session.usageSource).toBe('native-thread-totals'); }); + it('resumes a budget-gated Lead from metadata once its replayed history exceeds the stdio frame limit', async () => { + session = await createCodexMathSession({ ...options, threadId: 'root-id', nativeAgentControl: host, + requestGate: () => ({ allowed: true, settle: () => {} }), + environment: { ...options.environment, LONG_RESUME_HISTORY: '1' } }); + const resumes = calls().filter(call => call.method === 'thread/resume').map(call => call.params.excludeTurns); + expect(resumes).toEqual([undefined, true]); + expect(session.threadId).toBe('root-id'); + expect(session.usageSource).toBe('native-thread-totals'); + expect(await session.run('Continue the saved proof.', 'task', directory, () => {})).toBe('completed'); + }); + it('keeps native compaction open until the completed maintenance turn releases the writer', async () => { const release = deferred(), reachedRelease = deferred(); session = await createCodexMathSession({ ...options, nativeAgentControl: { request: async request => { diff --git a/tests/harnessProcess.test.ts b/tests/harnessProcess.test.ts index d3aab450..477e13cd 100644 --- a/tests/harnessProcess.test.ts +++ b/tests/harnessProcess.test.ts @@ -106,32 +106,34 @@ describe('shared native harness process isolation', () => { expect(fs.readFileSync(path.join(home, '.codex/auth.json'), 'utf8')).toBe('codex secret'); }); - it('derives home read roots from the launch environment, executable and workspace links', () => { + it('derives home read roots from the launch environment, executable and a verified workspace worktree', () => { const home = path.join(root, 'home'), bin = path.join(home, '.local/bin'); const release = path.join(home, '.codex/packages/releases/1/bin'), current = path.join(home, '.codex/packages/current'); const npm = path.join(home, '.npm-global/lib/node_modules'), cache = path.join(home, 'mathlib-cache'); - const gitdir = path.join(home, 'repo/.git/worktrees/work'); - for (const directory of [bin, release, path.join(npm, '@scope/cli'), path.join(root, 'opt/tool/bin'), cache, gitdir, + const gitdir = path.join(home, 'repo/.git/worktrees/work'), unlisted = path.join(home, 'unlisted'); + for (const directory of [bin, release, path.join(npm, '@scope/cli'), path.join(root, 'opt/tool/bin'), cache, gitdir, unlisted, path.join(workspace, '.lake/packages')]) fs.mkdirSync(directory, { recursive: true }); fs.writeFileSync(path.join(release, 'codex'), ''); fs.writeFileSync(path.join(npm, '@scope/cli/cli.js'), ''); fs.symlinkSync('releases/1', current); fs.symlinkSync(path.join(current, 'bin/codex'), path.join(bin, 'codex')); fs.symlinkSync(path.join(npm, '@scope/cli/cli.js'), path.join(bin, 'cli')); fs.symlinkSync(cache, path.join(workspace, '.lake/packages/mathlib')); + fs.symlinkSync(unlisted, path.join(workspace, '.lake/packages/other')); fs.writeFileSync(path.join(workspace, '.git'), `gitdir: ${gitdir}\n`); fs.writeFileSync(path.join(gitdir, 'commondir'), '../..\n'); + fs.writeFileSync(path.join(gitdir, 'gitdir'), path.join(workspace, '.git') + '\n'); const roots = harnessReadRoots({ PATH: `${bin}:${path.join(root, 'opt/tool/bin')}:/usr/bin`, LEAN_PATH: path.join(home, 'lean-path'), DEEPSCIENTIST_MATH_ENV_FILE: path.join(root, 'conf/math.env'), [HARNESS_READ_ROOTS_ENV]: `${path.join(home, 'granted')}:relative`, DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT: JSON.stringify({ rootPath: path.join(home, 'proof'), leaseSocket: path.join(home, 'lease.sock') }), - DEEPSCIENTIST_MATH_TOOLS_ROOT: path.join(root, 'tools/runtime'), + DEEPSCIENTIST_MATH_TOOLS_ROOT: path.join(root, 'tools/runtime'), DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: cache, }, [workspace], path.join(bin, 'codex'), [path.join(home, 'app')], [home]); expect(roots).toEqual(expect.arrayContaining([bin, path.join(bin, 'codex'), path.join(current, 'bin/codex'), release, path.join(home, '.codex/packages/releases/1'), npm, path.join(root, 'opt/tool/bin'), path.join(root, 'opt/tool'), path.join(home, 'lean-path'), path.join(root, 'conf'), path.join(home, 'granted'), path.join(home, 'proof'), path.join(home, 'lease.sock'), path.join(root, 'tools/runtime'), path.join(root, 'tools'), path.join(home, '.elan'), path.join(home, 'app'), cache, gitdir, path.join(home, 'repo/.git')])); - // Neither a home nor its `.local` counts as an installation prefix. - for (const personal of [home, path.join(home, '.local'), '/', 'relative']) expect(roots).not.toContain(personal); + // Neither a home nor its `.local` counts as an installation prefix; a workspace link grants nothing. + for (const personal of [home, path.join(home, '.local'), '/', 'relative', unlisted]) expect(roots).not.toContain(personal); // A read root's top-level links are followed; deeper links are not scanned. const deps = path.join(home, 'deps'), deep = path.join(home, 'deep'), app = path.join(home, 'app'); for (const directory of [deps, deep, path.join(app, 'sub')]) fs.mkdirSync(directory, { recursive: true }); @@ -147,6 +149,44 @@ describe('shared native harness process isolation', () => { expect(harnessReadRoots({ ELAN_HOME: path.join(root, 'elan') }, [], script, [], [home])).toEqual([path.join(root, 'elan'), node, script].sort()); }); + it('never widens the home allowlist from links or a forged .git the harness wrote in its own directories', () => { + const home = path.join(root, 'home'), runs = path.join(home, 'runs/other-problem'), repo = path.join(home, 'repo/.git'); + const real = path.join(repo, 'worktrees/real'), stranger = path.join(repo, 'worktrees/stranger'); + for (const directory of [runs, real, stranger, path.join(workspace, 'a/b')]) fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync(path.join(runs, 'answer'), 'other answer'); + for (const gitdir of [real, stranger]) fs.writeFileSync(path.join(gitdir, 'commondir'), '../..\n'); + fs.writeFileSync(path.join(real, 'gitdir'), path.join(workspace, '.git') + '\n'); + fs.writeFileSync(path.join(stranger, 'gitdir'), path.join(outside, 'stranger/.git') + '\n'); + const granted = () => harnessReadRoots({ ELAN_HOME: path.join(root, 'elan') }, [workspace, profile], undefined, [], [home]); + // Links planted at any depth of the workspace or profile. + fs.symlinkSync(home, path.join(workspace, 'h')); fs.symlinkSync(runs, path.join(workspace, 'a/b/x')); + fs.symlinkSync(home, path.join(profile, 'h')); + expect(granted()).toEqual([path.join(root, 'elan')]); + // A `.git` file naming a directory that does not name this checkout back, or not a worktree's metadata. + for (const target of [runs, stranger, path.join(home, 'repo')]) { + fs.writeFileSync(path.join(workspace, '.git'), `gitdir: ${target}\n`); + expect(granted()).toEqual([path.join(root, 'elan')]); + } + // A `.git` symlink is not a worktree marker either. + fs.rmSync(path.join(workspace, '.git')); fs.symlinkSync(path.join(real, 'gitdir'), path.join(workspace, '.git')); + expect(granted()).toEqual([path.join(root, 'elan')]); + fs.rmSync(path.join(workspace, '.git')); fs.writeFileSync(path.join(workspace, '.git'), `gitdir: ${real}\n`); + expect(granted()).toEqual([path.join(root, 'elan'), repo, real].sort()); + // The shell cannot read through any planted link. + vi.stubEnv('HOME', home); + try { + const launch = prepareHarnessProcess({ workspace, profile, environment: { ...process.env, ELAN_HOME: path.join(root, 'elan') } }, + process.execPath, ['-e', `const fs=require('fs'); + for (const file of ${JSON.stringify([path.join(runs, 'answer'), path.join(workspace, 'h/runs/other-problem/answer'), + path.join(workspace, 'a/b/x/answer'), path.join(profile, 'h/runs/other-problem/answer')])}) { + let text=''; try { text=fs.readFileSync(file,'utf8'); } catch(e) { if(e.code!=='ENOENT'&&e.code!=='EACCES') throw e; } + if(text) process.exit(7); + }`]); + const result = spawnSync(launch.command, launch.args, { env: launch.env, encoding: 'utf8', timeout: 10_000 }); + expect(result.status, result.stderr).toBe(0); + } finally { vi.unstubAllEnvs(); } + }); + it('masks a home around its launch and read roots, following user-owned links only', () => { const home = path.join(root, 'home'), store = path.join(outside, 'store'); for (const directory of ['work', 'tools/bin', 'notes', '.ssh', '.config/tool']) fs.mkdirSync(path.join(home, directory), { recursive: true }); diff --git a/tests/workerRecovery.test.ts b/tests/workerRecovery.test.ts index 8be37d47..f0a2da24 100644 --- a/tests/workerRecovery.test.ts +++ b/tests/workerRecovery.test.ts @@ -675,4 +675,12 @@ describe('recoverable failure classification', () => { 'math_source_outside_ownership', 'math_model_turn_failed']) expect(planResearchCooldown(reason, 0, unlimited)).toBeUndefined(); }); + + it('stops cooling an oversized frame that recurs after one cooldown', () => { + const unlimited = { maxTurns: Infinity, remainingMs: Infinity, aborted: false }; + const oversized = 'math_codex_transport_closed:frame_too_large'; + expect(planResearchCooldown(oversized, 0, unlimited)).toEqual({ cycle: 1, delayMs: 60_000, reason: 'math_codex_transport_closed' }); + expect(planResearchCooldown(oversized, 1, unlimited)).toBeUndefined(); + expect(planResearchCooldown('math_codex_transport_closed:process_exit:code=1:signal=none', 1, unlimited)).toMatchObject({ cycle: 2 }); + }); });