From c7a6e20b44a7e680fd9086754ad637dad2131987 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:28:35 -0300 Subject: [PATCH 01/43] Tools runtime: jail, tolerant edit, transactional rollback, contained bash Implements the ToolRuntime contract for bash, read, write, edit, grep and glob in src/tools: - Workspace jail: paths resolve to real paths under the session cwd, MCP roots and configured extra roots; traversal, links leaving the roots, Windows alias spellings and NUL bytes are refused. Writes and edits to protected host paths and .git are refused. - Commits re-check what prepare saw: no link at the final component (O_NOFOLLOW plus an fd path check), parent directories unchanged, content hash equal to the prepared before-hash. Writes are atomic (temp file in the same directory, mode kept; creates never replace a file that appeared meanwhile). - Edit uses Turnpack's tolerant matcher (exact, line endings, copied line numbers, trailing whitespace, indentation, punctuation), refusing ambiguous and missing matches with the nearest text. - Transactions journal originals in memory and durably under the state dir (64 MiB cap), roll back without clobbering external changes, and recoverStaleJournals restores journals left by a dead server. - bash runs in its own process group with output caps, kills the group on timeout, abort and exit, and runs under @anthropic-ai/sandbox-runtime (bubblewrap or Seatbelt) when the policy asks for containment. - grep and glob are pure JS with .git, node_modules and .gitignore ignores, and never follow links. Co-Authored-By: Claude Opus 5.5 --- NOTICE | 17 ++ package-lock.json | 52 ++++ package.json | 1 + src/tools/bash.test.ts | 155 +++++++++++ src/tools/bash.ts | 190 +++++++++++++ src/tools/diff.test.ts | 62 +++++ src/tools/diff.ts | 178 ++++++++++++ src/tools/edit-match.test.ts | 113 ++++++++ src/tools/edit-match.ts | 495 ++++++++++++++++++++++++++++++++++ src/tools/fs-ops.ts | 249 +++++++++++++++++ src/tools/index.ts | 5 + src/tools/integration.test.ts | 62 +++++ src/tools/jail.ts | 224 +++++++++++++++ src/tools/journal.test.ts | 185 +++++++++++++ src/tools/journal.ts | 386 ++++++++++++++++++++++++++ src/tools/runtime.test.ts | 370 +++++++++++++++++++++++++ src/tools/runtime.ts | 372 +++++++++++++++++++++++++ src/tools/sandbox.ts | 133 +++++++++ src/tools/search.ts | 338 +++++++++++++++++++++++ 19 files changed, 3587 insertions(+) create mode 100644 src/tools/bash.test.ts create mode 100644 src/tools/bash.ts create mode 100644 src/tools/diff.test.ts create mode 100644 src/tools/diff.ts create mode 100644 src/tools/edit-match.test.ts create mode 100644 src/tools/edit-match.ts create mode 100644 src/tools/fs-ops.ts create mode 100644 src/tools/index.ts create mode 100644 src/tools/integration.test.ts create mode 100644 src/tools/jail.ts create mode 100644 src/tools/journal.test.ts create mode 100644 src/tools/journal.ts create mode 100644 src/tools/runtime.test.ts create mode 100644 src/tools/runtime.ts create mode 100644 src/tools/sandbox.ts create mode 100644 src/tools/search.ts diff --git a/NOTICE b/NOTICE index 03af142..63d495a 100644 --- a/NOTICE +++ b/NOTICE @@ -7,3 +7,20 @@ Third-party code ---------------- Portions of this product that are derived from third-party projects are listed below together with their copyright notices and licenses. + +Turnpack + Files: src/tools/edit-match.ts, src/tools/edit-match.test.ts (ported), + src/tools/journal.ts and src/tools/jail.ts (design and parts adapted) + Source: https://github.com/OnlyTerp/turnpack (commit b14330d) + License: Apache License, Version 2.0 + Modified by the agent-code-mode authors (see the header of each file). + Turnpack's NOTICE: + + Turnpack + Copyright 2026 OnlyTerp (https://github.com/OnlyTerp) + + This product is licensed under the Apache License, Version 2.0. + You may obtain a copy of the License in the LICENSE file, or at + http://www.apache.org/licenses/LICENSE-2.0 + + Project home: https://github.com/OnlyTerp/turnpack diff --git a/package-lock.json b/package-lock.json index 596f70d..321bc15 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sandbox-runtime": "^0.0.81", "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, @@ -24,6 +25,33 @@ "node": ">=22" } }, + "node_modules/@anthropic-ai/sandbox-runtime": { + "version": "0.0.81", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.81.tgz", + "integrity": "sha512-bjHDu87gjIR7+Oxy9jPiK3v8CvSELCzfpXa3fjqfSKdvlZET2iF51xcXILWPayTpowB3xtZeQVf2JR916nVW/w==", + "license": "Apache-2.0", + "dependencies": { + "@pondwader/socks5-server": "^1.0.10", + "commander": "^12.1.0", + "node-forge": "^1.4.0", + "zod": "^3.25.0" + }, + "bin": { + "srt": "dist/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@anthropic-ai/sandbox-runtime/node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/@emnapi/core": { "version": "2.0.0-beta.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", @@ -175,6 +203,12 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@pondwader/socks5-server": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@pondwader/socks5-server/-/socks5-server-1.0.10.tgz", + "integrity": "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==", + "license": "MIT" + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.19", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", @@ -1057,6 +1091,15 @@ "node": ">=18" } }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/content-disposition": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", @@ -2054,6 +2097,15 @@ "url": "https://opencollective.com/express" } }, + "node_modules/node-forge": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", + "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", diff --git a/package.json b/package.json index 1d1997d..0f8d93a 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "bench": "node -e \"console.log('bench: not implemented yet')\"" }, "dependencies": { + "@anthropic-ai/sandbox-runtime": "^0.0.81", "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, diff --git a/src/tools/bash.test.ts b/src/tools/bash.test.ts new file mode 100644 index 0000000..0806edf --- /dev/null +++ b/src/tools/bash.test.ts @@ -0,0 +1,155 @@ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { BashContainment, BashResult, PolicySnapshot, SessionContext } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { NodeToolRuntime } from './runtime.js'; +import { containmentUnavailableReason } from './sandbox.js'; + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let ctx: SessionContext; +let seq = 0; + +function policyWith(bashContainment: BashContainment): PolicySnapshot { + return { host: 'generic', bashContainment, protectedPaths: [], payload: null }; +} + +async function bash( + command: string, + opts: { timeoutMs?: number; signal?: AbortSignal; containment?: BashContainment; capBytes?: number } = {}, +): Promise { + const rt = new NodeToolRuntime({ stateDir: path.join(base, 'state'), ...(opts.capBytes ? { bashOutputCapBytes: opts.capBytes } : {}) }); + const prepared = await rt.prepare( + { id: `c${++seq}`, tool: 'bash', args: { command, ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}) } }, + ctx, + policyWith(opts.containment ?? { mode: 'none' }), + ); + const result = await rt.commit(prepared, opts.signal ?? new AbortController().signal); + if (!('exitCode' in result)) throw new Error('not a bash result'); + return result; +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function eventually(check: () => boolean, ms = 3000): Promise { + const end = Date.now() + ms; + while (Date.now() < end) { + if (check()) return true; + await new Promise((r) => setTimeout(r, 50)); + } + return check(); +} + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-bash-'))); + ws = path.join(base, 'ws'); + mkdirSync(ws); + ctx = makeContext(ws); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe.skipIf(IS_WINDOWS)('bash', () => { + it('returns exit code and output; a non-zero exit is a result', async () => { + const r = await bash('echo out; echo err >&2; exit 3'); + expect(r).toEqual({ exitCode: 3, signal: null, stdout: 'out\n', stderr: 'err\n', truncated: false, timedOut: false }); + }); + + it('kills the whole process group on timeout, grandchildren included', async () => { + const started = Date.now(); + const r = await bash('sleep 100 & echo $! > bg.pid; sleep 100', { timeoutMs: 500 }); + expect(r.timedOut).toBe(true); + expect(r.signal).toBe('SIGKILL'); + expect(Date.now() - started).toBeLessThan(5000); + const pid = Number(readFileSync(path.join(ws, 'bg.pid'), 'utf8')); + expect(await eventually(() => !alive(pid))).toBe(true); + }); + + it('does not leave background processes behind after a normal exit', async () => { + const started = Date.now(); + const r = await bash('sleep 100 & echo $!'); + expect(Date.now() - started).toBeLessThan(5000); + const pid = Number(r.stdout.trim()); + expect(await eventually(() => !alive(pid))).toBe(true); + }); + + it('never starts when the signal is already aborted', async () => { + const ac = new AbortController(); + ac.abort(); + await expect(bash('touch spawned.txt', { signal: ac.signal })).rejects.toMatchObject({ code: 'cancelled' }); + expect(existsSync(path.join(ws, 'spawned.txt'))).toBe(false); + }); + + it('stops a running command on abort', async () => { + const ac = new AbortController(); + setTimeout(() => ac.abort(), 200); + const started = Date.now(); + await expect(bash('sleep 30', { signal: ac.signal })).rejects.toBeInstanceOf(ToolError); + expect(Date.now() - started).toBeLessThan(5000); + }); + + it('caps stdout and stderr', async () => { + const r = await bash("head -c 5000 /dev/zero | tr '\\0' a; head -c 3000 /dev/zero | tr '\\0' b >&2", { capBytes: 1000 }); + expect(r.stdout).toBe('a'.repeat(1000)); + expect(r.stderr).toBe('b'.repeat(1000)); + expect(r.truncated).toBe(true); + }); + + it('refuses a containment with a relative writable root', async () => { + await expect(bash('true', { containment: { mode: 'sandbox', readOnly: false, writableRoots: ['rel'], network: false } })).rejects.toMatchObject({ + code: 'containment-unavailable', + }); + }); +}); + +const unavailable = await containmentUnavailableReason(); +if (unavailable !== null) { + // Logged so a CI run shows why the containment tests were skipped. + console.log(`bash containment tests skipped: ${unavailable}`); +} + +describe.skipIf(unavailable !== null)('bash containment (OS sandbox)', () => { + const readOnly: BashContainment = { mode: 'sandbox', readOnly: true, writableRoots: [], network: false }; + + it('blocks writes under a read-only sandbox', async () => { + const r = await bash('touch x', { containment: readOnly }); + expect(r.exitCode).not.toBe(0); + expect(existsSync(path.join(ws, 'x'))).toBe(false); + }); + + it('allows writes only under the writable roots', async () => { + const r = await bash(`touch y && touch ${JSON.stringify(path.join(base, 'z'))}`, { + containment: { mode: 'sandbox', readOnly: false, writableRoots: [ws], network: false }, + }); + expect(existsSync(path.join(ws, 'y'))).toBe(true); + expect(r.exitCode).not.toBe(0); + expect(existsSync(path.join(base, 'z'))).toBe(false); + }); + + it('blocks the network when network is off', async () => { + const r = await bash("exec 3<>/dev/tcp/1.1.1.1/80 && echo connected", { containment: readOnly, timeoutMs: 15_000 }); + expect(r.exitCode).not.toBe(0); + expect(r.stdout).not.toContain('connected'); + }); + + it('kills the sandboxed command on timeout', async () => { + const started = Date.now(); + const r = await bash('sleep 100', { containment: readOnly, timeoutMs: 1000 }); + expect(r.timedOut).toBe(true); + expect(Date.now() - started).toBeLessThan(8000); + }); +}); diff --git a/src/tools/bash.ts b/src/tools/bash.ts new file mode 100644 index 0000000..8371aa9 --- /dev/null +++ b/src/tools/bash.ts @@ -0,0 +1,190 @@ +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import type { BashEffect, BashResult } from '../core/types.js'; +import { withSandbox } from './sandbox.js'; + +/** Default `bash` timeout. */ +export const DEFAULT_BASH_TIMEOUT_MS = 120_000; +/** Largest `bash` timeout. */ +export const MAX_BASH_TIMEOUT_MS = 600_000; +/** Bytes kept of each of stdout and stderr. */ +export const DEFAULT_OUTPUT_CAP_BYTES = 1024 * 1024; +/** After the shell exits, how long to wait for the output pipes to close. */ +const DRAIN_MS = 200; + +/** Quotes a string for POSIX sh as one word. */ +export function shellQuote(s: string): string { + return `'${s.replace(/'/g, `'\\''`)}'`; +} + +let cachedShell: string | null | undefined; + +/** The bash to run commands with: `/bin/bash` or `bash` on PATH; Git Bash on Windows. Null when none. */ +export function findBash(): string | null { + if (cachedShell !== undefined) return cachedShell; + if (process.platform === 'win32') { + const candidates = [ + process.env['ProgramFiles'] && path.join(process.env['ProgramFiles'], 'Git', 'bin', 'bash.exe'), + process.env['ProgramFiles(x86)'] && path.join(process.env['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'), + process.env['LOCALAPPDATA'] && path.join(process.env['LOCALAPPDATA'], 'Programs', 'Git', 'bin', 'bash.exe'), + ].filter((p): p is string => typeof p === 'string' && p !== ''); + cachedShell = candidates.find((p) => existsSync(p)) ?? null; + return cachedShell; + } + if (existsSync('/bin/bash')) cachedShell = '/bin/bash'; + else { + const which = spawnSync('sh', ['-c', 'command -v bash'], { encoding: 'utf8' }); + const found = which.status === 0 ? which.stdout.trim() : ''; + cachedShell = found !== '' ? found : null; + } + return cachedShell; +} + +class Capture { + readonly #chunks: Buffer[] = []; + #size = 0; + truncated = false; + + constructor(private readonly cap: number) {} + + push(chunk: Buffer): void { + if (this.#size >= this.cap) { + this.truncated = true; + return; + } + const room = this.cap - this.#size; + const kept = chunk.length > room ? chunk.subarray(0, room) : chunk; + if (kept.length < chunk.length) this.truncated = true; + this.#chunks.push(kept); + this.#size += kept.length; + } + + text(): string { + // A cut in the middle of a multi-byte character becomes U+FFFD. + return Buffer.concat(this.#chunks).toString('utf8'); + } +} + +/** Kills the whole process group of `child` (POSIX) or its tree (Windows). */ +function killGroup(child: ChildProcess): void { + const pid = child.pid; + if (pid === undefined) return; + if (process.platform === 'win32') { + spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }); + return; + } + try { + process.kill(-pid, 'SIGKILL'); + } catch { + try { + child.kill('SIGKILL'); + } catch { + // Already gone. + } + } +} + +export interface BashRunOptions { + readonly outputCapBytes?: number; + /** Paths a sandboxed command may never write (from the host's protected paths). */ + readonly denyWrite?: readonly string[]; +} + +function spawnAndWait( + argv: readonly string[], + env: NodeJS.ProcessEnv, + cwd: string, + timeoutMs: number, + signal: AbortSignal, + cap: number, +): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new ToolError('cancelled', 'the run was stopped before bash started')); + return; + } + const [file, ...args] = argv; + if (file === undefined) { + reject(new ToolError('tool-error', 'empty command line')); + return; + } + const child = spawn(file, args, { + cwd, + env, + stdio: ['ignore', 'pipe', 'pipe'], + detached: process.platform !== 'win32', + windowsHide: true, + }); + const out = new Capture(cap); + const err = new Capture(cap); + child.stdout?.on('data', (c: Buffer) => out.push(c)); + child.stderr?.on('data', (c: Buffer) => err.push(c)); + + let timedOut = false; + let settled = false; + let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined; + let drainTimer: NodeJS.Timeout | undefined; + + const finish = (): void => { + if (settled || !exit) return; + settled = true; + clearTimeout(timer); + if (drainTimer) clearTimeout(drainTimer); + signal.removeEventListener('abort', onAbort); + // No process of the call outlives it: background children are killed too. + killGroup(child); + if (signal.aborted && !timedOut) { + reject(new ToolError('cancelled', 'bash was stopped because the run stopped')); + return; + } + resolve({ + exitCode: exit.code, + signal: exit.signal, + stdout: out.text(), + stderr: err.text(), + truncated: out.truncated || err.truncated, + timedOut, + }); + }; + const onAbort = (): void => killGroup(child); + const timer = setTimeout(() => { + timedOut = true; + killGroup(child); + }, timeoutMs); + signal.addEventListener('abort', onAbort, { once: true }); + + child.once('error', (e) => { + if (settled) return; + settled = true; + clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + reject(new ToolError('tool-error', `bash failed to start: ${e.message}`)); + }); + child.once('exit', (code, sig) => { + exit = { code, signal: sig }; + // Background children may keep the pipes open; do not wait for them long. + drainTimer = setTimeout(finish, DRAIN_MS); + }); + child.once('close', () => finish()); + }); +} + +/** Runs a prepared `bash` effect. */ +export async function runBash(effect: BashEffect, signal: AbortSignal, opts: BashRunOptions = {}): Promise { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + const shell = findBash(); + if (shell === null) { + throw new ToolError('tool-error', process.platform === 'win32' ? 'bash requires Git Bash, which was not found' : 'bash was not found'); + } + const cap = opts.outputCapBytes ?? DEFAULT_OUTPUT_CAP_BYTES; + const containment = effect.containment; + if (containment.mode === 'none') { + return spawnAndWait([shell, '-c', effect.command], process.env, effect.cwd, effect.timeoutMs, signal, cap); + } + return withSandbox(effect.command, shell, effect.cwd, containment, opts.denyWrite ?? [], (wrapped) => { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + return spawnAndWait(wrapped.argv, { ...process.env, ...wrapped.env }, effect.cwd, effect.timeoutMs, signal, cap); + }); +} diff --git a/src/tools/diff.test.ts b/src/tools/diff.test.ts new file mode 100644 index 0000000..f595a2f --- /dev/null +++ b/src/tools/diff.test.ts @@ -0,0 +1,62 @@ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { unifiedDiff } from './diff.js'; + +const hasGit = spawnSync('git', ['--version']).status === 0; + +/** Applies `diff` with `git apply` in a scratch repo and returns the result. */ +function gitApply(before: string | null, diff: string): string { + const dir = mkdtempSync(path.join(os.tmpdir(), 'acm-diff-')); + try { + if (before !== null) writeFileSync(path.join(dir, 'f.txt'), before); + writeFileSync(path.join(dir, 'p.diff'), diff); + const r = spawnSync('git', ['apply', '--unsafe-paths', '--whitespace=nowarn', 'p.diff'], { cwd: dir, encoding: 'utf8' }); + if (r.status !== 0) throw new Error(`git apply failed: ${r.stderr}\n${diff}`); + return readFileSync(path.join(dir, 'f.txt'), 'utf8'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function randomText(rand: () => number): string { + const lines: string[] = []; + const n = Math.floor(rand() * 30); + for (let i = 0; i < n; i++) lines.push(['a', 'b', 'c', 'd', '', 'x y'][Math.floor(rand() * 6)] ?? ''); + return lines.join('\n') + (rand() < 0.5 ? '\n' : ''); +} + +function mulberry(seed: number): () => number { + let t = seed; + return () => { + t = (t + 0x6d2b79f5) | 0; + let r = Math.imul(t ^ (t >>> 15), 1 | t); + r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r; + return ((r ^ (r >>> 14)) >>> 0) / 4294967296; + }; +} + +describe('unifiedDiff', () => { + it('produces a standard hunk with context', () => { + const diff = unifiedDiff('src/a.ts', 'one\ntwo\nthree\n', 'one\n2\nthree\n'); + expect(diff).toBe('--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1,3 +1,3 @@\n one\n-two\n+2\n three\n'); + }); + + it('marks creation and a missing final newline', () => { + expect(unifiedDiff('n.txt', null, 'hi')).toBe('--- /dev/null\n+++ b/n.txt\n@@ -0,0 +1,1 @@\n+hi\n\\ No newline at end of file\n'); + expect(unifiedDiff('n.txt', 'same\n', 'same\n')).toBe(''); + }); + + it.skipIf(!hasGit)('round-trips through git apply on random edits', () => { + const rand = mulberry(42); + for (let i = 0; i < 150; i++) { + const before = randomText(rand); + const after = randomText(rand); + if (before === after) continue; + const diff = unifiedDiff('f.txt', before, after); + expect(gitApply(before, diff)).toBe(after); + } + }); +}); diff --git a/src/tools/diff.ts b/src/tools/diff.ts new file mode 100644 index 0000000..9a8f419 --- /dev/null +++ b/src/tools/diff.ts @@ -0,0 +1,178 @@ +/** + * Unified diff of two texts (line based, Myers O(ND) with a bounded edit + * distance). When the texts differ by more than the bound, the changed middle + * is reported as one replace block, which is wider than the minimal diff but + * never wrong. + */ + +const CONTEXT = 3; +const MAX_EDIT_DISTANCE = 1000; + +interface Line { + readonly text: string; + /** False only for a last line without a trailing newline. */ + readonly eol: boolean; +} + +function splitLines(text: string): Line[] { + if (text === '') return []; + const parts = text.split('\n'); + const last = parts.pop() ?? ''; + const lines: Line[] = parts.map((t) => ({ text: t, eol: true })); + if (last !== '') lines.push({ text: last, eol: false }); + return lines; +} + +type Op = { readonly kind: ' ' | '-' | '+'; readonly line: Line }; + +function same(a: Line | undefined, b: Line | undefined): boolean { + return a !== undefined && b !== undefined && a.text === b.text && a.eol === b.eol; +} + +/** Edit script between a[lo..] and b[lo..] (already trimmed of common prefix/suffix). */ +function myers(a: readonly Line[], b: readonly Line[]): Op[] | null { + const n = a.length; + const m = b.length; + const max = Math.min(n + m, MAX_EDIT_DISTANCE); + const offset = max + 1; + const v = new Int32Array(2 * max + 3); + const trace: Int32Array[] = []; + for (let d = 0; d <= max; d++) { + trace.push(v.slice()); + for (let k = -d; k <= d; k += 2) { + let x: number; + if (k === -d || (k !== d && (v[offset + k - 1] ?? 0) < (v[offset + k + 1] ?? 0))) x = v[offset + k + 1] ?? 0; + else x = (v[offset + k - 1] ?? 0) + 1; + let y = x - k; + while (x < n && y < m && same(a[x], b[y])) { + x++; + y++; + } + v[offset + k] = x; + if (x >= n && y >= m) { + // Backtrack. + const ops: Op[] = []; + let cx = n; + let cy = m; + for (let dd = d; dd > 0; dd--) { + const pv = trace[dd] ?? v; + const kk = cx - cy; + let prevK: number; + if (kk === -dd || (kk !== dd && (pv[offset + kk - 1] ?? 0) < (pv[offset + kk + 1] ?? 0))) prevK = kk + 1; + else prevK = kk - 1; + const prevX = pv[offset + prevK] ?? 0; + const prevY = prevX - prevK; + while (cx > prevX && cy > prevY) { + cx--; + cy--; + ops.push({ kind: ' ', line: a[cx] as Line }); + } + if (cx === prevX) { + cy--; + ops.push({ kind: '+', line: b[cy] as Line }); + } else { + cx--; + ops.push({ kind: '-', line: a[cx] as Line }); + } + } + while (cx > 0 && cy > 0) { + cx--; + cy--; + ops.push({ kind: ' ', line: a[cx] as Line }); + } + return ops.reverse(); + } + } + } + return null; +} + +function editScript(a: readonly Line[], b: readonly Line[]): Op[] { + let start = 0; + while (start < a.length && start < b.length && same(a[start], b[start])) start++; + let endA = a.length; + let endB = b.length; + while (endA > start && endB > start && same(a[endA - 1], b[endB - 1])) { + endA--; + endB--; + } + const midA = a.slice(start, endA); + const midB = b.slice(start, endB); + const middle = myers(midA, midB) ?? [ + ...midA.map((line): Op => ({ kind: '-', line })), + ...midB.map((line): Op => ({ kind: '+', line })), + ]; + return [ + ...a.slice(0, start).map((line): Op => ({ kind: ' ', line })), + ...middle, + ...a.slice(endA).map((line): Op => ({ kind: ' ', line })), + ]; +} + +function renderLine(op: Op): string { + const out = `${op.kind}${op.line.text}\n`; + return op.line.eol ? out : `${out}\\ No newline at end of file\n`; +} + +/** + * Unified diff from `before` to `after`. `before === null` means the file did + * not exist. `file` is shown as `a/` and `b/`. Returns '' when + * nothing changed. + */ +export function unifiedDiff(file: string, before: string | null, after: string): string { + if (before !== null && before === after) return ''; + const a = before === null ? [] : splitLines(before); + const b = splitLines(after); + const ops = editScript(a, b); + const header = `--- ${before === null ? '/dev/null' : `a/${file}`}\n+++ b/${file}\n`; + if (ops.every((op) => op.kind === ' ')) { + // Only possible when before is null and after is empty. + return `${header}`; + } + + let out = header; + let i = 0; + // Line counters at the start of ops[i]. + const posA: number[] = []; + const posB: number[] = []; + let la = 0; + let lb = 0; + for (const op of ops) { + posA.push(la); + posB.push(lb); + if (op.kind !== '+') la++; + if (op.kind !== '-') lb++; + } + while (i < ops.length) { + while (i < ops.length && ops[i]?.kind === ' ') i++; + if (i >= ops.length) break; + const hunkStart = Math.max(0, i - CONTEXT); + let end = i; + // Extend while changes are within 2*CONTEXT of each other. + for (;;) { + while (end < ops.length && ops[end]?.kind !== ' ') end++; + let next = end; + while (next < ops.length && ops[next]?.kind === ' ') next++; + if (next < ops.length && next - end <= 2 * CONTEXT) { + end = next; + continue; + } + break; + } + const hunkEnd = Math.min(ops.length, end + CONTEXT); + const slice = ops.slice(hunkStart, hunkEnd); + const countA = slice.filter((op) => op.kind !== '+').length; + const countB = slice.filter((op) => op.kind !== '-').length; + const startA = countA === 0 ? (posA[hunkStart] ?? 0) : (posA[hunkStart] ?? 0) + 1; + const startB = countB === 0 ? (posB[hunkStart] ?? 0) : (posB[hunkStart] ?? 0) + 1; + out += `@@ -${startA},${countA} +${startB},${countB} @@\n`; + out += slice.map(renderLine).join(''); + i = hunkEnd; + } + return out; +} + +/** Diff header for a binary change. */ +export function binaryDiff(file: string, existed: boolean): string { + return `--- ${existed ? `a/${file}` : '/dev/null'}\n+++ b/${file}\nBinary files differ\n`; +} diff --git a/src/tools/edit-match.test.ts b/src/tools/edit-match.test.ts new file mode 100644 index 0000000..94bb9ed --- /dev/null +++ b/src/tools/edit-match.test.ts @@ -0,0 +1,113 @@ +// Test cases ported from Turnpack's test/edit-match.test.mjs +// (https://github.com/OnlyTerp/turnpack, Copyright 2026 OnlyTerp, Apache-2.0). +// Modified by the agent-code-mode authors: vitest, typed, and checks of the +// `matched` text this port adds. +import { describe, expect, it } from 'vitest'; +import { applySearchReplace, type EditApplied, type EditMiss, type EditOutcome } from './edit-match.js'; + +const apply = (text: string, search: string, replace: string, all = false): EditOutcome => applySearchReplace(text, search, replace, all); + +function ok(out: EditOutcome): EditApplied { + if (!out.ok) throw new Error(`expected a match: ${out.message}`); + return out; +} +function miss(out: EditOutcome): EditMiss { + if (out.ok) throw new Error(`expected no match, got ${out.how}`); + return out; +} + +describe('edit matching (ported from Turnpack)', () => { + it('uses the exact text when it is there, and says where an ambiguous one occurs', () => { + const text = 'a = 1\nb = 2\na = 1\n'; + const once = ok(apply(text, 'b = 2', 'b = 3')); + expect([once.how, once.count, once.text, once.matched]).toEqual(['exact', 1, 'a = 1\nb = 3\na = 1\n', 'b = 2']); + + const twice = miss(apply(text, 'a = 1', 'a = 9')); + expect(twice.kind).toBe('ambiguous'); + expect(twice.message).toMatch(/matches 2 places \(lines 1, 3\)/); + + const all = ok(apply(text, 'a = 1', 'a = 9', true)); + expect([all.count, all.text]).toEqual([2, 'a = 9\nb = 2\na = 9\n']); + + // The replacement is inserted as written: no "$&" or "$1" expansion. + expect(ok(apply('x = 1\n', 'x = 1', "x = '$&$1'")).text).toBe("x = '$&$1'\n"); + expect(miss(apply('x\n', '', 'y')).kind).toBe('empty'); + }); + + it("matches LF text against a CRLF file and keeps the file's line endings", () => { + const out = ok(apply('a\r\nb\r\nc\r\n', 'a\nb', 'x\ny')); + expect([out.how, out.text, out.matched]).toEqual(['line-endings', 'x\r\ny\r\nc\r\n', 'a\r\nb']); + }); + + it('finds a block whose indentation was remembered wrongly, and re-indents what replaces it', () => { + const file = 'function f() {\n if (x) {\n return 1;\n }\n}\n'; + const out = ok(apply(file, 'if (x) {\n return 1;\n}', 'if (x) {\n log();\n return 2;\n}')); + expect(out.how).toBe('indentation'); + expect(out.text).toBe('function f() {\n if (x) {\n log();\n return 2;\n }\n}\n'); + expect(out.matched).toBe(' if (x) {\n return 1;\n }'); + + // Spaces remembered where the file has tabs: converted level by level. + const tabbed = 'class A {\n\trun() {\n\t\treturn 1;\n\t}\n}\n'; + const tabs = ok(apply(tabbed, ' run() {\n return 1;\n }', ' run() {\n if (ok) {\n return 2;\n }\n }')); + expect(tabs.how).toBe('indentation'); + expect(tabs.text).toBe('class A {\n\trun() {\n\t\tif (ok) {\n\t\t\treturn 2;\n\t\t}\n\t}\n}\n'); + + // And the other way round, in a CRLF file, with the trailing newline included in the search. + const crlf = ' a();\r\n b();\r\nend\r\n'; + const mixed = ok(apply(crlf, '\ta();\n\tb();\n', '\ta();\n\tc();\n')); + expect(mixed.text).toBe(' a();\r\n c();\r\nend\r\n'); + }); + + it('ignores line numbers copied from a listing, trailing spaces, and typographic quotes', () => { + const file = 'export const TAX = 0.08;\n\nexport function tax(n) {\n return n * TAX;\n}\n'; + const listing = ok( + apply(file, '3 | export function tax(n) {\n4 | return n * TAX;\n5 | }', '3 | export function tax(n) {\n4 | return round(n * TAX);\n5 | }'), + ); + expect(listing.how).toBe('line-numbers'); + expect(listing.text).toBe('export const TAX = 0.08;\n\nexport function tax(n) {\n return round(n * TAX);\n}\n'); + + // A file that really does contain "12 | x" is matched exactly, not stripped. + expect(ok(apply('12 | x\n', '12 | x', '13 | y')).how).toBe('exact'); + + const spaced = ok(apply('foo(); \nbar();\n', 'foo();\nbar();', 'baz();')); + expect([spaced.how, spaced.text, spaced.matched]).toEqual(['trailing-whitespace', 'baz();\n', 'foo(); \nbar();']); + + const quoted = ok(apply(' const s = “hello”; // it’s\n', 'const s = "hello"; // it\'s', 'const s = "bye";')); + expect([quoted.how, quoted.text, quoted.matched]).toEqual(['punctuation', ' const s = "bye";\n', ' const s = “hello”; // it’s']); + }); + + it('never picks between two places that only match loosely', () => { + const file = 'if (a) {\n go();\n}\nif (b) {\n go();\n}\n'; + const out = miss(apply(file, ' go();', ' stop();')); + expect(out.kind).toBe('ambiguous'); + expect(out.message).toMatch(/matches 2 places \(lines 2, 5\) when indentation is ignored/); + + const all = ok(apply(file, ' go();', ' stop();', true)); + expect(all.text).toBe('if (a) {\n stop();\n}\nif (b) {\n stop();\n}\n'); + + // Blank lines alone are not a place. + expect(miss(apply('a\n\n\nb\n', ' \n ', 'x')).kind).toBe('not-found'); + }); + + it('shows the nearest text and the first difference when nothing matches', () => { + const file = [ + "import { TAX } from './rates.js';", + '', + 'export function invoiceTotal(subtotal) {', + ' const tax = Number((subtotal * TAX).toFixed(2));', + ' return subtotal + tax;', + '}', + '', + ].join('\n'); + const out = miss(apply(file, 'export function invoiceTotal(subtotal) {\n const tax = subtotal * TAX;\n return subtotal + tax;\n}', 'x')); + expect(out.kind).toBe('not-found'); + expect(out.message).toMatch(/closest text is lines 3-6 \(3 of 4 line\(s\) identical/); + expect(out.message).toMatch(/ 4 \| {3}const tax = Number\(\(subtotal \* TAX\)\.toFixed\(2\)\);/); + expect(out.message).toMatch(/First difference, at line 4:/); + expect(out.message).toMatch(/search has: " {2}const tax = subtotal \* TAX;"/); + expect(out.message).toMatch(/file has: {3}" {2}const tax = Number/); + + const nowhere = miss(apply(file, 'class Zebra extends Animal {}', 'x')); + expect(nowhere.message).toMatch(/nothing close to it is in the file \(7 lines\)/); + }); +}); diff --git a/src/tools/edit-match.ts b/src/tools/edit-match.ts new file mode 100644 index 0000000..cdad6c2 --- /dev/null +++ b/src/tools/edit-match.ts @@ -0,0 +1,495 @@ +/* + * Copyright 2026 OnlyTerp (https://github.com/OnlyTerp) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Ported from Turnpack's src/tools/edit-match.ts + * (https://github.com/OnlyTerp/turnpack, commit b14330d). + * Modified by the agent-code-mode authors: the result also carries the exact + * text that was matched (`matched`), messages name this project's argument + * names, and the patch-hunk helpers that this project does not use were removed. + */ + +/** + * Search/replace matching for `edit`. + * + * A model writes an edit from its memory of a file, and that memory is often right about the + * code and wrong about the bytes: an indent one level off, tabs remembered as spaces, a + * trailing space dropped, the line numbers a listing printed copied along with the code, a curly + * quote typed straight. Refusing each of those costs a full extra turn (re-read, re-send) for a + * difference nobody meant. + * + * So matching is a ladder. The exact text is tried first and wins whenever it is there. Only if + * it is absent are looser comparisons tried, one at a time, each comparing whole lines: + * + * exact → line endings → copied line numbers → trailing whitespace → indentation → punctuation + * + * A looser rung is used only when it identifies the place unambiguously (or `replaceAll` is + * set), and the caller is told which rung matched so the reply can say so. Nothing here guesses + * between two candidate places. + * + * When no rung matches, `describeNearest` finds the most similar region and shows it with line + * numbers and the first differing line, so the next attempt can be written without re-reading. + */ + +export type MatchHow = + | "exact" + | "line-endings" + | "line-numbers" + | "trailing-whitespace" + | "indentation" + | "punctuation"; + +export interface EditApplied { + ok: true; + text: string; + how: MatchHow; + count: number; + /** The exact text of the file that the first match covers (what is replaced). */ + matched: string; +} + +export interface EditMiss { + ok: false; + kind: "empty" | "not-found" | "ambiguous"; + /** Complete, model-readable explanation, without the file name. */ + message: string; +} + +export type EditOutcome = EditApplied | EditMiss; + +/** What a looser match ignored, in the words used in replies. */ +export const HOW_LABEL: Record = { + exact: "exact", + "line-endings": "line endings", + "line-numbers": "line numbers copied from a listing", + "trailing-whitespace": "trailing whitespace", + indentation: "indentation", + punctuation: "indentation and typographic quotes or dashes", +}; + +interface FileLine { + /** Offset of the first character of the line. */ + start: number; + /** Offset just past the last character before the line ending. */ + bodyEnd: number; + /** Offset just past the line ending (equal to bodyEnd on a last line with none). */ + end: number; + body: string; +} + +function splitLines(text: string): FileLine[] { + const lines: FileLine[] = []; + let pos = 0; + for (;;) { + const nl = text.indexOf("\n", pos); + if (nl === -1) { + lines.push({ start: pos, bodyEnd: text.length, end: text.length, body: text.slice(pos) }); + return lines; + } + const bodyEnd = nl > pos && text[nl - 1] === "\r" ? nl - 1 : nl; + lines.push({ start: pos, bodyEnd, end: nl + 1, body: text.slice(pos, bodyEnd) }); + pos = nl + 1; + } +} + +function lineNumberAt(lines: FileLine[], offset: number): number { + let lo = 0; + let hi = lines.length - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if ((lines[mid]?.start ?? 0) <= offset) lo = mid; + else hi = mid - 1; + } + return lo + 1; +} + +function occurrences(haystack: string, needle: string): number[] { + const found: number[] = []; + if (!needle) return found; + let from = 0; + for (;;) { + const at = haystack.indexOf(needle, from); + if (at === -1) return found; + found.push(at); + from = at + needle.length; + } +} + +function listLines(numbers: number[]): string { + const shown = numbers.slice(0, 8).join(", "); + return numbers.length > 8 ? `${shown}, and ${numbers.length - 8} more` : shown; +} + +function ambiguous(lineNumbers: number[], ignoring?: string): EditMiss { + return { + ok: false, + kind: "ambiguous", + message: + `search text matches ${lineNumbers.length} places (lines ${listLines(lineNumbers)})` + + `${ignoring ? ` when ${ignoring} is ignored` : ""}. ` + + "Add a neighbouring line to oldString so it names one place, or pass replaceAll: true.", + }; +} + +// " 12 | code" is how Turnpack's pack prints a line; " 12\tcode" is `cat -n`; "12→code" is another +// common listing style. A search made only of such lines was copied from a listing. +const GUTTER = /^[>\s]*\d+(?: \|(?: |$)|\t|→)/; + +function stripGutter(lines: string[]): string[] | null { + const meaningful = lines.filter((line) => line.trim() !== ""); + if (meaningful.length === 0 || !meaningful.every((line) => GUTTER.test(line))) return null; + return lines.map((line) => line.replace(GUTTER, "")); +} + +const PUNCTUATION: Array<[RegExp, string]> = [ + [/[‘’‚‛′]/g, "'"], + [/[“”„‟″]/g, '"'], + [/[‐‑‒–—―−]/g, "-"], + [/[             ]/g, " "], + [/…/g, "..."], +]; + +function foldPunctuation(value: string): string { + let out = value; + for (const [pattern, plain] of PUNCTUATION) out = out.replace(pattern, plain); + return out; +} + +function leadingWhitespace(value: string): string { + return /^[ \t]*/.exec(value)?.[0] ?? ""; +} + +/** + * Rewrites the indentation of replacement lines from the way the model wrote the block to the + * way the file has it. + * + * The matched lines are the evidence: line k of the search was written with one indent and the + * file has another, which gives a small dictionary from "the model's indent" to "the file's + * indent" (no indent → one tab, four spaces → two tabs). A replacement line whose indent is in + * the dictionary is translated outright. One that is deeper than anything matched is + * extrapolated from the step between two matched depths, and failing that keeps its extra + * indentation on top of the nearest known depth. + */ +function reindentLike(replaceLines: string[], searchLines: string[], fileLines: string[]): string[] { + const known = new Map(); + for (let k = 0; k < searchLines.length; k++) { + const searchLine = searchLines[k] ?? ""; + const fileLine = fileLines[k] ?? ""; + if (searchLine.trim() === "" || fileLine.trim() === "") continue; + const indent = leadingWhitespace(searchLine); + if (!known.has(indent)) known.set(indent, leadingWhitespace(fileLine)); + } + if (known.size === 0 || [...known].every(([from, to]) => from === to)) return replaceLines; + + // One level of nesting, as the model writes it and as the file writes it. + const depths = [...known.keys()].sort((a, b) => a.length - b.length); + let step: { from: number; to: string } | null = null; + for (let i = 1; i < depths.length && !step; i++) { + const shallow = depths[i - 1] ?? ""; + const deep = depths[i] ?? ""; + const fileShallow = known.get(shallow) ?? ""; + const fileDeep = known.get(deep) ?? ""; + if (deep.startsWith(shallow) && fileDeep.startsWith(fileShallow) && fileDeep.length > fileShallow.length) { + step = { from: deep.length - shallow.length, to: fileDeep.slice(fileShallow.length) }; + } + } + // With one matched depth and a file that indents with tabs, a level is taken to be the + // smallest extra indent the replacement itself uses. + const extras = replaceLines + .filter((line) => line.trim() !== "") + .map((line) => leadingWhitespace(line)) + .map((indent) => { + const base = depths.filter((depth) => indent.startsWith(depth)).pop(); + return base === undefined ? 0 : indent.length - base.length; + }) + .filter((extra) => extra > 0); + const smallestExtra = extras.length > 0 ? Math.min(...extras) : 0; + + return replaceLines.map((line) => { + if (line.trim() === "") return line; + const indent = leadingWhitespace(line); + const rest = line.slice(indent.length); + const direct = known.get(indent); + if (direct !== undefined) return direct + rest; + + const base = depths.filter((depth) => indent.startsWith(depth)).pop(); + if (base === undefined) return line; // shallower than anything matched: leave it as written + const fileBase = known.get(base) ?? ""; + const extra = indent.slice(base.length); + if (step && extra.length % step.from === 0) { + return fileBase + step.to.repeat(extra.length / step.from) + rest; + } + if (/^\t+$/.test(fileBase) && /^ +$/.test(extra) && smallestExtra > 0 && extra.length % smallestExtra === 0) { + return fileBase + "\t".repeat(extra.length / smallestExtra) + rest; + } + return fileBase + extra + rest; + }); +} + +interface Rung { + how: MatchHow; + normalize: (line: string) => string; + /** Whether the replacement needs its indentation moved to where the file has it. */ + reindent: boolean; +} + +const RUNGS: Rung[] = [ + { how: "trailing-whitespace", normalize: (line) => line.replace(/[ \t]+$/, ""), reindent: false }, + { how: "indentation", normalize: (line) => line.trim(), reindent: true }, + { how: "punctuation", normalize: (line) => foldPunctuation(line).trim(), reindent: true }, +]; + +function findLineMatches(fileNorm: string[], wanted: string[]): number[] { + const hits: number[] = []; + const n = wanted.length; + const first = wanted[0]; + for (let i = 0; i + n <= fileNorm.length; i++) { + if (fileNorm[i] !== first) continue; + let same = true; + for (let k = 1; k < n; k++) { + if (fileNorm[i + k] !== wanted[k]) { + same = false; + break; + } + } + if (same) { + hits.push(i); + i += n - 1; // matches may not overlap + } + } + return hits; +} + +/** + * Applies one search/replace to `text`. See the file comment for the order of attempts. + */ +export function applySearchReplace( + text: string, + search: string, + replace: string, + replaceAll: boolean, +): EditOutcome { + if (!search) { + return { ok: false, kind: "empty", message: "the search text is empty" }; + } + + // Rung 1: the text exactly as written. + let exact = occurrences(text, search); + let how: MatchHow = "exact"; + let exactSearch = search; + let exactReplace = replace; + + // Rung 2: the same text with the file's line endings. + const fileUsesCrlf = text.includes("\r\n"); + const eol = fileUsesCrlf ? "\r\n" : "\n"; + const toFileEol = (value: string): string => { + const lf = value.replace(/\r\n/g, "\n"); + return fileUsesCrlf ? lf.replace(/\n/g, "\r\n") : lf; + }; + if (exact.length === 0 && /\n/.test(search)) { + const alt = toFileEol(search); + if (alt !== search) { + const altHits = occurrences(text, alt); + if (altHits.length > 0) { + exact = altHits; + exactSearch = alt; + exactReplace = toFileEol(replace); + how = "line-endings"; + } + } + } + + let fileLines: FileLine[] | undefined; + const linesOfFile = (): FileLine[] => (fileLines ??= splitLines(text)); + + if (exact.length > 1 && !replaceAll) { + return ambiguous(exact.map((offset) => lineNumberAt(linesOfFile(), offset))); + } + if (exact.length > 0) { + return { ok: true, text: text.split(exactSearch).join(exactReplace), how, count: exact.length, matched: exactSearch }; + } + + // From here on the comparison is line by line. + let searchLines = search.replace(/\r\n/g, "\n").split("\n"); + let replaceLines = replace.replace(/\r\n/g, "\n").split("\n"); + + // A search that ends in a newline covers its last line's ending too. + const coversLastEnding = searchLines.length > 1 && searchLines[searchLines.length - 1] === ""; + if (coversLastEnding) searchLines = searchLines.slice(0, -1); + + let gutterStripped = false; + const withoutGutter = stripGutter(searchLines); + if (withoutGutter) { + searchLines = withoutGutter; + replaceLines = replaceLines.map((line) => line.replace(GUTTER, "")); + gutterStripped = true; + } + + const file = linesOfFile(); + const bodies = file.map((line) => line.body); + + const rungs: Rung[] = gutterStripped + ? [{ how: "line-numbers", normalize: (line) => line, reindent: false }, ...RUNGS] + : RUNGS; + + for (const rung of rungs) { + const wanted = searchLines.map(rung.normalize); + // A search that normalises to nothing would match every blank line. + if (wanted.every((line) => line === "")) continue; + const hits = findLineMatches(bodies.map(rung.normalize), wanted); + if (hits.length === 0) continue; + const label = rung.how; + if (hits.length > 1 && !replaceAll) { + return ambiguous( + hits.map((index) => index + 1), + HOW_LABEL[label], + ); + } + + const pieces: string[] = []; + let cursor = 0; + let matched: string | undefined; + for (const index of hits) { + const firstLine = file[index]; + const lastLine = file[index + searchLines.length - 1]; + if (!firstLine || !lastLine) continue; + const lines = rung.reindent + ? reindentLike(replaceLines, searchLines, bodies.slice(index, index + searchLines.length)) + : replaceLines; + pieces.push(text.slice(cursor, firstLine.start), lines.join(eol)); + cursor = coversLastEnding ? lastLine.end : lastLine.bodyEnd; + matched ??= text.slice(firstLine.start, cursor); + } + pieces.push(text.slice(cursor)); + return { ok: true, text: pieces.join(""), how: label, count: hits.length, matched: matched ?? "" }; + } + + return { ok: false, kind: "not-found", message: describeNearest(text, searchLines) }; +} + +function tokensOf(line: string): string[] { + return line.match(/[A-Za-z_$][\w$]*|\d+|[^\s\w]/g) ?? []; +} + +/** Token overlap between two lines, 0 to 1. Order-blind, which is fine for "is this the place". */ +function similarity(a: string, b: string): number { + if (a === b) return 1; + const ta = tokensOf(a); + const tb = tokensOf(b); + if (ta.length === 0 || tb.length === 0) return 0; + const counts = new Map(); + for (const token of ta) counts.set(token, (counts.get(token) ?? 0) + 1); + let common = 0; + for (const token of tb) { + const left = counts.get(token); + if (left) { + common += 1; + counts.set(token, left - 1); + } + } + return (2 * common) / (ta.length + tb.length); +} + +const MAX_SCAN_LINES = 60000; +const MAX_SNIPPET_LINES = 12; + +function quoteLine(line: string): string { + const shown = line.length > 160 ? `${line.slice(0, 160)}…` : line; + return JSON.stringify(shown); +} + +/** + * Explains a search that matched nowhere: the most similar region of the file with line + * numbers, how much of it agrees, and the first line that does not. + */ +export function describeNearest(text: string, searchLinesRaw: string[]): string { + const file = splitLines(text); + const total = file.length; + const wanted = searchLinesRaw.map((line) => line.trim()); + const fileTrim = file.slice(0, MAX_SCAN_LINES).map((line) => line.body.trim()); + const nothing = `search text not found, and nothing close to it is in the file (${total} lines). Read the file and write oldString from what is there.`; + + // Find candidate positions through the search's most distinctive line: its longest. + let probe = 0; + for (let k = 1; k < wanted.length; k++) { + if ((wanted[k]?.length ?? 0) > (wanted[probe]?.length ?? 0)) probe = k; + } + const probeLine = wanted[probe] ?? ""; + if (!probeLine) return nothing; + + const candidates: Array<{ start: number; score: number }> = []; + for (let j = 0; j < fileTrim.length; j++) { + const score = similarity(fileTrim[j] ?? "", probeLine); + if (score >= 0.5) candidates.push({ start: j - probe, score }); + } + candidates.sort((a, b) => b.score - a.score); + + let best: { start: number; score: number; identical: number } | null = null; + for (const candidate of candidates.slice(0, 12)) { + let sum = 0; + let identical = 0; + for (let k = 0; k < wanted.length; k++) { + const fileLine = fileTrim[candidate.start + k]; + if (fileLine === undefined) continue; + const score = similarity(fileLine, wanted[k] ?? ""); + sum += score; + if (fileLine === wanted[k]) identical += 1; + } + const mean = sum / wanted.length; + if (!best || mean > best.score) best = { start: candidate.start, score: mean, identical }; + } + if (!best || best.score < 0.35) return nothing; + + const from = Math.max(0, best.start); + const to = Math.min(total, best.start + wanted.length); // exclusive + let firstDiff = -1; + for (let k = 0; k < wanted.length; k++) { + if (fileTrim[best.start + k] !== wanted[k]) { + firstDiff = k; + break; + } + } + + // Show the whole region when it is short, otherwise the part around the first difference. + let showFrom = from; + let showTo = to; + if (to - from > MAX_SNIPPET_LINES) { + const centre = best.start + Math.max(0, firstDiff); + showFrom = Math.max(from, centre - 3); + showTo = Math.min(to, showFrom + MAX_SNIPPET_LINES); + } + const width = String(showTo).length; + const snippet: string[] = []; + for (let i = showFrom; i < showTo; i++) { + const body = file[i]?.body ?? ""; + snippet.push(` ${String(i + 1).padStart(width, " ")} | ${body.length > 200 ? `${body.slice(0, 200)}…` : body}`); + } + + const out = [ + `search text not found. The closest text is lines ${from + 1}-${to} (${best.identical} of ${wanted.length} line(s) identical apart from indentation):`, + ...snippet, + ]; + if (showTo < to || showFrom > from) out.push(` (showing lines ${showFrom + 1}-${showTo})`); + if (firstDiff !== -1) { + const fileLine = file[best.start + firstDiff]; + out.push( + fileLine + ? `First difference, at line ${best.start + firstDiff + 1}:` + : "First difference: the search runs past the end of the file:", + ` search has: ${quoteLine(searchLinesRaw[firstDiff] ?? "")}`, + ` file has: ${fileLine ? quoteLine(fileLine.body) : "(no such line)"}`, + ); + } + return out.join("\n"); +} diff --git a/src/tools/fs-ops.ts b/src/tools/fs-ops.ts new file mode 100644 index 0000000..da3be27 --- /dev/null +++ b/src/tools/fs-ops.ts @@ -0,0 +1,249 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { constants as FS, type Stats } from 'node:fs'; +import fs, { type FileHandle } from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; + +/** + * File operations that do not let a symlink or a race widen what was + * prepared. Every open of a final component uses `O_NOFOLLOW` where the + * platform has it; the opened file is then checked to be the one at the path + * (Linux: `/proc/self/fd`; elsewhere: `fstat` vs `lstat` identity). + */ + +const NOFOLLOW = FS.O_NOFOLLOW ?? 0; +const IS_LINUX = process.platform === 'linux'; +const IS_WINDOWS = process.platform === 'win32'; + +export function sha256(data: Buffer | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +export function errnoCode(err: unknown): string | undefined { + if (err !== null && typeof err === 'object' && 'code' in err && typeof err.code === 'string') return err.code; + return undefined; +} + +function sameFile(a: Stats, b: Stats): boolean { + return a.ino === b.ino && a.dev === b.dev; +} + +/** Throws `stale` unless the real path of `dir` is still exactly `dir`. */ +export async function assertDirUnchanged(dir: string): Promise { + let real: string; + try { + real = await fs.realpath(dir); + } catch (err) { + throw new ToolError('stale', `${dir} changed since prepared (${errnoCode(err) ?? 'unresolvable'})`); + } + const same = IS_WINDOWS ? real.toLowerCase() === dir.toLowerCase() : real === dir; + if (!same) throw new ToolError('stale', `file changed since prepared: ${dir} now resolves to ${real}`); +} + +/** Verifies an open handle is the file at `abs` and not something reached through a link. */ +async function assertHandleAt(handle: FileHandle, abs: string): Promise { + const st = await handle.stat(); + if (IS_LINUX) { + let actual: string | undefined; + try { + actual = await fs.readlink(`/proc/self/fd/${handle.fd}`); + } catch { + actual = undefined; + } + if (actual !== undefined && actual !== abs) { + throw new ToolError('stale', `file changed since prepared: ${abs} opened as ${actual}`); + } + } + const lst = await fs.lstat(abs).catch(() => null); + if (!lst || lst.isSymbolicLink() || !sameFile(st, lst)) { + throw new ToolError('stale', `file changed since prepared: ${abs} was replaced while it was opened`); + } + return st; +} + +export interface RegularFile { + readonly bytes: Buffer; + readonly mode: number; +} + +/** + * Reads a regular file without following a link at its final component. + * Returns null when it does not exist. `maxBytes` bounds the read. + */ +export async function readRegularFile(abs: string, maxBytes = Number.MAX_SAFE_INTEGER): Promise { + let handle: FileHandle; + try { + handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW); + } catch (err) { + const code = errnoCode(err); + if (code === 'ENOENT') return null; + if (code === 'ELOOP' || code === 'EMLINK') throw new ToolError('stale', `${abs} is a symbolic link`); + if (code === 'EISDIR') throw new ToolError('invalid-args', `${abs} is a directory`); + throw new ToolError('tool-error', `cannot open ${abs}: ${code ?? String(err)}`); + } + try { + const st = await assertHandleAt(handle, abs); + if (st.isDirectory()) throw new ToolError('invalid-args', `${abs} is a directory`); + if (!st.isFile()) throw new ToolError('invalid-args', `${abs} is not a regular file`); + if (st.size > maxBytes) throw new ToolError('tool-error', `${abs} is ${st.size} bytes, more than the ${maxBytes}-byte limit`); + const bytes = await handle.readFile(); + return { bytes, mode: st.mode & 0o7777 }; + } finally { + await handle.close(); + } +} + +/** What a commit expects to find at the path before it writes. */ +export type Expectation = { readonly kind: 'absent' } | { readonly kind: 'hash'; readonly sha256: string }; + +export interface WriteOutcome { + /** Bytes that were there before (null when absent). */ + readonly before: RegularFile | null; + /** Directories created to hold the file, outermost first. */ + readonly createdDirs: readonly string[]; +} + +async function missingDirs(dir: string): Promise { + const missing: string[] = []; + let cursor = dir; + for (;;) { + const st = await fs.lstat(cursor).catch(() => null); + if (st) { + if (st.isSymbolicLink() || !st.isDirectory()) { + throw new ToolError('stale', `file changed since prepared: ${cursor} is not a directory`); + } + break; + } + missing.push(cursor); + const parent = path.dirname(cursor); + if (parent === cursor) break; + cursor = parent; + } + return missing.reverse(); +} + +/** + * Atomically replaces (or creates) `abs` with `bytes`: + * 1. the parent directory must still resolve to itself (no symlink swapped in); + * 2. the current content must match `expect` (else `ToolError('stale')`, no write); + * 3. the bytes go to a temp file in the same directory (fsync), keep the old mode, + * and are renamed over the target; a create uses `link` so it never replaces + * a file that appeared meanwhile. + * `beforeWrite` runs after the checks and before anything is written (the + * transaction journal snapshots the original there). + */ +export async function atomicWrite( + abs: string, + bytes: Buffer, + expect: Expectation, + beforeWrite?: (before: RegularFile | null, createdDirs: readonly string[]) => Promise, +): Promise { + const dir = path.dirname(abs); + const toCreate = await missingDirs(dir); + const existingAncestor = toCreate.length > 0 ? path.dirname(toCreate[0] ?? dir) : dir; + await assertDirUnchanged(existingAncestor); + + const before = await readRegularFile(abs); + if (expect.kind === 'absent' && before !== null) { + throw new ToolError('stale', `file changed since prepared: ${abs} was created after the call was prepared`); + } + if (expect.kind === 'hash') { + if (before === null) throw new ToolError('stale', `file changed since prepared: ${abs} no longer exists`); + if (sha256(before.bytes) !== expect.sha256) throw new ToolError('stale', `file changed since prepared: ${abs}`); + } + + await beforeWrite?.(before, toCreate); + + for (const d of toCreate) { + try { + await fs.mkdir(d); + } catch (err) { + if (errnoCode(err) !== 'EEXIST') throw err; + } + await assertDirUnchanged(d); + } + await assertDirUnchanged(dir); + + const tmp = path.join(dir, `.${path.basename(abs)}.acm-${randomBytes(6).toString('hex')}.tmp`); + const mode = before?.mode ?? 0o666; + const handle = await fs.open(tmp, FS.O_WRONLY | FS.O_CREAT | FS.O_EXCL | NOFOLLOW, mode); + let placed = false; + try { + try { + await handle.writeFile(bytes); + if (before && !IS_WINDOWS) await handle.chmod(before.mode); + await handle.sync(); + } finally { + await handle.close(); + } + await assertDirUnchanged(dir); + if (expect.kind === 'absent') { + try { + await fs.link(tmp, abs); + placed = true; + } catch (err) { + const code = errnoCode(err); + if (code === 'EEXIST') throw new ToolError('stale', `file changed since prepared: ${abs} was created meanwhile`); + // File systems without hard links: fall back to rename. + if (code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV') throw err; + } + } + if (!placed) await fs.rename(tmp, abs); + return { before, createdDirs: toCreate }; + } finally { + // After `link` the temp name is still there; after `rename` it is gone. + await fs.rm(tmp, { force: true }).catch(() => undefined); + } +} + +/** Removes `abs` if it is a regular file (never follows a link). */ +export async function removeRegularFile(abs: string): Promise { + const st = await fs.lstat(abs).catch(() => null); + if (!st) return; + if (!st.isFile()) throw new ToolError('stale', `${abs} is no longer a regular file`); + await fs.unlink(abs); +} + +/** fsyncs a directory where the platform allows it. */ +export async function syncDir(dir: string): Promise { + if (IS_WINDOWS) return; + try { + const handle = await fs.open(dir, FS.O_RDONLY); + try { + await handle.sync(); + } finally { + await handle.close(); + } + } catch { + // Not every file system lets a directory be flushed. + } +} + +/** Writes and fsyncs a private file (journal records). */ +export async function writeDurable(file: string, data: Buffer | string): Promise { + const handle = await fs.open(file, FS.O_WRONLY | FS.O_CREAT | FS.O_TRUNC, 0o600); + try { + await handle.writeFile(data); + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Whether a buffer looks like binary data: a NUL byte in the first 8 KiB, or invalid UTF-8. */ +export function isBinary(bytes: Buffer): boolean { + const head = bytes.subarray(0, 8192); + if (head.includes(0)) return true; + try { + new TextDecoder('utf-8', { fatal: true }).decode(bytes); + return false; + } catch { + return true; + } +} + +/** Decodes UTF-8 text, throwing `ToolError('tool-error', 'binary file')` for binary data. */ +export function decodeText(abs: string, bytes: Buffer): string { + if (isBinary(bytes)) throw new ToolError('tool-error', `binary file: ${abs}`); + return bytes.toString('utf8'); +} diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 0000000..925fd0c --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,5 @@ +export { NodeToolRuntime, DEFAULT_READ_LIMIT, READ_CAP_BYTES, MAX_FILE_BYTES, type NodeToolRuntimeOptions } from './runtime.js'; +export { FileTransaction, MAX_JOURNAL_BYTES, recoverStaleJournals, journalRoot, type RecoveredJournal } from './journal.js'; +export { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, DEFAULT_OUTPUT_CAP_BYTES } from './bash.js'; +export { DEFAULT_GREP_MAX_RESULTS, DEFAULT_GLOB_MAX_RESULTS } from './search.js'; +export { containmentUnavailableReason } from './sandbox.js'; diff --git a/src/tools/integration.test.ts b/src/tools/integration.test.ts new file mode 100644 index 0000000..971200f --- /dev/null +++ b/src/tools/integration.test.ts @@ -0,0 +1,62 @@ +import { existsSync, mkdirSync, readdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { runScript } from '../core/run.js'; +import { FakeSandbox, StaticHostAdapter, makeContext } from '../testing/index.js'; +import { NodeToolRuntime } from './runtime.js'; + +/** The real tool runtime behind the P0 dispatcher and run pipeline. */ +let base: string; +let ws: string; + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-int-'))); + ws = path.join(base, 'ws'); + mkdirSync(ws); + writeFileSync(path.join(ws, 'a.txt'), 'alpha\n'); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +function deps(adapter = new StaticHostAdapter({ protectedPaths: [] })) { + return { sandbox: new FakeSandbox(), adapter, tools: new NodeToolRuntime({ stateDir: path.join(base, 'state') }), ctx: makeContext(ws) }; +} + +describe('NodeToolRuntime in the run pipeline', () => { + it('commits writes and edits and reports the diff', async () => { + const code = JSON.stringify([ + { tool: 'edit', args: { path: 'a.txt', oldString: 'alpha', newString: 'beta' } }, + { tool: 'write', args: { path: 'b/c.txt', content: 'new\n' } }, + { tool: 'read', args: { path: 'b/c.txt' } }, + ]); + const result = await runScript({ code, transaction: false, timeoutMs: 10_000 }, deps()); + expect(result.ok).toBe(true); + expect(result.changedFiles).toEqual(['a.txt', path.join('b', 'c.txt')]); + expect(result.diff).toContain('-alpha\n+beta\n'); + expect(result.diff).toContain('--- /dev/null\n+++ b/b/c.txt\n'); + expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('beta\n'); + }); + + it('rolls a transactional run back when a call is denied', async () => { + const adapter = new StaticHostAdapter({ + protectedPaths: [], + rules: [(p) => (p.tool === 'write' && p.effect.absPath.endsWith('denied.txt') ? { kind: 'deny', reason: 'no' } : undefined)], + }); + const code = JSON.stringify([ + { tool: 'write', args: { path: 'a.txt', content: 'changed\n' } }, + { tool: 'write', args: { path: 'fresh/new.txt', content: 'x' } }, + { tool: 'write', args: { path: 'denied.txt', content: 'x' } }, + ]); + const result = await runScript({ code, transaction: true, timeoutMs: 10_000 }, deps(adapter)); + expect(result.ok).toBe(false); + expect(result.rolledBack?.skipped).toEqual([]); + expect(result.rolledBack?.restored.length).toBe(2); + expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('alpha\n'); + expect(existsSync(path.join(ws, 'fresh'))).toBe(false); + // The journal is released once the run is over. + expect(readdirSync(path.join(base, 'state', 'journal'))).toEqual([]); + }); +}); diff --git a/src/tools/jail.ts b/src/tools/jail.ts new file mode 100644 index 0000000..28784b3 --- /dev/null +++ b/src/tools/jail.ts @@ -0,0 +1,224 @@ +/* + * `realpathWithSuffix`, `isInsideDir` and `windowsPathProblem` are adapted + * from Turnpack's src/security.ts (https://github.com/OnlyTerp/turnpack, + * Copyright 2026 OnlyTerp, licensed under the Apache License, Version 2.0: + * http://www.apache.org/licenses/LICENSE-2.0). + * Modified by the agent-code-mode authors: asynchronous, multiple roots, + * errors as ToolError, UNC and device prefixes refused. + */ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import { DEFAULT_CASE_INSENSITIVE, findMatchingPattern } from '../core/paths.js'; + +/** + * Workspace jail: every path a tool touches is resolved to an absolute real + * path and must live under one of the allowed roots. + * + * Resolution follows Turnpack's `realpathWithSuffix`: the deepest part of the + * path that exists is found with `lstat` (not `exists`, which follows links + * and would call a dangling symlink "missing"), resolved with `realpath`, and + * the missing rest is joined back. A dangling link is followed by hand so the + * boundary check sees where a write would really land. + */ + +const MAX_LINK_HOPS = 40; +const IS_WINDOWS = process.platform === 'win32'; + +function errnoCode(err: unknown): string | undefined { + if (err !== null && typeof err === 'object' && 'code' in err && typeof err.code === 'string') return err.code; + return undefined; +} + +async function lstatOrNull(p: string): Promise { + try { + return await fs.lstat(p); + } catch (err) { + const code = errnoCode(err); + if (code === 'ENOENT' || code === 'ENOTDIR') return null; + if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${p.slice(0, 120)}…`); + throw err; + } +} + +/** Real path of `target`, which may not exist yet. */ +export async function realpathWithSuffix(target: string, hops = 0): Promise { + if (hops > MAX_LINK_HOPS) throw new ToolError('outside-workspace', `too many symbolic links while resolving ${target}`); + let cursor = path.resolve(target); + const trailing: string[] = []; + let stat = await lstatOrNull(cursor); + while (!stat) { + const parent = path.dirname(cursor); + if (parent === cursor) throw new ToolError('outside-workspace', `no existing ancestor for ${target}`); + trailing.push(path.basename(cursor)); + cursor = parent; + stat = await lstatOrNull(cursor); + } + let realBase: string; + try { + realBase = await fs.realpath(cursor); + } catch (err) { + if (!stat.isSymbolicLink()) throw err; + // Dangling link: follow it by hand so the check sees its destination. + const linkTarget = await fs.readlink(cursor); + const parentReal = await fs.realpath(path.dirname(cursor)); + realBase = await realpathWithSuffix(path.resolve(parentReal, linkTarget), hops + 1); + } + return trailing.length === 0 ? realBase : path.resolve(realBase, ...trailing.reverse()); +} + +/** True when `target` is `base` or below it. Both must be real absolute paths. */ +export function isInsideDir(base: string, target: string): boolean { + const b = IS_WINDOWS ? base.toLowerCase() : base; + const t = IS_WINDOWS ? target.toLowerCase() : target; + const rel = path.relative(b, t); + if (rel === '') return true; + return !(rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)); +} + +/** + * Windows spellings that alias another name: device and verbatim prefixes + * (`\\?\`, `\\.\`), UNC shares, NTFS alternate data streams (`name:stream`, + * `.git::$INDEX_ALLOCATION`) and segments ending in a dot or space. Plain + * string logic, tested everywhere; enforced only on Windows unless `force`. + */ +export function windowsPathProblem(target: string): string | null { + if (/^[\\/]{2}/.test(target)) return 'UNC, device and verbatim (\\\\?\\) paths are not accepted'; + const rest = target.slice(path.win32.parse(target).root.length); + for (const segment of rest.split(/[\\/]+/)) { + if (segment === '' || segment === '.' || segment === '..') continue; + if (segment.includes(':')) return `"${segment}" contains ":" (NTFS stream syntax is not accepted)`; + if (/[. ]$/.test(segment)) return `"${segment}" ends in a dot or a space, which Windows silently drops`; + } + return null; +} + +/** Expands a leading `~` or `~/` to the home directory. */ +export function expandTilde(p: string, home: string = os.homedir()): string { + if (p === '~') return home; + if (p.startsWith('~/') || (IS_WINDOWS && p.startsWith('~\\'))) return path.join(home, p.slice(2)); + return p; +} + +/** Whether any segment of `absPath` is a `.git` directory (as Windows would also open it). */ +export function isInsideGitDir(absPath: string): boolean { + return absPath + .split(/[\\/]+/) + .some((segment) => { + const lower = segment.toLowerCase(); + const plain = lower.replace(/:.*$/, '').replace(/[. ]+$/, ''); + return (DEFAULT_CASE_INSENSITIVE ? lower : segment) === '.git' || (IS_WINDOWS && plain === '.git'); + }); +} + +export interface JailOptions { + /** Absolute directory relative paths resolve against. */ + readonly cwd: string; + /** Allowed roots (absolute; resolved to real paths by `Jail.create`). */ + readonly roots: readonly string[]; + /** Protected path patterns (`~` expanded here). */ + readonly protectedPaths: readonly string[]; + /** Enforce the Windows alias checks even off Windows (tests). */ + readonly windowsChecks?: boolean; +} + +/** A resolved set of allowed roots for one call. */ +export class Jail { + /** Real path of the session cwd. */ + readonly cwd: string; + /** Real paths of the allowed roots; `roots[0]` is the session cwd. */ + readonly roots: readonly string[]; + readonly #protected: readonly string[]; + readonly #windowsChecks: boolean; + + private constructor(cwd: string, roots: readonly string[], protectedPaths: readonly string[], windowsChecks: boolean) { + this.cwd = cwd; + this.roots = roots; + this.#protected = protectedPaths; + this.#windowsChecks = windowsChecks; + } + + static async create(opts: JailOptions): Promise { + if (!path.isAbsolute(opts.cwd)) throw new ToolError('tool-error', `session cwd is not absolute: ${opts.cwd}`); + let cwd: string; + try { + cwd = await fs.realpath(opts.cwd); + } catch (err) { + throw new ToolError('tool-error', `session cwd ${opts.cwd} cannot be resolved: ${errnoCode(err) ?? String(err)}`); + } + const roots: string[] = [cwd]; + for (const root of opts.roots) { + if (!path.isAbsolute(root)) continue; + try { + const real = await fs.realpath(root); + if (!roots.includes(real)) roots.push(real); + } catch { + // A root that does not exist grants nothing. + } + } + const protectedPaths = opts.protectedPaths.map((p) => expandTilde(p)); + return new Jail(cwd, roots, protectedPaths, opts.windowsChecks ?? IS_WINDOWS); + } + + /** Protected path patterns with `~` expanded. */ + get protectedPaths(): readonly string[] { + return this.#protected; + } + + /** The root that contains `abs`, or undefined. */ + rootOf(abs: string): string | undefined { + return this.roots.find((root) => isInsideDir(root, abs)); + } + + /** + * Resolves `input` (relative to the session cwd, `~` expanded) to an + * absolute real path inside the roots, or throws `ToolError`. + */ + async resolve(input: string): Promise { + if (input.includes('\0')) throw new ToolError('invalid-args', 'path must not contain NUL characters'); + const trimmed = input.trim(); + if (trimmed === '') throw new ToolError('invalid-args', 'path must not be empty'); + if (this.#windowsChecks) { + const problem = windowsPathProblem(trimmed); + if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); + } + const expanded = expandTilde(trimmed); + const candidate = path.isAbsolute(expanded) ? path.resolve(expanded) : path.resolve(this.cwd, expanded); + let real: string; + try { + real = await realpathWithSuffix(candidate); + } catch (err) { + if (err instanceof ToolError) throw err; + const code = errnoCode(err); + if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${trimmed.slice(0, 120)}…`); + if (code === 'ELOOP') throw new ToolError('outside-workspace', `${trimmed}: too many symbolic links`); + throw new ToolError('tool-error', `cannot resolve ${trimmed}: ${code ?? String(err)}`); + } + if (this.rootOf(real) === undefined) { + throw new ToolError('outside-workspace', `${trimmed} resolves to ${real}, outside the workspace (${this.roots.join(', ')})`); + } + if (this.#windowsChecks) { + const problem = windowsPathProblem(real); + if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); + } + return real; + } + + /** Throws `protected-path` when `abs` must not be written or edited. */ + assertWritable(abs: string): void { + if (isInsideGitDir(abs)) throw new ToolError('protected-path', `${abs} is inside a .git directory`); + const hit = findMatchingPattern(abs, this.#protected); + if (hit !== undefined) throw new ToolError('protected-path', `${abs} is a protected host policy path (${hit})`); + } + + /** Path for diffs and messages: relative to the first root when inside it, else absolute. */ + displayPath(abs: string): string { + const first = this.roots[0] ?? this.cwd; + if (isInsideDir(first, abs)) { + const rel = path.relative(first, abs); + return rel === '' ? '.' : rel.split(path.sep).join('/'); + } + return abs.split(path.sep).join('/'); + } +} diff --git a/src/tools/journal.test.ts b/src/tools/journal.test.ts new file mode 100644 index 0000000..7e857c7 --- /dev/null +++ b/src/tools/journal.test.ts @@ -0,0 +1,185 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { PolicySnapshot, SessionContext, ToolCall, Transaction } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { FileTransaction, journalRoot, recoverStaleJournals } from './journal.js'; +import { NodeToolRuntime } from './runtime.js'; + +let base: string; +let ws: string; +let outside: string; +let stateDir: string; +let ctx: SessionContext; +let rt: NodeToolRuntime; +let seq = 0; +const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; +const signal = new AbortController().signal; + +async function write(rel: string, content: string, tx: Transaction): Promise { + const prepared = await rt.prepare({ id: `c${++seq}`, tool: 'write', args: { path: rel, content } } satisfies ToolCall, ctx, policy); + await rt.commit(prepared, signal, tx); +} + +const read = (rel: string): string => readFileSync(path.join(ws, rel), 'utf8'); + +/** A pid that belonged to a process that has exited. */ +function deadPid(): number { + const r = spawnSync(process.execPath, ['-e', '']); + return r.pid ?? 999_999; +} + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-journal-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + stateDir = path.join(base, 'state'); + mkdirSync(ws); + mkdirSync(outside); + ctx = makeContext(ws); + rt = new NodeToolRuntime({ stateDir }); + writeFileSync(path.join(ws, 'a.txt'), 'a0\n'); + writeFileSync(path.join(ws, 'b.txt'), 'b0\n'); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe('transactions', () => { + it('rolls back three writes (two edits and a create in a new directory)', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await write('a.txt', 'a2\n', tx); + await write('b.txt', 'b1\n', tx); + await write('new/dir/c.txt', 'c1\n', tx); + expect(existsSync(path.join(stateDir, 'journal'))).toBe(true); + const report = await tx.rollback(); + expect(report.skipped).toEqual([]); + expect([...report.restored].sort()).toEqual([path.join(ws, 'a.txt'), path.join(ws, 'b.txt'), path.join(ws, 'new/dir/c.txt')].sort()); + expect(read('a.txt')).toBe('a0\n'); + expect(read('b.txt')).toBe('b0\n'); + expect(existsSync(path.join(ws, 'new'))).toBe(false); + expect(readdirSync(journalRoot(stateDir))).toEqual([]); + }); + + it('does not clobber a file changed externally after our write, and reports it', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await write('b.txt', 'b1\n', tx); + writeFileSync(path.join(ws, 'a.txt'), 'edited by someone else\n'); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'b.txt')]); + expect(report.skipped).toEqual([{ path: path.join(ws, 'a.txt'), reason: 'changed-externally', detail: expect.any(String) }]); + expect(read('a.txt')).toBe('edited by someone else\n'); + expect(read('b.txt')).toBe('b0\n'); + }); + + it('keeps changes and deletes the journal on dispose, and refuses writes afterwards', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await tx.dispose(); + await tx.dispose(); + expect(read('a.txt')).toBe('a1\n'); + expect(readdirSync(journalRoot(stateDir))).toEqual([]); + await expect(write('b.txt', 'b1\n', tx)).rejects.toBeInstanceOf(ToolError); + expect(read('b.txt')).toBe('b0\n'); + }); + + it('refuses a write that would push the journal past its size cap', async () => { + const big = Buffer.alloc(33 * 1024 * 1024, 0x61); + writeFileSync(path.join(ws, 'big1.txt'), big); + writeFileSync(path.join(ws, 'big2.txt'), big); + const tx = rt.beginTransaction(); + await write('big1.txt', 'small\n', tx); + const err = await write('big2.txt', 'small\n', tx).then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ToolError); + expect(String(err)).toMatch(/journal is full/); + expect(readFileSync(path.join(ws, 'big2.txt')).length).toBe(big.length); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'big1.txt')]); + expect(readFileSync(path.join(ws, 'big1.txt')).equals(big)).toBe(true); + }); + + it('refuses a transaction it did not start', async () => { + const foreign: Transaction = { rollback: async () => ({ restored: [], skipped: [] }), dispose: async () => undefined }; + await expect(write('a.txt', 'a1\n', foreign)).rejects.toThrow(/not started by this tool runtime/); + expect(read('a.txt')).toBe('a0\n'); + }); +}); + +describe('crash recovery', () => { + /** Makes the journal of `tx` look like it was left by a process that died. */ + function abandon(tx: FileTransaction): string { + const dir = tx.dir; + const manifestPath = path.join(dir, 'manifest.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { pid: number }; + const pid = deadPid(); + manifest.pid = pid; + writeFileSync(manifestPath, JSON.stringify(manifest)); + const [stamp, , hex] = path.basename(dir).split('-'); + const moved = path.join(path.dirname(dir), `${stamp}-${pid}-${hex}`); + renameSync(dir, moved); + return moved; + } + + it('restores a journal whose process is gone, and leaves a live one alone', async () => { + const crashed = rt.beginTransaction(); + if (!(crashed instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', crashed); + await write('new.txt', 'n1\n', crashed); + await write('b.txt', 'b1\n', crashed); + writeFileSync(path.join(ws, 'b.txt'), 'changed after the crash\n'); + const moved = abandon(crashed); + + const live = rt.beginTransaction(); + writeFileSync(path.join(ws, 'live.txt'), 'l0\n'); + await write('live.txt', 'l1\n', live); + + const recovered = await recoverStaleJournals(stateDir, [ws]); + expect(recovered).toHaveLength(1); + const report = recovered[0]?.report; + expect([...(report?.restored ?? [])].sort()).toEqual([path.join(ws, 'a.txt'), path.join(ws, 'new.txt')]); + expect(report?.skipped).toEqual([{ path: path.join(ws, 'b.txt'), reason: 'changed-externally', detail: expect.any(String) }]); + expect(read('a.txt')).toBe('a0\n'); + expect(existsSync(path.join(ws, 'new.txt'))).toBe(false); + expect(read('b.txt')).toBe('changed after the crash\n'); + expect(read('live.txt')).toBe('l1\n'); + expect(existsSync(moved)).toBe(false); + await live.dispose(); + }); + + it('ignores journals of other workspaces and never restores outside the roots', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + const moved = abandon(tx); + // Another workspace: nothing happens. + expect(await recoverStaleJournals(stateDir, [outside])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + + // A tampered record pointing outside the roots is not followed. + writeFileSync(path.join(outside, 'victim.txt'), 'victim\n'); + const manifestPath = path.join(moved, 'manifest.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { entries: { path: string }[] }; + const first = manifest.entries[0]; + if (first) first.path = path.join(outside, 'victim.txt'); + writeFileSync(manifestPath, JSON.stringify(manifest)); + const recovered = await recoverStaleJournals(stateDir, [ws]); + expect(recovered[0]?.report.restored).toEqual([]); + expect(recovered[0]?.report.skipped[0]?.reason).toBe('error'); + expect(readFileSync(path.join(outside, 'victim.txt'), 'utf8')).toBe('victim\n'); + }); + + it('skips a malformed record', async () => { + mkdirSync(path.join(journalRoot(stateDir), 'zz-1-abcd'), { recursive: true }); + writeFileSync(path.join(journalRoot(stateDir), 'zz-1-abcd', 'manifest.json'), '{"version":1,"entries":"nope"}'); + expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); + }); +}); diff --git a/src/tools/journal.ts b/src/tools/journal.ts new file mode 100644 index 0000000..0798d0d --- /dev/null +++ b/src/tools/journal.ts @@ -0,0 +1,386 @@ +/* + * The journal design (original bytes written durably before the first change, + * restore only files that still hold what this process wrote, recovery of a + * record whose process is gone) follows Turnpack's src/journal.ts + * (https://github.com/OnlyTerp/turnpack, Copyright 2026 OnlyTerp, Apache-2.0). + * Modified by the agent-code-mode authors: the record grows one file at a time + * across a run instead of being written once per call, and it is restored + * through the workspace jail checks of this project. + */ +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { z } from 'zod'; +import { ToolError, errorMessage } from '../core/errors.js'; +import type { RollbackReport, Transaction } from '../core/types.js'; +import { assertDirUnchanged, atomicWrite, errnoCode, readRegularFile, removeRegularFile, sha256, syncDir, writeDurable } from './fs-ops.js'; +import { isInsideDir, isInsideGitDir } from './jail.js'; + +/** Above this many bytes of originals a transaction refuses further writes. */ +export const MAX_JOURNAL_BYTES = 64 * 1024 * 1024; +/** Slack when comparing a start time with the boot time. */ +const BOOT_SLACK_MS = 10_000; +const MANIFEST = 'manifest.json'; +const RECOVERING = '.recovering-'; + +const EntrySchema = z.object({ + path: z.string().min(1), + existed: z.boolean(), + /** SHA-256 of the original bytes ('' when absent). */ + original: z.string(), + mode: z.number().int().nullable(), + /** Blob file name holding the original bytes (null when absent). */ + blob: z.string().regex(/^[0-9]+\.bin$/).nullable(), + /** Hashes this transaction wrote (or was about to write) to the file, oldest first. */ + written: z.array(z.string()), +}); + +const ManifestSchema = z.object({ + version: z.literal(1), + pid: z.number().int(), + host: z.string(), + startedAt: z.number(), + roots: z.array(z.string()), + /** Directories the transaction created, outermost first. */ + dirs: z.array(z.string()), + entries: z.array(EntrySchema), +}); + +type Manifest = z.infer; +type Entry = z.infer; + +/** Journal directory under the server state dir. */ +export function journalRoot(stateDir: string): string { + return path.join(stateDir, 'journal'); +} + +/** Ids of transactions this process still has open; a recovery pass leaves them alone. */ +const openTransactions = new Set(); + +interface LiveEntry { + readonly entry: Entry; + /** Original bytes, kept in memory for the in-process rollback. */ + readonly bytes: Buffer | null; + /** Hash of what this transaction last wrote, or null after a failed write. */ + last: string | null; +} + +/** + * A per-run journal. The first write to a file snapshots its original bytes + * (or "absent") in memory and durably under `/journal//` + * before the file is touched. + */ +export class FileTransaction implements Transaction { + readonly id: string; + readonly dir: string; + readonly #roots: string[] = []; + readonly #startedAt = Date.now(); + readonly #entries = new Map(); + readonly #dirs: string[] = []; + #bytes = 0; + #created = false; + #closed = false; + #queue: Promise = Promise.resolve(); + + constructor(stateDir: string) { + this.id = `${this.#startedAt.toString(36)}-${process.pid}-${randomBytes(4).toString('hex')}`; + this.dir = path.join(journalRoot(stateDir), this.id); + openTransactions.add(this.id); + } + + /** True once rolled back or disposed. */ + get closed(): boolean { + return this.#closed; + } + + #serial(fn: () => Promise): Promise { + const next = this.#queue.then(fn, fn); + this.#queue = next.catch(() => undefined); + return next; + } + + #manifest(): Manifest { + return { + version: 1, + pid: process.pid, + host: os.hostname(), + startedAt: this.#startedAt, + roots: [...this.#roots], + dirs: [...this.#dirs], + entries: [...this.#entries.values()].map((live) => live.entry), + }; + } + + async #persist(): Promise { + if (!this.#created) { + await fs.mkdir(path.dirname(this.dir), { recursive: true, mode: 0o700 }); + await fs.mkdir(this.dir, { mode: 0o700 }); + this.#created = true; + } + const next = path.join(this.dir, `${MANIFEST}.next`); + await writeDurable(next, JSON.stringify(this.#manifest())); + await fs.rename(next, path.join(this.dir, MANIFEST)); + await syncDir(this.dir); + } + + /** + * Called by a commit after the stale check and before the write. Records + * the original on the first write to `absPath` and the hash about to be + * written. Throws when the journal is full or closed. + */ + record( + absPath: string, + root: string, + before: { readonly bytes: Buffer; readonly mode: number } | null, + nextHash: string, + createdDirs: readonly string[], + ): Promise { + return this.#serial(async () => { + if (this.#closed) throw new ToolError('tool-error', 'the transaction is already finished'); + if (!this.#roots.includes(root)) this.#roots.push(root); + const existing = this.#entries.get(absPath); + if (existing) { + existing.entry.written.push(nextHash); + await this.#persist(); + return; + } + const size = before?.bytes.length ?? 0; + if (this.#bytes + size > MAX_JOURNAL_BYTES) { + throw new ToolError( + 'tool-error', + `transaction journal is full: snapshotting ${absPath} (${size} bytes) would exceed ${MAX_JOURNAL_BYTES} bytes, so the write was refused to keep rollback possible`, + ); + } + let blob: string | null = null; + if (before) { + if (!this.#created) await this.#persist(); + blob = `${this.#entries.size}.bin`; + await writeDurable(path.join(this.dir, blob), before.bytes); + } + this.#bytes += size; + for (const d of createdDirs) if (!this.#dirs.includes(d)) this.#dirs.push(d); + this.#entries.set(absPath, { + entry: { + path: absPath, + existed: before !== null, + original: before ? sha256(before.bytes) : '', + mode: before?.mode ?? null, + blob, + written: [nextHash], + }, + bytes: before?.bytes ?? null, + last: null, + }); + await this.#persist(); + }); + } + + /** Called after a successful write. */ + written(absPath: string, hash: string): void { + const live = this.#entries.get(absPath); + if (live) live.last = hash; + } + + rollback(): Promise { + return this.#serial(async () => { + if (this.#closed) return { restored: [], skipped: [] }; + this.#closed = true; + openTransactions.delete(this.id); + const restored: string[] = []; + const skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[] = []; + for (const live of [...this.#entries.values()].reverse()) { + const { entry } = live; + try { + const current = await readRegularFile(entry.path).catch((err: unknown) => { + throw new ToolError('stale', `cannot read: ${errorMessage(err)}`); + }); + const currentHash = current ? sha256(current.bytes) : null; + const originalHash = entry.existed ? entry.original : null; + if (currentHash === originalHash) continue; + if (live.last === null || currentHash !== live.last) { + skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what this run wrote' }); + continue; + } + await restoreEntry(entry, live.bytes, currentHash); + restored.push(entry.path); + } catch (err) { + skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); + } + } + await removeCreatedDirs(this.#dirs); + await this.#removeRecord(); + return { restored, skipped }; + }); + } + + dispose(): Promise { + return this.#serial(async () => { + this.#closed = true; + openTransactions.delete(this.id); + await this.#removeRecord(); + }); + } + + async #removeRecord(): Promise { + if (!this.#created) return; + await fs.rm(this.dir, { recursive: true, force: true }); + this.#created = false; + } +} + +async function restoreEntry(entry: Entry, bytes: Buffer | null, currentHash: string | null): Promise { + if (isInsideGitDir(entry.path)) throw new ToolError('protected-path', 'inside a .git directory'); + if (!entry.existed) { + await assertDirUnchanged(path.dirname(entry.path)); + await removeRegularFile(entry.path); + return; + } + if (bytes === null || sha256(bytes) !== entry.original) throw new ToolError('tool-error', 'the saved original is damaged'); + const expect = currentHash === null ? ({ kind: 'absent' } as const) : ({ kind: 'hash', sha256: currentHash } as const); + await atomicWrite(entry.path, bytes, expect); + if (entry.mode !== null && process.platform !== 'win32') await fs.chmod(entry.path, entry.mode).catch(() => undefined); +} + +async function removeCreatedDirs(dirs: readonly string[]): Promise { + for (const d of [...dirs].sort((a, b) => b.length - a.length)) { + try { + await fs.rmdir(d); + } catch { + // Not empty, or already gone. + } + } +} + +// --------------------------------------------------------------------------- +// Crash recovery. +// --------------------------------------------------------------------------- + +function isAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return errnoCode(err) === 'EPERM'; + } +} + +/** Whether the process that wrote a record can no longer be running it. */ +function ownerGone(manifest: Manifest, openHere: ReadonlySet, id: string): boolean { + if (manifest.pid === process.pid) return !openHere.has(id); + if (!isAlive(manifest.pid)) return true; + // A pid alone does not say: the system hands a dead process's id to a new one. + const bootedAt = Date.now() - os.uptime() * 1000; + return bootedAt > manifest.startedAt + BOOT_SLACK_MS; +} + +/** What a recovery pass did for one stale journal. */ +export interface RecoveredJournal { + readonly id: string; + readonly report: RollbackReport; +} + +async function realOrSelf(p: string): Promise { + try { + return await fs.realpath(p); + } catch { + return p; + } +} + +async function readOriginal(dir: string, entry: Entry): Promise { + if (entry.blob === null) return null; + return fs.readFile(path.join(dir, entry.blob)); +} + +async function undoRecord(manifest: Manifest, dir: string, roots: readonly string[]): Promise { + const restored: string[] = []; + const skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[] = []; + for (const entry of [...manifest.entries].reverse()) { + try { + // The record is data on disk: each path is checked like a tool argument. + if (!path.isAbsolute(entry.path) || !roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the workspace roots; not touched' }); + continue; + } + if (!manifest.roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the roots the journal was written for; not touched' }); + continue; + } + await assertDirUnchanged(path.dirname(entry.path)).catch((err: unknown) => { + // A parent that no longer exists is fine for a created file that is gone too. + if (entry.existed) throw err; + }); + const current = await readRegularFile(entry.path); + const currentHash = current ? sha256(current.bytes) : null; + const originalHash = entry.existed ? entry.original : null; + if (currentHash === originalHash) continue; + if (currentHash === null || !entry.written.includes(currentHash)) { + skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what the crashed run wrote' }); + continue; + } + const bytes = await readOriginal(dir, entry); + await restoreEntry(entry, bytes, currentHash); + restored.push(entry.path); + } catch (err) { + skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); + } + } + const dirs = manifest.dirs.filter((d) => path.isAbsolute(d) && roots.some((root) => isInsideDir(root, d) && root !== d)); + await removeCreatedDirs(dirs); + return { restored, skipped }; +} + +/** + * Restores every journal left by a server process that is gone and that + * touched one of `roots` (newest first, so two cut-off runs that changed the + * same file unwind in order). Files are restored only when they still hold + * what that run wrote; anything else is reported in `skipped`. Never throws. + */ +export async function recoverStaleJournals(stateDir: string, roots: readonly string[]): Promise { + const base = journalRoot(stateDir); + let names: string[]; + try { + names = await fs.readdir(base); + } catch { + return []; + } + const realRoots = await Promise.all(roots.filter((r) => path.isAbsolute(r)).map(realOrSelf)); + const records = names + .map((name) => ({ name, id: name.includes(RECOVERING) ? name.slice(0, name.indexOf(RECOVERING)) : name })) + .filter((r) => /^[0-9a-z]+-\d+-[0-9a-f]+$/.test(r.id)) + .sort((a, b) => parseInt(b.id.split('-')[0] ?? '0', 36) - parseInt(a.id.split('-')[0] ?? '0', 36)); + const out: RecoveredJournal[] = []; + for (const record of records) { + const dir = path.join(base, record.name); + try { + const raw: unknown = JSON.parse(await fs.readFile(path.join(dir, MANIFEST), 'utf8')); + const parsed = ManifestSchema.safeParse(raw); + if (!parsed.success) continue; + const manifest = parsed.data; + if (manifest.host !== os.hostname()) continue; + if (!manifest.roots.some((r) => realRoots.some((root) => isInsideDir(root, r) || isInsideDir(r, root)))) continue; + if (record.name.includes(RECOVERING)) { + const claimer = Number(record.name.slice(record.name.indexOf(RECOVERING) + RECOVERING.length)); + if (claimer !== process.pid && isAlive(claimer)) continue; + } else if (!ownerGone(manifest, openTransactions, record.id)) { + continue; + } + const claimed = path.join(base, `${record.id}${RECOVERING}${process.pid}`); + if (claimed !== dir) { + try { + await fs.rename(dir, claimed); + } catch { + continue; + } + } + const report = await undoRecord(manifest, claimed, realRoots); + await fs.rm(claimed, { recursive: true, force: true }); + out.push({ id: record.id, report }); + } catch { + // One bad record must not stop the others. + } + } + return out; +} diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts new file mode 100644 index 0000000..15912e7 --- /dev/null +++ b/src/tools/runtime.test.ts @@ -0,0 +1,370 @@ +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { PolicySnapshot, PreparedCall, SessionContext, ToolArgsMap, ToolCall, ToolName, ToolResult } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { windowsPathProblem } from './jail.js'; +import { NodeToolRuntime } from './runtime.js'; + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let outside: string; +let ctx: SessionContext; +let policy: PolicySnapshot; +let rt: NodeToolRuntime; +let outsideBefore: Record; +let seq = 0; + +/** Every entry under `dir` with its type and content (links are not followed). */ +function snapshot(dir: string): Record { + const out: Record = {}; + const walk = (d: string): void => { + for (const name of readdirSync(d)) { + const p = path.join(d, name); + const st = lstatSync(p); + if (st.isSymbolicLink()) out[p] = `link:${readlinkSync(p)}`; + else if (st.isDirectory()) { + out[p] = 'dir'; + walk(p); + } else out[p] = `file:${readFileSync(p, 'utf8')}`; + } + }; + walk(dir); + return out; +} + +function call(tool: K, args: ToolArgsMap[K]): ToolCall { + return { id: `c${++seq}`, tool, args } as ToolCall; +} + +async function prep(tool: K, args: ToolArgsMap[K]): Promise { + return rt.prepare(call(tool, args), ctx, policy); +} + +async function run(tool: K, args: ToolArgsMap[K]): Promise { + return rt.commit(await prep(tool, args), new AbortController().signal); +} + +async function code(p: Promise): Promise { + try { + await p; + } catch (err) { + if (err instanceof ToolError) return err.code; + throw err; + } + return 'resolved'; +} + +function link(target: string, at: string): void { + symlinkSync(target, at, statSync(target, { throwIfNoEntry: false })?.isDirectory() ? 'dir' : 'file'); +} + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-tools-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + mkdirSync(ws); + mkdirSync(outside); + writeFileSync(path.join(outside, 'secret.txt'), 'secret value\n'); + mkdirSync(path.join(outside, 'deep')); + writeFileSync(path.join(outside, 'deep', 'more.txt'), 'secret value too\n'); + ctx = makeContext(ws); + policy = { + host: 'generic', + bashContainment: { mode: 'none' }, + protectedPaths: [`${ws}/.claude/settings*.json`, `${ws}/.claude/hooks/**`, `${ws}/.codex/**`, `${ws}/.mcp.json`], + payload: null, + }; + rt = new NodeToolRuntime({ stateDir: path.join(base, 'state') }); + outsideBefore = snapshot(outside); +}); + +afterEach(() => { + // Every attack test also asserts that nothing outside the jail changed. + expect(snapshot(outside)).toEqual(outsideBefore); + rmSync(base, { recursive: true, force: true }); +}); + +describe('path traversal', () => { + it('refuses ../, absolute paths outside and ~', async () => { + for (const p of ['../outside/secret.txt', `${outside}/secret.txt`, 'a/../../outside/new.txt', '~/acm-must-not-exist.txt', '~']) { + expect(await code(prep('read', { path: p }))).toBe('outside-workspace'); + expect(await code(prep('write', { path: p, content: 'x' }))).toBe('outside-workspace'); + expect(await code(prep('edit', { path: p, oldString: 'secret', newString: 'x' }))).toBe('outside-workspace'); + } + expect(await code(prep('grep', { pattern: 'secret', path: '..' }))).toBe('outside-workspace'); + expect(await code(prep('glob', { pattern: '**/*', path: outside }))).toBe('outside-workspace'); + expect(await code(prep('bash', { command: 'pwd', cwd: '../outside' }))).toBe('outside-workspace'); + expect(existsSync(path.join(os.homedir(), 'acm-must-not-exist.txt'))).toBe(false); + }); + + it('refuses NUL bytes and very long paths', async () => { + expect(await code(prep('write', { path: 'a\0b', content: 'x' }))).toBe('invalid-args'); + const long = `${'a'.repeat(250)}/`.repeat(40) + 'f.txt'; + const result = await code(run('write', { path: long, content: 'x' })); + expect(['invalid-args', 'tool-error']).toContain(result); + expect(readdirSync(ws)).toEqual([]); + }); + + it('keeps unicode lookalikes of .. inside the workspace', async () => { + for (const p of ['\u2025/outside/x.txt', '\uff0e\uff0e/outside/x.txt', '.\u2024/outside/x.txt']) { + const prepared = await prep('write', { path: p, content: 'x' }); + expect(prepared.tool === 'write' && prepared.effect.absPath.startsWith(`${ws}${path.sep}`)).toBe(true); + } + }); + + it('flags Windows alias spellings', () => { + expect(windowsPathProblem('\\\\?\\C:\\x')).not.toBeNull(); + expect(windowsPathProblem('\\\\server\\share\\x')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\.env::$DATA')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\file.txt:stream')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\.git.\\config')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\src\\a.ts')).toBeNull(); + }); +}); + +describe.skipIf(IS_WINDOWS)('symlinks', () => { + beforeEach(() => { + link(outside, path.join(ws, 'link-out')); + link(path.join(outside, 'secret.txt'), path.join(ws, 'file-link')); + symlinkSync(path.join(outside, 'not-yet.txt'), path.join(ws, 'dangling')); + writeFileSync(path.join(ws, 'inside.txt'), 'inside secret value\n'); + }); + + it('does not let read, write or edit follow a link out', async () => { + for (const p of ['file-link', 'link-out/secret.txt', 'link-out/deep/more.txt', 'dangling', 'link-out/new.txt']) { + expect(await code(prep('read', { path: p }))).toBe('outside-workspace'); + expect(await code(prep('write', { path: p, content: 'pwned' }))).toBe('outside-workspace'); + expect(await code(prep('edit', { path: p, oldString: 'secret', newString: 'pwned' }))).toBe('outside-workspace'); + } + expect(await code(prep('grep', { pattern: 'x', path: 'link-out' }))).toBe('outside-workspace'); + expect(await code(prep('glob', { pattern: '*', path: 'link-out' }))).toBe('outside-workspace'); + expect(existsSync(path.join(outside, 'not-yet.txt'))).toBe(false); + }); + + it('does not let grep or glob walk through links', async () => { + const grep = await run('grep', { pattern: 'secret' }); + expect('matches' in grep ? grep.matches.map((m) => m.file) : []).toEqual([path.join(ws, 'inside.txt')]); + const glob = await run('glob', { pattern: '**/*' }); + expect('files' in glob ? glob.files : []).toEqual([path.join(ws, 'inside.txt')]); + }); + + it('refuses a write when the file was swapped for a link after prepare', async () => { + writeFileSync(path.join(ws, 'f.txt'), 'one\n'); + const write = await prep('write', { path: 'f.txt', content: 'pwned\n' }); + const edit = await prep('edit', { path: 'f.txt', oldString: 'one', newString: 'pwned' }); + const read = await prep('read', { path: 'f.txt' }); + rmSync(path.join(ws, 'f.txt')); + link(path.join(outside, 'secret.txt'), path.join(ws, 'f.txt')); + const signal = new AbortController().signal; + expect(await code(rt.commit(write, signal))).toBe('stale'); + expect(await code(rt.commit(edit, signal))).toBe('stale'); + expect(await code(rt.commit(read, signal))).toBe('stale'); + }); + + it('refuses a create when a link appears at the name after prepare', async () => { + const write = await prep('write', { path: 'new.txt', content: 'pwned\n' }); + symlinkSync(path.join(outside, 'created-by-link.txt'), path.join(ws, 'new.txt')); + expect(await code(rt.commit(write, new AbortController().signal))).toBe('stale'); + expect(existsSync(path.join(outside, 'created-by-link.txt'))).toBe(false); + }); + + it('refuses a write when a parent directory was replaced by a link after prepare', async () => { + mkdirSync(path.join(ws, 'dir')); + writeFileSync(path.join(ws, 'dir', 'secret.txt'), 'secret value\n'); + const write = await prep('write', { path: 'dir/secret.txt', content: 'pwned\n' }); + const create = await prep('write', { path: 'dir/fresh.txt', content: 'pwned\n' }); + const nested = await prep('write', { path: 'dir/a/b/c.txt', content: 'pwned\n' }); + renameSync(path.join(ws, 'dir'), path.join(ws, 'dir-moved')); + link(outside, path.join(ws, 'dir')); + const signal = new AbortController().signal; + expect(await code(rt.commit(write, signal))).toBe('stale'); + expect(await code(rt.commit(create, signal))).toBe('stale'); + expect(await code(rt.commit(nested, signal))).toBe('stale'); + }); + + it('refuses writing through a link that bash created mid-run', async () => { + const pending = await prep('write', { path: 'via-later.txt', content: 'pwned\n' }); + const bash = await run('bash', { command: `ln -s ${JSON.stringify(path.join(outside, 'secret.txt'))} via.txt && ln -s ${JSON.stringify(path.join(outside, 'later.txt'))} via-later.txt` }); + expect('exitCode' in bash && bash.exitCode).toBe(0); + expect(await code(prep('write', { path: 'via.txt', content: 'pwned\n' }))).toBe('outside-workspace'); + expect(await code(rt.commit(pending, new AbortController().signal))).toBe('stale'); + expect(existsSync(path.join(outside, 'later.txt'))).toBe(false); + }); + + it('follows links that stay inside the workspace', async () => { + link(path.join(ws, 'inside.txt'), path.join(ws, 'alias.txt')); + const read = await run('read', { path: 'alias.txt' }); + expect('content' in read && read.path).toBe(path.join(ws, 'inside.txt')); + }); +}); + +describe('protected paths', () => { + it('refuses writes and edits to host config and .git, but allows reads', async () => { + mkdirSync(path.join(ws, '.git')); + writeFileSync(path.join(ws, '.git', 'config'), '[core]\n'); + mkdirSync(path.join(ws, '.claude')); + writeFileSync(path.join(ws, '.claude', 'settings.json'), '{}\n'); + for (const p of ['.claude/settings.json', '.claude/settings.local.json', '.codex/config.toml', '.git/config', '.git/hooks/pre-commit', 'sub/.git/config', '.mcp.json']) { + expect(await code(prep('write', { path: p, content: 'x' }))).toBe('protected-path'); + } + expect(await code(prep('edit', { path: '.git/config', oldString: '[core]', newString: '[x]' }))).toBe('protected-path'); + expect(await code(prep('edit', { path: '.claude/settings.json', oldString: '{}', newString: '{"x":1}' }))).toBe('protected-path'); + const read = await run('read', { path: '.git/config' }); + expect('content' in read && read.content).toBe('[core]'); + expect(readFileSync(path.join(ws, '.git', 'config'), 'utf8')).toBe('[core]\n'); + }); + + it('expands ~ in protected patterns', async () => { + const home = path.join(ws, 'home'); + mkdirSync(home); + const homeCtx = makeContext(ws); + const p = { ...policy, protectedPaths: [`~/.claude/**`] }; + const prevHome = process.env['HOME']; + process.env['HOME'] = home; + try { + if (os.homedir() !== home) return; // os.homedir ignores HOME on this platform + expect(await code(rt.prepare(call('write', { path: 'home/.claude/x.json', content: '1' }), homeCtx, p))).toBe('protected-path'); + } finally { + process.env['HOME'] = prevHome; + } + }); +}); + +describe('write and edit', () => { + it('refuses an ambiguous edit without writing', async () => { + writeFileSync(path.join(ws, 'a.ts'), 'x = 1\ny = 2\nx = 1\n'); + expect(await code(prep('edit', { path: 'a.ts', oldString: 'x = 1', newString: 'x = 3' }))).toBe('invalid-args'); + expect(await code(prep('edit', { path: 'a.ts', oldString: 'nothing like it', newString: 'z' }))).toBe('not-found'); + expect(readFileSync(path.join(ws, 'a.ts'), 'utf8')).toBe('x = 1\ny = 2\nx = 1\n'); + }); + + it('refuses a commit when the file changed after prepare', async () => { + writeFileSync(path.join(ws, 'a.ts'), 'x = 1\n'); + const edit = await prep('edit', { path: 'a.ts', oldString: 'x = 1', newString: 'x = 2' }); + const write = await prep('write', { path: 'a.ts', content: 'overwritten\n' }); + writeFileSync(path.join(ws, 'a.ts'), 'x = 1 // changed\n'); + expect(await code(rt.commit(edit, new AbortController().signal))).toBe('stale'); + expect(await code(rt.commit(write, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'a.ts'), 'utf8')).toBe('x = 1 // changed\n'); + + const create = await prep('write', { path: 'b.ts', content: 'mine\n' }); + writeFileSync(path.join(ws, 'b.ts'), 'theirs\n'); + expect(await code(rt.commit(create, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'b.ts'), 'utf8')).toBe('theirs\n'); + }); + + it('applies a tolerant edit and carries the exact matched text and diff', async () => { + writeFileSync(path.join(ws, 'f.js'), 'function f() {\n if (x) {\n return 1;\n }\n}\n'); + const prepared = await prep('edit', { path: 'f.js', oldString: 'if (x) {\n return 1;\n}', newString: 'if (x) {\n return 2;\n}' }); + if (prepared.tool !== 'edit') throw new Error('unreachable'); + expect(prepared.effect.matchStrategy).toBe('indentation-flexible'); + expect(prepared.effect.matchedOldString).toBe(' if (x) {\n return 1;\n }'); + expect(prepared.effect.diff).toContain('--- a/f.js\n+++ b/f.js\n'); + expect(prepared.effect.diff).toContain('- return 1;\n+ return 2;\n'); + const result = await rt.commit(prepared, new AbortController().signal); + expect('replacements' in result && result.replacements).toBe(1); + expect(readFileSync(path.join(ws, 'f.js'), 'utf8')).toBe(prepared.effect.afterContent); + }); + + it.skipIf(IS_WINDOWS)('writes atomically, keeps the mode and creates parents', async () => { + writeFileSync(path.join(ws, 'run.sh'), '#!/bin/sh\necho 1\n'); + chmodSync(path.join(ws, 'run.sh'), 0o751); + const result = await run('write', { path: 'run.sh', content: '#!/bin/sh\necho 2\n' }); + expect('created' in result && result.created).toBe(false); + expect(statSync(path.join(ws, 'run.sh')).mode & 0o777).toBe(0o751); + const created = await run('write', { path: 'new/deep/file.txt', content: 'hi' }); + expect('created' in created && created.created).toBe(true); + expect(readFileSync(path.join(ws, 'new/deep/file.txt'), 'utf8')).toBe('hi'); + expect(readdirSync(path.join(ws, 'new/deep'))).toEqual(['file.txt']); + }); + + it('refuses edits of binary files and directories', async () => { + writeFileSync(path.join(ws, 'b.bin'), Buffer.from([0, 1, 2, 3])); + mkdirSync(path.join(ws, 'd')); + expect(await code(prep('edit', { path: 'b.bin', oldString: 'a', newString: 'b' }))).toBe('tool-error'); + expect(await code(prep('write', { path: 'd', content: 'x' }))).toBe('invalid-args'); + expect(await code(prep('edit', { path: 'missing.txt', oldString: 'a', newString: 'b' }))).toBe('not-found'); + }); +}); + +describe('read', () => { + it('returns a window of lines and the total', async () => { + writeFileSync(path.join(ws, 'r.txt'), 'l1\nl2\nl3\nl4\n'); + const all = await run('read', { path: 'r.txt' }); + expect(all).toEqual({ path: path.join(ws, 'r.txt'), content: 'l1\nl2\nl3\nl4', startLine: 1, totalLines: 4, truncated: false }); + const part = await run('read', { path: 'r.txt', offset: 2, limit: 2 }); + expect(part).toEqual({ path: path.join(ws, 'r.txt'), content: 'l2\nl3', startLine: 2, totalLines: 4, truncated: true }); + }); + + it('caps the bytes returned and refuses binary files', async () => { + writeFileSync(path.join(ws, 'big.txt'), `${'x'.repeat(1000)}\n`.repeat(1000)); + const big = await run('read', { path: 'big.txt' }); + expect('content' in big && big.truncated).toBe(true); + expect('content' in big && Buffer.byteLength(big.content)).toBeLessThanOrEqual(256 * 1024); + writeFileSync(path.join(ws, 'b.bin'), Buffer.from([0x89, 0x50, 0, 0, 1])); + expect(await code(run('read', { path: 'b.bin' }))).toBe('tool-error'); + expect(await code(prep('read', { path: 'missing' }))).toBe('not-found'); + }); +}); + +describe('grep and glob', () => { + beforeEach(() => { + mkdirSync(path.join(ws, 'src')); + mkdirSync(path.join(ws, 'node_modules', 'dep'), { recursive: true }); + mkdirSync(path.join(ws, 'build')); + mkdirSync(path.join(ws, '.git')); + writeFileSync(path.join(ws, '.gitignore'), 'build/\n*.log\n!keep.log\n'); + writeFileSync(path.join(ws, 'src', 'a.ts'), 'const needle = 1;\nother\n'); + writeFileSync(path.join(ws, 'src', 'b.js'), 'needle again\n'); + writeFileSync(path.join(ws, 'src', 'nested.ts'), 'NEEDLE upper\n'); + writeFileSync(path.join(ws, 'node_modules', 'dep', 'i.js'), 'needle in deps\n'); + writeFileSync(path.join(ws, 'build', 'out.js'), 'needle built\n'); + writeFileSync(path.join(ws, 'debug.log'), 'needle log\n'); + writeFileSync(path.join(ws, 'keep.log'), 'needle kept\n'); + writeFileSync(path.join(ws, '.git', 'HEAD'), 'needle git\n'); + }); + + it('grep skips .git, node_modules and gitignored files', async () => { + const r = await run('grep', { pattern: 'needle' }); + if (!('matches' in r)) throw new Error('unreachable'); + expect(r.matches.map((m) => path.relative(ws, m.file)).sort()).toEqual(['keep.log', path.join('src', 'a.ts'), path.join('src', 'b.js')]); + const ci = await run('grep', { pattern: 'needle', ignoreCase: true, glob: '*.ts' }); + if (!('matches' in ci)) throw new Error('unreachable'); + expect(ci.matches.map((m) => [path.basename(m.file), m.line, m.text])).toEqual([ + ['a.ts', 1, 'const needle = 1;'], + ['nested.ts', 1, 'NEEDLE upper'], + ]); + const capped = await run('grep', { pattern: 'needle', maxResults: 1 }); + expect('matches' in capped && [capped.matches.length, capped.truncated]).toEqual([1, true]); + expect(await code(prep('grep', { pattern: '(' }))).toBe('invalid-args'); + }); + + it('glob lists sorted files with the same ignores', async () => { + const r = await run('glob', { pattern: '**/*.{ts,js}' }); + expect('files' in r && r.files).toEqual([path.join(ws, 'src', 'a.ts'), path.join(ws, 'src', 'b.js'), path.join(ws, 'src', 'nested.ts')]); + const capped = await run('glob', { pattern: '**/*', maxResults: 2 }); + expect('files' in capped && [capped.files.length, capped.truncated]).toEqual([2, true]); + expect(await code(prep('glob', { pattern: `${outside}/*` }))).toBe('invalid-args'); + }); +}); + +describe.skipIf(IS_WINDOWS)('bash cwd', () => { + it('moves a non-default cwd into the command and keeps the effect cwd at the session cwd', async () => { + mkdirSync(path.join(ws, "it's here")); + const prepared = await prep('bash', { command: 'pwd', cwd: "it's here" }); + if (prepared.tool !== 'bash') throw new Error('unreachable'); + expect(prepared.effect.cwd).toBe(ws); + expect(prepared.effect.command).toBe(`cd -- '${ws}/it'\\''s here' && pwd`); + expect(prepared.args.command).toBe(prepared.effect.command); + expect(prepared.effect.timeoutMs).toBe(120_000); + const result = await rt.commit(prepared, new AbortController().signal); + expect('stdout' in result && result.stdout.trim()).toBe(path.join(ws, "it's here")); + const same = await prep('bash', { command: 'pwd', cwd: '.' }); + expect(same.tool === 'bash' && same.effect.command).toBe('pwd'); + }); +}); diff --git a/src/tools/runtime.ts b/src/tools/runtime.ts new file mode 100644 index 0000000..5137fbe --- /dev/null +++ b/src/tools/runtime.ts @@ -0,0 +1,372 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError, errorMessage } from '../core/errors.js'; +import type { + BashContainment, + MatchStrategy, + PolicySnapshot, + PreparedCall, + PreparedCallOf, + ReadResult, + SessionContext, + ToolCall, + ToolResult, + ToolRuntime, + Transaction, +} from '../core/types.js'; +import { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, findBash, runBash, shellQuote } from './bash.js'; +import { binaryDiff, unifiedDiff } from './diff.js'; +import { applySearchReplace, type MatchHow } from './edit-match.js'; +import { assertDirUnchanged, atomicWrite, decodeText, errnoCode, isBinary, readRegularFile, sha256 } from './fs-ops.js'; +import { FileTransaction } from './journal.js'; +import { Jail } from './jail.js'; +import { containmentUnavailableReason } from './sandbox.js'; +import { DEFAULT_GLOB_MAX_RESULTS, DEFAULT_GREP_MAX_RESULTS, compileGrep, normalizeGlob, runGlob, runGrep } from './search.js'; + +/** Default number of lines `read` returns. */ +export const DEFAULT_READ_LIMIT = 2000; +/** Most bytes of content one `read` returns. */ +export const READ_CAP_BYTES = 256 * 1024; +/** Largest file `read`, `write` (existing content) and `edit` load. */ +export const MAX_FILE_BYTES = 64 * 1024 * 1024; + +/** + * How each Turnpack rung is reported in the frozen `MatchStrategy` type, + * which has fewer names than the ladder has rungs. + */ +const STRATEGY: Record = { + exact: 'exact', + 'line-endings': 'whitespace-normalized', + 'line-numbers': 'line-trimmed', + 'trailing-whitespace': 'line-trimmed', + indentation: 'indentation-flexible', + punctuation: 'whitespace-normalized', +}; + +export interface NodeToolRuntimeOptions { + /** Server state directory; transaction journals live under `/journal/`. */ + readonly stateDir: string; + /** Extra absolute directories the tools may touch besides the session cwd and MCP roots. */ + readonly additionalRoots?: readonly string[]; + /** Bytes kept of each of bash stdout and stderr. */ + readonly bashOutputCapBytes?: number; +} + +/** What `commit` needs to know about a call besides its frozen effect. */ +interface CallMeta { + /** Workspace root that contains the call's path. */ + readonly root: string; + /** Path shown in diffs. */ + readonly display: string; + /** Paths a sandboxed bash may never write. */ + readonly denyWrite: readonly string[]; +} + +/** + * Literal paths from protected patterns that the OS sandbox can enforce: + * patterns without wildcards, and `dir/**` patterns as `dir`. + */ +function sandboxDenyWrite(patterns: readonly string[]): string[] { + const out: string[] = []; + for (const p of patterns) { + const base = p.endsWith('/**') ? p.slice(0, -3) : p; + if (!/[*?[]/.test(base) && path.isAbsolute(base)) out.push(base); + } + return out; +} + +/** Any failure of the runtime reaches the dispatcher as a `ToolError`. */ +function asToolError(err: unknown): ToolError { + if (err instanceof ToolError) return err; + const code = errnoCode(err); + if (code === 'ENAMETOOLONG') return new ToolError('invalid-args', `path is too long: ${errorMessage(err)}`); + if (code === 'ENOENT') return new ToolError('not-found', errorMessage(err)); + return new ToolError('tool-error', errorMessage(err)); +} + +function assertContainmentShape(c: BashContainment): void { + if (c.mode === 'sandbox' && c.writableRoots.some((r) => !path.isAbsolute(r))) { + throw new ToolError('containment-unavailable', 'bash containment has a writable root that is not absolute'); + } +} + +/** + * The real `ToolRuntime`: workspace jail, tolerant edit, atomic writes with + * stale checks, transactional rollback, and contained `bash`. + */ +export class NodeToolRuntime implements ToolRuntime { + readonly #opts: NodeToolRuntimeOptions; + readonly #meta = new WeakMap(); + + constructor(opts: NodeToolRuntimeOptions) { + this.#opts = opts; + } + + async prepare(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot): Promise { + try { + return await this.#prepareInJail(call, ctx, policy); + } catch (err) { + throw asToolError(err); + } + } + + async #prepareInJail(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot): Promise { + const jail = await Jail.create({ + cwd: ctx.cwd, + roots: [...ctx.roots, ...(this.#opts.additionalRoots ?? [])], + protectedPaths: policy.protectedPaths, + }); + const meta = (abs: string, denyWrite: readonly string[] = []): CallMeta => ({ + root: jail.rootOf(abs) ?? jail.cwd, + display: jail.displayPath(abs), + denyWrite, + }); + return this.#prepare(call, jail, policy, meta); + } + + async #prepare( + call: ToolCall, + jail: Jail, + policy: PolicySnapshot, + meta: (abs: string, denyWrite?: readonly string[]) => CallMeta, + ): Promise { + switch (call.tool) { + case 'bash': { + if (findBash() === null) { + throw new ToolError('tool-error', process.platform === 'win32' ? 'bash requires Git Bash, which was not found' : 'bash was not found'); + } + let cwd = jail.cwd; + if (call.args.cwd !== undefined) { + cwd = await jail.resolve(call.args.cwd); + const st = await fs.stat(cwd).catch(() => null); + if (!st) throw new ToolError('not-found', `bash cwd ${call.args.cwd} does not exist`); + if (!st.isDirectory()) throw new ToolError('invalid-args', `bash cwd ${call.args.cwd} is not a directory`); + } + // What hooks see is exactly what runs: another cwd becomes part of the command. + const command = cwd === jail.cwd ? call.args.command : `cd -- ${shellQuote(cwd)} && ${call.args.command}`; + const timeoutMs = Math.min(call.args.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS); + const containment = policy.bashContainment; + assertContainmentShape(containment); + if (containment.mode === 'sandbox') { + const reason = await containmentUnavailableReason(); + if (reason !== null) throw new ToolError('containment-unavailable', reason); + } + const prepared: PreparedCallOf<'bash'> = { + id: call.id, + tool: 'bash', + args: { command, timeoutMs }, + effect: { command, cwd: jail.cwd, timeoutMs, containment }, + }; + this.#meta.set(prepared, meta(jail.cwd, sandboxDenyWrite(jail.protectedPaths))); + return prepared; + } + case 'read': { + const absPath = await jail.resolve(call.args.path); + await this.#assertFile(absPath, call.args.path); + const offset = call.args.offset ?? 1; + const limit = call.args.limit ?? DEFAULT_READ_LIMIT; + const prepared: PreparedCallOf<'read'> = { + id: call.id, + tool: 'read', + args: { path: absPath, offset, limit }, + effect: { absPath, offset, limit }, + }; + this.#meta.set(prepared, meta(absPath)); + return prepared; + } + case 'write': { + const absPath = await jail.resolve(call.args.path); + jail.assertWritable(absPath); + const m = meta(absPath); + const current = await this.#readExisting(absPath); + const diff = + current !== null && isBinary(current.bytes) + ? binaryDiff(m.display, true) + : unifiedDiff(m.display, current === null ? null : current.bytes.toString('utf8'), call.args.content); + const prepared: PreparedCallOf<'write'> = { + id: call.id, + tool: 'write', + args: { path: absPath, content: call.args.content }, + effect: { + absPath, + beforeHash: current === null ? null : sha256(current.bytes), + afterContent: call.args.content, + diff, + }, + }; + this.#meta.set(prepared, m); + return prepared; + } + case 'edit': { + const absPath = await jail.resolve(call.args.path); + jail.assertWritable(absPath); + const m = meta(absPath); + const current = await this.#readExisting(absPath); + if (current === null) throw new ToolError('not-found', `${m.display} does not exist`); + const text = decodeText(m.display, current.bytes); + if (call.args.oldString === call.args.newString) { + throw new ToolError('invalid-args', 'oldString and newString are the same; the edit would change nothing'); + } + const outcome = applySearchReplace(text, call.args.oldString, call.args.newString, call.args.replaceAll === true); + if (!outcome.ok) { + const code = outcome.kind === 'not-found' ? 'not-found' : 'invalid-args'; + throw new ToolError(code, `${m.display}: ${outcome.message}`); + } + const prepared: PreparedCallOf<'edit'> = { + id: call.id, + tool: 'edit', + args: { ...call.args, path: absPath }, + effect: { + absPath, + beforeHash: sha256(current.bytes), + afterContent: outcome.text, + diff: unifiedDiff(m.display, text, outcome.text), + matchedOldString: outcome.matched, + matchStrategy: STRATEGY[outcome.how], + replacements: outcome.count, + }, + }; + this.#meta.set(prepared, m); + return prepared; + } + case 'grep': { + const absRoot = await jail.resolve(call.args.path ?? '.'); + await this.#assertExists(absRoot, call.args.path ?? '.'); + const ignoreCase = call.args.ignoreCase ?? false; + compileGrep(call.args.pattern, ignoreCase); + const effect = { + absRoot, + pattern: call.args.pattern, + glob: call.args.glob ?? null, + ignoreCase, + maxResults: call.args.maxResults ?? DEFAULT_GREP_MAX_RESULTS, + }; + const prepared: PreparedCallOf<'grep'> = { id: call.id, tool: 'grep', args: { ...call.args, path: absRoot }, effect }; + this.#meta.set(prepared, meta(absRoot)); + return prepared; + } + case 'glob': { + const absRoot = await jail.resolve(call.args.path ?? '.'); + const st = await this.#assertExists(absRoot, call.args.path ?? '.'); + if (!st.isDirectory()) throw new ToolError('invalid-args', `glob path ${call.args.path ?? '.'} is not a directory`); + normalizeGlob(call.args.pattern, absRoot); + const effect = { absRoot, pattern: call.args.pattern, maxResults: call.args.maxResults ?? DEFAULT_GLOB_MAX_RESULTS }; + const prepared: PreparedCallOf<'glob'> = { id: call.id, tool: 'glob', args: { ...call.args, path: absRoot }, effect }; + this.#meta.set(prepared, meta(absRoot)); + return prepared; + } + } + } + + async #assertExists(abs: string, shown: string): Promise { + const st = await fs.lstat(abs).catch((err: unknown) => { + if (errnoCode(err) === 'ENOENT' || errnoCode(err) === 'ENOTDIR') return null; + throw new ToolError('tool-error', `cannot stat ${shown}: ${errnoCode(err) ?? String(err)}`); + }); + if (!st) throw new ToolError('not-found', `${shown} does not exist`); + return st; + } + + async #assertFile(abs: string, shown: string): Promise { + const st = await this.#assertExists(abs, shown); + if (st.isDirectory()) throw new ToolError('invalid-args', `${shown} is a directory`); + if (!st.isFile()) throw new ToolError('invalid-args', `${shown} is not a regular file`); + } + + async #readExisting(abs: string): Promise<{ bytes: Buffer; mode: number } | null> { + const st = await fs.lstat(abs).catch(() => null); + if (st?.isDirectory()) throw new ToolError('invalid-args', `${abs} is a directory`); + return readRegularFile(abs, MAX_FILE_BYTES); + } + + #metaOf(prepared: PreparedCall, fallbackPath: string): CallMeta { + return this.#meta.get(prepared) ?? { root: path.dirname(fallbackPath), display: fallbackPath, denyWrite: [] }; + } + + async commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { + try { + return await this.#commit(prepared, signal, tx); + } catch (err) { + throw asToolError(err); + } + } + + async #commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before commit'); + switch (prepared.tool) { + case 'bash': { + const m = this.#metaOf(prepared, prepared.effect.cwd); + return runBash(prepared.effect, signal, { + ...(this.#opts.bashOutputCapBytes !== undefined ? { outputCapBytes: this.#opts.bashOutputCapBytes } : {}), + denyWrite: m.denyWrite, + }); + } + case 'read': + return this.#commitRead(prepared); + case 'write': + case 'edit': + return this.#commitWrite(prepared, tx); + case 'grep': { + await assertDirUnchanged(prepared.effect.absRoot); + return runGrep(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal); + } + case 'glob': { + await assertDirUnchanged(prepared.effect.absRoot); + return runGlob(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal); + } + } + } + + async #commitRead(prepared: PreparedCallOf<'read'>): Promise { + const { absPath, offset, limit } = prepared.effect; + await assertDirUnchanged(path.dirname(absPath)); + const file = await readRegularFile(absPath, MAX_FILE_BYTES); + if (file === null) throw new ToolError('not-found', `${absPath} does not exist`); + const text = decodeText(absPath, file.bytes); + const lines = text === '' ? [] : text.split('\n'); + if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop(); + const window: string[] = []; + let bytes = 0; + let truncated = false; + for (let i = offset - 1; i < lines.length && window.length < limit; i++) { + const line = lines[i] ?? ''; + const size = Buffer.byteLength(line, 'utf8') + 1; + if (bytes + size > READ_CAP_BYTES) { + truncated = true; + break; + } + window.push(line); + bytes += size; + } + if (offset - 1 + window.length < lines.length) truncated = true; + return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated }; + } + + async #commitWrite(prepared: PreparedCallOf<'write'> | PreparedCallOf<'edit'>, tx: Transaction | undefined): Promise { + if (tx !== undefined && !(tx instanceof FileTransaction)) { + throw new ToolError('tool-error', 'the transaction was not started by this tool runtime; refusing to write without a journal'); + } + const { absPath, beforeHash, afterContent } = prepared.effect; + const m = this.#metaOf(prepared, absPath); + const bytes = Buffer.from(afterContent, 'utf8'); + const nextHash = sha256(bytes); + const outcome = await atomicWrite( + absPath, + bytes, + beforeHash === null ? { kind: 'absent' } : { kind: 'hash', sha256: beforeHash }, + tx ? (before, createdDirs) => tx.record(absPath, m.root, before, nextHash, createdDirs) : undefined, + ); + tx?.written(absPath, nextHash); + if (prepared.tool === 'write') return { path: absPath, created: outcome.before === null, diff: prepared.effect.diff }; + return { + path: absPath, + replacements: prepared.effect.replacements, + matchStrategy: prepared.effect.matchStrategy, + diff: prepared.effect.diff, + }; + } + + beginTransaction(): Transaction { + return new FileTransaction(this.#opts.stateDir); + } +} diff --git a/src/tools/sandbox.ts b/src/tools/sandbox.ts new file mode 100644 index 0000000..f09c201 --- /dev/null +++ b/src/tools/sandbox.ts @@ -0,0 +1,133 @@ +import { ToolError, errorMessage } from '../core/errors.js'; +import type { BashContainment } from '../core/types.js'; + +/** + * OS containment for `bash` through `@anthropic-ai/sandbox-runtime` + * (bubblewrap on Linux, Seatbelt on macOS). The library keeps one global + * configuration and one network proxy per process, so this module owns it: + * it is initialized once, lazily, with no network allowed, and each command + * passes its own filesystem rules. + * + * Network: the library routes all traffic through its proxy and refuses an + * allow-everything domain list, so "network on" is implemented with the + * library's ask callback, which allows a host only while a network-enabled + * command holds the sandbox. Sandboxed commands are therefore serialized in + * this process, so a network-off command never runs while the gate is open. + * On Linux the command has no network namespace of its own either way: with + * network on, only clients that honor the proxy variables the library sets + * (curl, git, npm, ...) reach the network; raw sockets never do. + */ + +type SandboxModule = typeof import('@anthropic-ai/sandbox-runtime'); +type Manager = SandboxModule['SandboxManager']; + +let loading: Promise | undefined; +let networkOpen = false; +let tail: Promise = Promise.resolve(); + +/** Why containment is unavailable on this machine, or null when it is available. */ +let availability: Promise | undefined; + +async function loadManager(): Promise { + const mod: SandboxModule = await import('@anthropic-ai/sandbox-runtime'); + return mod.SandboxManager; +} + +/** Returns null when OS containment can be enforced here, else the reason. Cached. */ +export function containmentUnavailableReason(): Promise { + availability ??= (async () => { + if (process.platform !== 'linux' && process.platform !== 'darwin') { + return `bash containment is not supported on ${process.platform}`; + } + try { + const manager = await loadManager(); + if (!manager.isSupportedPlatform()) return 'the sandbox runtime does not support this platform'; + const check = manager.checkDependencies(); + if (check.errors.length > 0) return `sandbox dependencies missing: ${check.errors.join('; ')}`; + return null; + } catch (err) { + return `sandbox runtime failed to load: ${errorMessage(err)}`; + } + })(); + return availability; +} + +async function manager(): Promise { + loading ??= (async () => { + const m = await loadManager(); + await m.initialize( + { network: { allowedDomains: [], deniedDomains: [] }, filesystem: { denyRead: [], allowWrite: [], denyWrite: [] } }, + async () => networkOpen, + ); + return m; + })(); + try { + return await loading; + } catch (err) { + loading = undefined; + throw err; + } +} + +/** A command wrapped for the sandbox. */ +export interface WrappedCommand { + readonly argv: readonly string[]; + readonly env: NodeJS.ProcessEnv; +} + +/** + * Runs `fn` with `command` wrapped for `containment`. Sandboxed commands are + * serialized in this process (see the module comment). `denyWrite` adds + * paths the command may never write even inside a writable root. + */ +export function withSandbox( + command: string, + shell: string, + cwd: string, + containment: Extract, + denyWrite: readonly string[], + fn: (wrapped: WrappedCommand) => Promise, +): Promise { + const run = async (): Promise => { + const reason = await containmentUnavailableReason(); + if (reason !== null) throw new ToolError('containment-unavailable', reason); + let m: Manager; + try { + m = await manager(); + } catch (err) { + throw new ToolError('containment-unavailable', `sandbox runtime failed to start: ${errorMessage(err)}`); + } + let wrapped: WrappedCommand; + try { + wrapped = await m.wrapWithSandboxArgv( + command, + shell, + { + filesystem: { + denyRead: [], + allowWrite: containment.readOnly ? [] : [...containment.writableRoots], + denyWrite: [...denyWrite], + }, + }, + undefined, + cwd, + ); + } catch (err) { + throw new ToolError('containment-unavailable', `sandbox runtime could not wrap the command: ${errorMessage(err)}`); + } + networkOpen = containment.network; + try { + return await fn(wrapped); + } finally { + networkOpen = false; + try { + m.cleanupAfterCommand(); + } catch { + // Cleanup is best effort. + } + } + }; + const next = tail.then(run, run); + tail = next.catch(() => undefined); + return next; +} diff --git a/src/tools/search.ts b/src/tools/search.ts new file mode 100644 index 0000000..7208018 --- /dev/null +++ b/src/tools/search.ts @@ -0,0 +1,338 @@ +import { constants as FS } from 'node:fs'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import { DEFAULT_CASE_INSENSITIVE, matchesPathPattern } from '../core/paths.js'; +import type { GlobEffect, GlobResult, GrepEffect, GrepMatch, GrepResult } from '../core/types.js'; + +/** Default `grep` result count. */ +export const DEFAULT_GREP_MAX_RESULTS = 500; +/** Default `glob` result count. */ +export const DEFAULT_GLOB_MAX_RESULTS = 1000; +/** Longest matching line returned by `grep`. */ +const MAX_LINE_CHARS = 2000; +/** Files larger than this are not searched by `grep`. */ +const MAX_GREP_FILE_BYTES = 16 * 1024 * 1024; +/** Upper bound of directory entries visited by one call. */ +const MAX_VISITED = 500_000; + +const ALWAYS_IGNORED = new Set(['.git', 'node_modules']); + +// --------------------------------------------------------------------------- +// gitignore +// --------------------------------------------------------------------------- + +interface IgnoreRule { + readonly re: RegExp; + readonly negate: boolean; + readonly dirOnly: boolean; +} + +function globToRegExpSource(glob: string): string { + let src = ''; + for (let i = 0; i < glob.length; i++) { + const ch = glob[i] ?? ''; + if (ch === '\\' && i + 1 < glob.length) { + src += (glob[++i] ?? '').replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); + } else if (ch === '*') { + if (glob[i + 1] === '*') { + const prevSlash = i === 0 || glob[i - 1] === '/'; + const nextSlash = glob[i + 2] === '/' || i + 2 === glob.length; + if (prevSlash && nextSlash) { + if (i + 2 === glob.length) src += '.*'; + else { + src += '(?:.*/)?'; + i++; + } + i++; + continue; + } + i++; + } + src += '[^/]*'; + } else if (ch === '?') { + src += '[^/]'; + } else if (ch === '[') { + const close = glob.indexOf(']', i + 1); + if (close === -1) src += '\\['; + else { + let body = glob.slice(i + 1, close); + if (body.startsWith('!')) body = `^${body.slice(1)}`; + src += `[${body.replace(/\\/g, '\\\\')}]`; + i = close; + } + } else { + src += ch.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); + } + } + return src; +} + +/** Parses a `.gitignore` file. Patterns are relative to the directory holding it. */ +export function parseGitignore(text: string): IgnoreRule[] { + const rules: IgnoreRule[] = []; + for (const rawLine of text.split(/\r?\n/)) { + let line = rawLine.replace(/(? 0 && !matchedParent; i--) { + if (rule.re.test(parts.slice(0, i).join('/'))) matchedParent = true; + } + if (matchedParent) ignored = !rule.negate; + continue; + } + if (rule.re.test(rel)) ignored = !rule.negate; + } + } + return ignored; +} + +async function loadIgnore(dir: string): Promise { + try { + const handle = await fs.open(path.join(dir, '.gitignore'), FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0)); + try { + const st = await handle.stat(); + if (!st.isFile() || st.size > 1024 * 1024) return null; + return { base: dir, rules: parseGitignore(await handle.readFile('utf8')) }; + } finally { + await handle.close(); + } + } catch { + return null; + } +} + +/** `.gitignore` layers of the directories from `top` down to `dir` (inclusive). */ +async function ancestorLayers(top: string, dir: string): Promise { + const chain: string[] = []; + let cursor = dir; + for (;;) { + chain.push(cursor); + if (cursor === top) break; + const parent = path.dirname(cursor); + if (parent === cursor || path.relative(top, parent).startsWith('..')) break; + cursor = parent; + } + const layers: IgnoreLayer[] = []; + for (const d of chain.reverse()) { + const layer = await loadIgnore(d); + if (layer) layers.push(layer); + } + return layers; +} + +// --------------------------------------------------------------------------- +// Walking +// --------------------------------------------------------------------------- + +/** + * Lists regular files below `absRoot` (real path, inside the jail), sorted, + * skipping `.git`, `node_modules` and gitignored entries. Symbolic links are + * never followed, whether they point inside or outside the workspace. + * `jailRoot` is the workspace root above it whose `.gitignore` files apply. + */ +async function* walkFiles(absRoot: string, jailRoot: string, signal: AbortSignal): AsyncGenerator { + const rootStat = await fs.lstat(absRoot); + if (rootStat.isFile()) { + yield absRoot; + return; + } + if (!rootStat.isDirectory()) return; + const startLayers = await ancestorLayers(jailRoot, absRoot); + let visited = 0; + const stack: { dir: string; layers: IgnoreLayer[] }[] = [{ dir: absRoot, layers: startLayers }]; + while (stack.length > 0) { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped'); + const { dir, layers } = stack.pop() as { dir: string; layers: IgnoreLayer[] }; + let entries: import('node:fs').Dirent[]; + try { + entries = await fs.readdir(dir, { withFileTypes: true }); + } catch { + continue; + } + const own = dir === absRoot ? null : await loadIgnore(dir); + const here = own ? [...layers, own] : layers; + entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const subdirs: string[] = []; + for (const entry of entries) { + if (++visited > MAX_VISITED) throw new ToolError('tool-error', `too many files under ${absRoot} (more than ${MAX_VISITED}); narrow the path`); + const abs = path.join(dir, entry.name); + if (entry.isSymbolicLink()) continue; + if (entry.isDirectory()) { + if (ALWAYS_IGNORED.has(entry.name)) continue; + if (isIgnored(here, abs, true)) continue; + subdirs.push(abs); + } else if (entry.isFile()) { + if (isIgnored(here, abs, false)) continue; + yield abs; + } + } + // Depth first, in name order: push in reverse so the first name pops first. + // Files of a directory come before its subdirectories' files. + for (const sub of subdirs.reverse()) stack.push({ dir: sub, layers: here }); + } +} + +// --------------------------------------------------------------------------- +// Patterns +// --------------------------------------------------------------------------- + +/** Expands `{a,b}` alternations (nested allowed, at most 256 results). */ +export function expandBraces(pattern: string): string[] { + const open = pattern.indexOf('{'); + if (open === -1) return [pattern]; + let depth = 0; + let close = -1; + const commas: number[] = []; + for (let i = open; i < pattern.length; i++) { + const ch = pattern[i]; + if (ch === '{') depth++; + else if (ch === '}') { + depth--; + if (depth === 0) { + close = i; + break; + } + } else if (ch === ',' && depth === 1) commas.push(i); + } + if (close === -1 || commas.length === 0) return [pattern]; + const head = pattern.slice(0, open); + const tail = pattern.slice(close + 1); + const cuts = [open, ...commas, close]; + const out: string[] = []; + for (let i = 0; i + 1 < cuts.length; i++) { + const alt = pattern.slice((cuts[i] ?? 0) + 1, cuts[i + 1]); + for (const expanded of expandBraces(head + alt + tail)) { + out.push(expanded); + if (out.length >= 256) return out; + } + } + return out; +} + +/** Normalizes a glob pattern given relative to `absRoot`; refuses patterns that leave it. */ +export function normalizeGlob(pattern: string, absRoot: string): string { + let p = pattern.replace(/\\/g, '/'); + const rootFwd = absRoot.replace(/\\/g, '/'); + if (p.startsWith(`${rootFwd}/`)) p = p.slice(rootFwd.length + 1); + else if (p.startsWith('/') || /^[A-Za-z]:\//.test(p)) { + throw new ToolError('invalid-args', `glob pattern ${pattern} is absolute and not under ${absRoot}; pass the directory as path and a relative pattern`); + } + if (p.startsWith('./')) p = p.slice(2); + if (p.split('/').includes('..')) throw new ToolError('invalid-args', `glob pattern ${pattern} must not contain ..`); + return p; +} + +function toRel(absRoot: string, abs: string): string { + return path.relative(absRoot, abs).split(path.sep).join('/'); +} + +// --------------------------------------------------------------------------- +// grep and glob +// --------------------------------------------------------------------------- + +/** Compiles a grep pattern (JavaScript RegExp syntax). */ +export function compileGrep(pattern: string, ignoreCase: boolean): RegExp { + try { + return new RegExp(pattern, ignoreCase ? 'i' : ''); + } catch (err) { + throw new ToolError('invalid-args', `invalid regular expression ${JSON.stringify(pattern)}: ${err instanceof Error ? err.message : String(err)}`); + } +} + +function matchesFileGlob(rel: string, globs: readonly string[]): boolean { + const base = rel.slice(rel.lastIndexOf('/') + 1); + return globs.some((g) => (g.includes('/') ? matchesPathPattern(rel, g) : matchesPathPattern(base, g))); +} + +export async function runGrep(effect: GrepEffect, jailRoot: string, signal: AbortSignal): Promise { + const re = compileGrep(effect.pattern, effect.ignoreCase); + const globs = effect.glob === null ? null : expandBraces(effect.glob.replace(/\\/g, '/')); + const matches: GrepMatch[] = []; + let truncated = false; + for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { + if (globs && file !== effect.absRoot && !matchesFileGlob(toRel(effect.absRoot, file), globs)) continue; + let bytes: Buffer; + try { + const handle = await fs.open(file, FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0)); + try { + const st = await handle.stat(); + if (!st.isFile() || st.size > MAX_GREP_FILE_BYTES) continue; + bytes = await handle.readFile(); + } finally { + await handle.close(); + } + } catch { + continue; + } + if (bytes.subarray(0, 8192).includes(0)) continue; + const lines = bytes.toString('utf8').split('\n'); + for (let i = 0; i < lines.length; i++) { + let text = lines[i] ?? ''; + if (text.endsWith('\r')) text = text.slice(0, -1); + if (i === lines.length - 1 && text === '') break; + if (!re.test(text)) continue; + if (matches.length >= effect.maxResults) { + truncated = true; + return { matches, truncated }; + } + matches.push({ file, line: i + 1, text: text.length > MAX_LINE_CHARS ? `${text.slice(0, MAX_LINE_CHARS)}…` : text }); + } + } + return { matches, truncated }; +} + +export async function runGlob(effect: GlobEffect, jailRoot: string, signal: AbortSignal): Promise { + const patterns = expandBraces(normalizeGlob(effect.pattern, effect.absRoot)); + const all: string[] = []; + for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { + if (file === effect.absRoot) continue; + const rel = toRel(effect.absRoot, file); + if (patterns.some((p) => matchesPathPattern(rel, p))) all.push(file); + } + all.sort(); + return { files: all.slice(0, effect.maxResults), truncated: all.length > effect.maxResults }; +} + From 8e8a3f0cd07865a875fa825c858e692db836411a Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:31:01 -0300 Subject: [PATCH 02/43] Match protected patterns written through an alias of the workspace Protected path patterns are built by the host adapter from the session cwd as the host spells it. Paths are checked as real paths, so a cwd reached through a symlink, macOS /var or a Windows 8.3 short name made the patterns miss. Each pattern now also matches with its literal prefix resolved. Tests use native real paths so they agree with the runtime on Windows. Co-Authored-By: Claude Opus 5.5 --- src/tools/bash.test.ts | 2 +- src/tools/diff.test.ts | 2 +- src/tools/integration.test.ts | 2 +- src/tools/jail.ts | 35 ++++++++++++++++++++++++++++++++++- src/tools/journal.test.ts | 2 +- src/tools/runtime.test.ts | 20 +++++++++++++++++--- 6 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src/tools/bash.test.ts b/src/tools/bash.test.ts index 0806edf..fdccf1b 100644 --- a/src/tools/bash.test.ts +++ b/src/tools/bash.test.ts @@ -53,7 +53,7 @@ async function eventually(check: () => boolean, ms = 3000): Promise { } beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-bash-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-bash-'))); ws = path.join(base, 'ws'); mkdirSync(ws); ctx = makeContext(ws); diff --git a/src/tools/diff.test.ts b/src/tools/diff.test.ts index f595a2f..d6e72f1 100644 --- a/src/tools/diff.test.ts +++ b/src/tools/diff.test.ts @@ -13,7 +13,7 @@ function gitApply(before: string | null, diff: string): string { try { if (before !== null) writeFileSync(path.join(dir, 'f.txt'), before); writeFileSync(path.join(dir, 'p.diff'), diff); - const r = spawnSync('git', ['apply', '--unsafe-paths', '--whitespace=nowarn', 'p.diff'], { cwd: dir, encoding: 'utf8' }); + const r = spawnSync('git', ['-c', 'core.autocrlf=false', 'apply', '--unsafe-paths', '--whitespace=nowarn', 'p.diff'], { cwd: dir, encoding: 'utf8' }); if (r.status !== 0) throw new Error(`git apply failed: ${r.stderr}\n${diff}`); return readFileSync(path.join(dir, 'f.txt'), 'utf8'); } finally { diff --git a/src/tools/integration.test.ts b/src/tools/integration.test.ts index 971200f..74f8933 100644 --- a/src/tools/integration.test.ts +++ b/src/tools/integration.test.ts @@ -11,7 +11,7 @@ let base: string; let ws: string; beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-int-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-int-'))); ws = path.join(base, 'ws'); mkdirSync(ws); writeFileSync(path.join(ws, 'a.txt'), 'alpha\n'); diff --git a/src/tools/jail.ts b/src/tools/jail.ts index 28784b3..7d3a64d 100644 --- a/src/tools/jail.ts +++ b/src/tools/jail.ts @@ -112,6 +112,39 @@ export function isInsideGitDir(absPath: string): boolean { }); } +/** + * Adds, for each pattern, the same pattern with its literal directory prefix + * replaced by that directory's real path. Paths are checked as real paths, so + * a pattern written through an alias of the workspace (a symlinked cwd, + * macOS `/var` vs `/private/var`, a Windows 8.3 short name) must match too. + */ +async function withRealPrefixes(patterns: readonly string[]): Promise { + const out = new Set(patterns); + for (const pattern of patterns) { + const fwd = pattern.replace(/\\/g, '/'); + const wild = fwd.search(/[*?[]/); + const literal = wild === -1 ? fwd : fwd.slice(0, wild); + const cut = literal.lastIndexOf('/'); + if (cut <= 0) continue; + // Resolve the deepest existing directory of the literal prefix. + let dir = fwd.slice(0, cut); + let rest = fwd.slice(cut); + for (;;) { + try { + const real = (await fs.realpath(dir)).replace(/\\/g, '/'); + if (real !== dir) out.add(real + rest); + break; + } catch { + const up = dir.lastIndexOf('/'); + if (up <= 0 || /^[A-Za-z]:$/.test(dir.slice(0, up))) break; + rest = dir.slice(up) + rest; + dir = dir.slice(0, up); + } + } + } + return [...out]; +} + export interface JailOptions { /** Absolute directory relative paths resolve against. */ readonly cwd: string; @@ -157,7 +190,7 @@ export class Jail { // A root that does not exist grants nothing. } } - const protectedPaths = opts.protectedPaths.map((p) => expandTilde(p)); + const protectedPaths = await withRealPrefixes(opts.protectedPaths.map((p) => expandTilde(p))); return new Jail(cwd, roots, protectedPaths, opts.windowsChecks ?? IS_WINDOWS); } diff --git a/src/tools/journal.test.ts b/src/tools/journal.test.ts index 7e857c7..91bf991 100644 --- a/src/tools/journal.test.ts +++ b/src/tools/journal.test.ts @@ -33,7 +33,7 @@ function deadPid(): number { } beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-journal-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-journal-'))); ws = path.join(base, 'ws'); outside = path.join(base, 'outside'); stateDir = path.join(base, 'state'); diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts index 15912e7..f21deff 100644 --- a/src/tools/runtime.test.ts +++ b/src/tools/runtime.test.ts @@ -64,7 +64,7 @@ function link(target: string, at: string): void { } beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-tools-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-tools-'))); ws = path.join(base, 'ws'); outside = path.join(base, 'outside'); mkdirSync(ws); @@ -106,8 +106,12 @@ describe('path traversal', () => { expect(await code(prep('write', { path: 'a\0b', content: 'x' }))).toBe('invalid-args'); const long = `${'a'.repeat(250)}/`.repeat(40) + 'f.txt'; const result = await code(run('write', { path: long, content: 'x' })); - expect(['invalid-args', 'tool-error']).toContain(result); - expect(readdirSync(ws)).toEqual([]); + // Windows with long-path support accepts it; it must then be inside the workspace. + if (result === 'resolved') expect(readFileSync(path.join(ws, long), 'utf8')).toBe('x'); + else { + expect(['invalid-args', 'tool-error']).toContain(result); + expect(readdirSync(ws)).toEqual([]); + } }); it('keeps unicode lookalikes of .. inside the workspace', async () => { @@ -219,6 +223,16 @@ describe('protected paths', () => { expect(readFileSync(path.join(ws, '.git', 'config'), 'utf8')).toBe('[core]\n'); }); + it.skipIf(IS_WINDOWS)('matches patterns written through an alias of the workspace', async () => { + const alias = path.join(base, 'alias'); + link(ws, alias); + const aliasCtx = makeContext(alias); + const p = { ...policy, protectedPaths: [`${alias}/.claude/settings*.json`, `${alias}/.codex/**`] }; + expect(await code(rt.prepare(call('write', { path: '.claude/settings.json', content: '{}' }), aliasCtx, p))).toBe('protected-path'); + expect(await code(rt.prepare(call('write', { path: '.codex/config.toml', content: '' }), aliasCtx, p))).toBe('protected-path'); + expect(await code(rt.prepare(call('write', { path: 'ok.txt', content: '' }), aliasCtx, p))).toBe('resolved'); + }); + it('expands ~ in protected patterns', async () => { const home = path.join(ws, 'home'); mkdirSync(home); From 7c10018aa44dd0342ad2f8a3cb45290ba767e1d9 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:32:00 -0300 Subject: [PATCH 03/43] Add the QuickJS-ng WASM sandbox Runs each script in a fresh Node child process (empty env, bounded heap, Node permission model) that hosts a QuickJS-ng VM from the sync WASM build. Bindings are deferred promises settled by the parent's replies; the parent validates every child message and kills the child on anything unexpected, on timeout and on cancel. The WASM memory maximum is the real heap limit, because QuickJS-ng's own accounting undercounts in this build. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 26 ++ package.json | 2 + src/sandbox/child.ts | 632 ++++++++++++++++++++++++++++ src/sandbox/index.ts | 1 + src/sandbox/protocol.ts | 88 ++++ src/sandbox/quickjs-sandbox.test.ts | 503 ++++++++++++++++++++++ src/sandbox/quickjs-sandbox.ts | 208 +++++++++ src/sandbox/session.test.ts | 202 +++++++++ src/sandbox/session.ts | 200 +++++++++ 9 files changed, 1862 insertions(+) create mode 100644 src/sandbox/child.ts create mode 100644 src/sandbox/index.ts create mode 100644 src/sandbox/protocol.ts create mode 100644 src/sandbox/quickjs-sandbox.test.ts create mode 100644 src/sandbox/quickjs-sandbox.ts create mode 100644 src/sandbox/session.test.ts create mode 100644 src/sandbox/session.ts diff --git a/package-lock.json b/package-lock.json index 596f70d..8dca43c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,9 @@ "version": "0.0.0", "license": "Apache-2.0", "dependencies": { + "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0", "@modelcontextprotocol/sdk": "^1.32.2", + "quickjs-emscripten-core": "^0.32.0", "zod": "^4.6.7" }, "bin": { @@ -73,6 +75,21 @@ "hono": "^4 || ^5.0.0-0" } }, + "node_modules/@jitl/quickjs-ffi-types": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-ffi-types/-/quickjs-ffi-types-0.32.0.tgz", + "integrity": "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg==", + "license": "MIT" + }, + "node_modules/@jitl/quickjs-ng-wasmfile-release-sync": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-ng-wasmfile-release-sync/-/quickjs-ng-wasmfile-release-sync-0.32.0.tgz", + "integrity": "sha512-XAX2jjZWWh3M0YaRqi82xMKNW/gkF6mo3MpW3UY2cmVxnQai1JuboVsJQVoLU629iEL4XWvHtO4h5lo7NRnAcg==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", @@ -2235,6 +2252,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/quickjs-emscripten-core": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/quickjs-emscripten-core/-/quickjs-emscripten-core-0.32.0.tgz", + "integrity": "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, "node_modules/range-parser": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", diff --git a/package.json b/package.json index 1d1997d..dd7b34e 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,9 @@ "bench": "node -e \"console.log('bench: not implemented yet')\"" }, "dependencies": { + "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0", "@modelcontextprotocol/sdk": "^1.32.2", + "quickjs-emscripten-core": "^0.32.0", "zod": "^4.6.7" }, "devDependencies": { diff --git a/src/sandbox/child.ts b/src/sandbox/child.ts new file mode 100644 index 0000000..9e1d16c --- /dev/null +++ b/src/sandbox/child.ts @@ -0,0 +1,632 @@ +/** + * Sandbox child process. Started by `QuickJsSandbox` for exactly one run with + * a minimal env, then killed. It reads newline-delimited JSON from stdin + * (`start`, then `reply`s), runs the script in a QuickJS-ng WASM VM (sync + * build) and writes `call`, `log` and `done` messages to stdout. + * + * Inside the VM the script sees only standard ECMAScript built-ins, `console` + * and the async bindings. Each binding call creates a QuickJS deferred promise + * that this process settles when the parent replies; pending jobs are then + * drained until the script's promise settles. + * + * This file has no runtime import of other project files (only `import type`), + * so Node can run it from source with type stripping during tests. + */ +import { newQuickJSWASMModuleFromVariant, newVariant, type QuickJSContext, type QuickJSDeferredPromise, type QuickJSHandle, type QuickJSRuntime, type QuickJSSyncVariant, type QuickJSWASMModule } from 'quickjs-emscripten-core'; +import * as variantModule from '@jitl/quickjs-ng-wasmfile-release-sync'; +import { z } from 'zod'; +import type { ChildMessage, SandboxLimits, StartMessage } from './protocol.js'; + +/** File name the script is compiled under; stack frames of the script carry it. */ +const SCRIPT_FILE = 'script.js'; +const SHIM_FILE = 'shim.js'; +const MAX_ERROR_CHARS = 10_000; +const WASM_PAGE_BYTES = 64 * 1024; + +/** The part of the WebAssembly API this file uses (the project's `lib` has no WebAssembly types). */ +interface WasmMemory { + readonly buffer: ArrayBuffer; +} +declare const WebAssembly: { readonly Memory: new (descriptor: { initial: number; maximum: number }) => WasmMemory }; +/** Initial memory of the WASM build (its INITIAL_MEMORY, 16 MiB). */ +const INITIAL_PAGES = 256; +/** Largest memory the WASM build declares (2 GiB). */ +const MAX_PAGES = 32_768; + +// --------------------------------------------------------------------------- +// Incoming messages (from the parent). Validated even though the parent is the +// trusted side: a malformed message ends the process. +// --------------------------------------------------------------------------- + +const int = z.number().int().positive(); +const LimitsSchema = z.strictObject({ + memoryBytes: int, + stackBytes: int, + maxCalls: int, + maxLogBytes: int, + maxLogLineChars: int, + maxResultChars: int, + maxArgsChars: int, +}); +const BindingErrorSchema = z.strictObject({ + name: z.enum(['PermissionDenied', 'ToolError']), + message: z.string(), + code: z.string(), + source: z.string().optional(), +}); +const ParentMessageSchema = z.discriminatedUnion('type', [ + z.strictObject({ type: z.literal('start'), code: z.string(), timeoutMs: z.number().positive(), limits: LimitsSchema }), + z.strictObject({ + type: z.literal('reply'), + id: int, + reply: z.discriminatedUnion('ok', [ + z.strictObject({ ok: z.literal(true), value: z.unknown() }), + z.strictObject({ ok: z.literal(false), error: BindingErrorSchema }), + ]), + }), +]); +type IncomingMessage = z.infer; + +function send(message: ChildMessage): void { + process.stdout.write(`${JSON.stringify(message)}\n`); +} + +function fatal(message: string): never { + process.stderr.write(`sandbox child: ${message}\n`); + process.exit(70); +} + +// --------------------------------------------------------------------------- +// In-VM shim. Evaluated before the script; its completion value is a function +// that receives the host natives (never exposed as globals), installs the +// bindings and `console`, and returns the runner. It captures the intrinsics +// it uses first, so a script that overrides `JSON.stringify` or +// `Promise.prototype.then` only breaks its own values. +// --------------------------------------------------------------------------- + +const SHIM = String.raw`(function (hostCall, hostLog, hostDone, maxResultChars, maxLogLineChars) { + 'use strict'; + var G = globalThis; + var stringify = JSON.stringify, parse = JSON.parse; + var apply = Reflect.apply; + var defineProperty = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var objectKeys = Object.keys, isArray = Array.isArray, numberIsFinite = Number.isFinite, objectIs = Object.is; + var promiseThen = Promise.prototype.then, promiseResolve = Promise.resolve, promiseReject = Promise.reject, PromiseCtor = Promise; + var ErrorCtor = Error, TypeErrorCtor = TypeError, StringCtor = String; + var symbolToString = Symbol.prototype.toString, stringSlice = String.prototype.slice, arrayJoin = Array.prototype.join; + var dateToISOString = Date.prototype.toISOString, DateCtor = Date, RegExpCtor = RegExp, MapCtor = Map, SetCtor = Set; + var regexpToString = RegExp.prototype.toString; + var mapForEach = Map.prototype.forEach, setForEach = Set.prototype.forEach; + var mapSize = getOwnPropertyDescriptor(Map.prototype, 'size').get, setSize = getOwnPropertyDescriptor(Set.prototype, 'size').get; + var identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/, regexpTest = RegExp.prototype.test; + + // Not ECMAScript: removed so the script sees only the standard library. + var extras = ['performance', 'DOMException', 'queueMicrotask']; + for (var x = 0; x < extras.length; x++) { try { delete G[extras[x]]; } catch (e) { /* keep going */ } } + + function push(list, item) { list[list.length] = item; } + function join(list, sep) { return apply(arrayJoin, list, [sep]); } + function cut(text, max) { return text.length > max ? apply(stringSlice, text, [0, max]) + '... [truncated]' : text; } + function isError(v) { try { return v instanceof ErrorCtor; } catch (e) { return false; } } + function safeString(v) { try { return StringCtor(v); } catch (e) { return '[unprintable value]'; } } + function fnName(f) { + try { var n = f.name; return typeof n === 'string' && n !== '' ? n : 'anonymous'; } catch (e) { return 'anonymous'; } + } + function messageOf(e) { try { return isError(e) ? safeString(e.message) : safeString(e); } catch (x) { return 'unknown error'; } } + function define(name, value) { defineProperty(G, name, { value: value, writable: true, enumerable: false, configurable: true }); } + + // ---- console: Node-like formatting, without running getters -------------- + function inspect(v, depth, seen, top) { + switch (typeof v) { + case 'string': return top ? v : "'" + v + "'"; + case 'number': return objectIs(v, -0) ? '-0' : StringCtor(v); + case 'bigint': return StringCtor(v) + 'n'; + case 'boolean': case 'undefined': return StringCtor(v); + case 'symbol': return apply(symbolToString, v, []); + case 'function': return '[Function: ' + fnName(v) + ']'; + } + if (v === null) return 'null'; + try { + for (var s = 0; s < seen.length; s++) if (seen[s] === v) return '[Circular]'; + if (isError(v)) return safeString(v.name) + ': ' + safeString(v.message); + if (v instanceof DateCtor) { try { return apply(dateToISOString, v, []); } catch (e) { return 'Invalid Date'; } } + if (v instanceof RegExpCtor) return apply(regexpToString, v, []); + var parts = []; + push(seen, v); + if (v instanceof MapCtor) { + if (depth > 2) { seen.length--; return '[Map]'; } + apply(mapForEach, v, [function (val, key) { push(parts, inspect(key, depth + 1, seen, false) + ' => ' + inspect(val, depth + 1, seen, false)); }]); + seen.length--; + return 'Map(' + apply(mapSize, v, []) + ') {' + (parts.length ? ' ' + join(parts, ', ') + ' ' : '') + '}'; + } + if (v instanceof SetCtor) { + if (depth > 2) { seen.length--; return '[Set]'; } + apply(setForEach, v, [function (val) { push(parts, inspect(val, depth + 1, seen, false)); }]); + seen.length--; + return 'Set(' + apply(setSize, v, []) + ') {' + (parts.length ? ' ' + join(parts, ', ') + ' ' : '') + '}'; + } + if (isArray(v)) { + if (depth > 2) { seen.length--; return '[Array]'; } + var n = v.length, shown = n > 100 ? 100 : n; + for (var i = 0; i < shown; i++) push(parts, inspect(v[i], depth + 1, seen, false)); + if (n > shown) push(parts, '... ' + (n - shown) + ' more items'); + seen.length--; + return parts.length ? '[ ' + join(parts, ', ') + ' ]' : '[]'; + } + if (depth > 2) { seen.length--; return '[Object]'; } + var keys = objectKeys(v), shownKeys = keys.length > 100 ? 100 : keys.length; + for (var k = 0; k < shownKeys; k++) { + var key = keys[k], d = getOwnPropertyDescriptor(v, key); + var label = apply(regexpTest, identifier, [key]) ? key : "'" + key + "'"; + var shownValue = d === undefined ? 'undefined' : 'value' in d ? inspect(d.value, depth + 1, seen, false) : '[Getter/Setter]'; + push(parts, label + ': ' + shownValue); + } + if (keys.length > shownKeys) push(parts, '... ' + (keys.length - shownKeys) + ' more properties'); + seen.length--; + return parts.length ? '{ ' + join(parts, ', ') + ' }' : '{}'; + } catch (e) { + return '[uninspectable: ' + messageOf(e) + ']'; + } + } + function logger(level) { + return function () { + var parts = []; + for (var i = 0; i < arguments.length; i++) push(parts, inspect(arguments[i], 0, [], true)); + hostLog(level, cut(join(parts, ' '), maxLogLineChars)); + }; + } + define('console', { log: logger('log'), info: logger('info'), warn: logger('warn'), error: logger('error') }); + + // ---- bindings ----------------------------------------------------------- + function bindingError(text) { + var info; + try { info = parse(text); } catch (e) { info = { name: 'ToolError', message: 'invalid binding error', code: 'tool-error' }; } + var err = new ErrorCtor(safeString(info.message)); + defineProperty(err, 'name', { value: safeString(info.name), writable: true, enumerable: false, configurable: true }); + defineProperty(err, 'code', { value: safeString(info.code), writable: true, enumerable: true, configurable: true }); + if (info.source !== undefined) { + defineProperty(err, 'source', { value: safeString(info.source), writable: true, enumerable: true, configurable: true }); + defineProperty(err, 'reason', { value: safeString(info.message), writable: true, enumerable: true, configurable: true }); + } + return err; + } + function invoke(tool, arg) { + var json; + try { json = stringify(arg); } catch (e) { + return apply(promiseReject, PromiseCtor, [new TypeErrorCtor(tool + ': the argument is not JSON-serializable: ' + messageOf(e))]); + } + if (json === undefined) json = 'null'; + return apply(promiseThen, hostCall(tool, json), [function (text) { return parse(text); }, function (text) { throw bindingError(text); }]); + } + var bindings = { + bash: function bash(arg) { return invoke('bash', typeof arg === 'string' ? { command: arg } : arg); }, + read: function read(arg) { return invoke('read', arg); }, + write: function write(arg) { return invoke('write', arg); }, + edit: function edit(arg) { return invoke('edit', arg); }, + grep: function grep(arg) { return invoke('grep', arg); }, + glob: function glob(arg) { return invoke('glob', arg); }, + }; + var names = objectKeys(bindings); + for (var b = 0; b < names.length; b++) define(names[b], bindings[names[b]]); + + // ---- return value: JSON, with non-JSON values described ----------------- + var tooLarge = {}; + function serialize(root) { + var out = [], size = 0, stack = []; + function emit(text) { + size += text.length; + if (size > maxResultChars) throw tooLarge; + push(out, text); + } + function value(v, key, inArray, depth) { + try { + if (v !== null && (typeof v === 'object' || typeof v === 'bigint') && typeof v.toJSON === 'function') v = v.toJSON(key); + } catch (e) { + if (e === tooLarge) throw e; + emit(stringify('[toJSON threw: ' + messageOf(e) + ']')); + return; + } + switch (typeof v) { + case 'string': emit(stringify(v)); return; + case 'number': emit(numberIsFinite(v) ? stringify(v) : stringify(StringCtor(v))); return; + case 'boolean': emit(v ? 'true' : 'false'); return; + case 'undefined': emit(inArray || depth === 0 ? 'null' : '"[undefined]"'); return; + case 'bigint': emit(stringify(StringCtor(v) + 'n')); return; + case 'symbol': emit(stringify(apply(symbolToString, v, []))); return; + case 'function': emit(stringify('[Function: ' + fnName(v) + ']')); return; + } + if (v === null) { emit('null'); return; } + for (var s = 0; s < stack.length; s++) if (stack[s] === v) { emit('"[Circular]"'); return; } + if (depth >= 200) { emit('"[Too deep]"'); return; } + try { + if (isError(v)) { emit(stringify(safeString(v.name) + ': ' + safeString(v.message))); return; } + push(stack, v); + if (isArray(v)) { + emit('['); + for (var i = 0, n = v.length; i < n; i++) { + if (i > 0) emit(','); + var item; + try { item = v[i]; } catch (e) { if (e === tooLarge) throw e; item = '[threw: ' + messageOf(e) + ']'; } + value(item, StringCtor(i), true, depth + 1); + } + emit(']'); + } else { + var keys = objectKeys(v), first = true; + emit('{'); + for (var k = 0; k < keys.length; k++) { + var prop; + try { prop = v[keys[k]]; } catch (e) { if (e === tooLarge) throw e; prop = '[threw: ' + messageOf(e) + ']'; } + if (prop === undefined) continue; + if (!first) emit(','); + first = false; + emit(stringify(keys[k]) + ':'); + value(prop, keys[k], false, depth + 1); + } + emit('}'); + } + stack.length--; + } catch (e) { + if (e === tooLarge) throw e; + throw new TypeErrorCtor('the return value cannot be serialized: ' + messageOf(e)); + } + } + value(root, '', false, 0); + return join(out, ''); + } + + // ---- runner --------------------------------------------------------------- + function errorInfo(e) { + var info; + if (isError(e)) { + var stack; + try { stack = e.stack; } catch (x) { stack = undefined; } + info = { name: safeString(e.name), message: safeString(e.message) }; + if (typeof stack === 'string') info.stack = stack; + } else { + info = { name: 'Error', message: typeof e === 'string' ? e : 'Uncaught ' + inspect(e, 0, [], false) }; + } + return stringify(info); + } + return function run(fn) { + var started; + try { started = typeof fn === 'function' ? fn() : fn; } catch (e) { hostDone('E' + errorInfo(e)); return; } + apply(promiseThen, apply(promiseResolve, PromiseCtor, [started]), [ + function (v) { + var text; + try { text = serialize(v); } catch (e) { + if (e === tooLarge) { + hostDone('E' + stringify({ name: 'ResultTooLarge', message: 'the return value is larger than ' + maxResultChars + ' characters of JSON; return less data' })); + return; + } + hostDone('E' + errorInfo(e)); + return; + } + hostDone('R' + text); + }, + function (e) { hostDone('E' + errorInfo(e)); }, + ]); + }; +})`; + +// --------------------------------------------------------------------------- +// One run. +// --------------------------------------------------------------------------- + +type DoneOutcome = Extract['outcome']; + +interface ErrorInfo { + readonly name: string; + readonly message: string; + readonly stack?: string; +} + +const LooseErrorSchema = z.object({ name: z.string(), message: z.string(), stack: z.string().optional() }); + +/** Keeps only the stack frames of the script itself. */ +function trimStack(stack: string | undefined): string | undefined { + if (stack === undefined) return undefined; + const frames = stack.split('\n').filter((line) => line.includes(`${SCRIPT_FILE}:`)); + return frames.length > 0 ? frames.join('\n').slice(0, MAX_ERROR_CHARS) : undefined; +} + +function toErrorInfo(raw: unknown): ErrorInfo { + const parsed = LooseErrorSchema.safeParse(raw); + if (!parsed.success) return { name: 'Error', message: typeof raw === 'string' ? raw.slice(0, MAX_ERROR_CHARS) : 'unknown error' }; + const stack = trimStack(parsed.data.stack); + const base = { name: parsed.data.name.slice(0, 200), message: parsed.data.message.slice(0, MAX_ERROR_CHARS) }; + return stack === undefined ? base : { ...base, stack }; +} + +function isOutOfMemory(info: ErrorInfo): boolean { + return /out of memory/i.test(info.message); +} + +/** + * The WASM memory of one run. QuickJS-ng's own accounting + * (`runtime.setMemoryLimit`) undercounts in this WASM build because + * `malloc_usable_size` is unavailable, so the hard limit is the maximum of + * the WebAssembly memory itself: past it, allocations fail and QuickJS throws + * "out of memory". + */ +/** + * The variant package's types describe its CommonJS entry, while Node loads + * its ESM entry, whose default export is the variant itself. Checked at + * runtime instead of cast. + */ +function syncVariant(candidate: unknown): QuickJSSyncVariant { + if (typeof candidate === 'object' && candidate !== null && 'type' in candidate && candidate.type === 'sync' && 'importFFI' in candidate && 'importModuleLoader' in candidate) { + return candidate as QuickJSSyncVariant; + } + if (typeof candidate === 'object' && candidate !== null && 'default' in candidate) return syncVariant(candidate.default); + throw new Error('the QuickJS variant package did not load as expected'); +} + +function runMemory(memoryBytes: number): WasmMemory { + const maximum = Math.min(MAX_PAGES, INITIAL_PAGES + Math.ceil(memoryBytes / WASM_PAGE_BYTES)); + return new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum }); +} + +class VmRun { + readonly #rt: QuickJSRuntime; + readonly #ctx: QuickJSContext; + readonly #limits: SandboxLimits; + readonly #deadline: number; + readonly #pending = new Map(); + readonly #timer: NodeJS.Timeout; + readonly #memory: WasmMemory; + readonly #memoryMaxBytes: number; + #nextId = 1; + #logBytes = 0; + #logCapped = false; + #done = false; + + constructor(qjs: QuickJSWASMModule, memory: WasmMemory, start: StartMessage) { + this.#memory = memory; + this.#memoryMaxBytes = Math.min(MAX_PAGES, INITIAL_PAGES + Math.ceil(start.limits.memoryBytes / WASM_PAGE_BYTES)) * WASM_PAGE_BYTES; + this.#limits = start.limits; + this.#deadline = Date.now() + start.timeoutMs; + this.#rt = qjs.newRuntime(); + this.#rt.setMemoryLimit(start.limits.memoryBytes); + this.#rt.setMaxStackSize(start.limits.stackBytes); + this.#rt.setInterruptHandler(() => Date.now() > this.#deadline); + this.#ctx = this.#rt.newContext(); + this.#timer = setTimeout(() => this.#finish({ ok: false, kind: 'timeout', error: { name: 'Timeout', message: `the script did not finish within ${start.timeoutMs} ms` } }), start.timeoutMs); + } + + begin(code: string): void { + try { + this.#begin(code); + } catch (err) { + this.#hostFailure(err); + } + } + + #begin(code: string): void { + const ctx = this.#ctx; + const shim = ctx.evalCode(SHIM, SHIM_FILE, { type: 'global' }); + if (shim.error) return this.#fail(shim.error); + const natives = [this.#callNative(), this.#logNative(), this.#doneNative(), ctx.newNumber(this.#limits.maxResultChars), ctx.newNumber(this.#limits.maxLogLineChars)]; + const runner = ctx.callFunction(shim.value, ctx.undefined, natives); + shim.value.dispose(); + for (const handle of natives) handle.dispose(); + if (runner.error) return this.#fail(runner.error); + + const compiled = ctx.evalCode(`(async function () {${code}\n})`, SCRIPT_FILE, { type: 'global' }); + if (compiled.error) { + runner.value.dispose(); + return this.#fail(compiled.error); + } + const started = ctx.callFunction(runner.value, ctx.undefined, compiled.value); + runner.value.dispose(); + compiled.value.dispose(); + if (started.error) return this.#fail(started.error); + started.value.dispose(); + this.#drain(); + } + + reply(message: Extract): void { + try { + this.#reply(message); + } catch (err) { + this.#hostFailure(err); + } + } + + #reply(message: Extract): void { + if (this.#done) return; + const deferred = this.#pending.get(message.id); + if (!deferred) return; + this.#pending.delete(message.id); + const { reply } = message; + const text = (reply.ok ? JSON.stringify(reply.value) : JSON.stringify(reply.error)) ?? 'null'; + const handle = this.#ctx.newString(text); + if (reply.ok) deferred.resolve(handle); + else deferred.reject(handle); + handle.dispose(); + deferred.dispose(); + this.#drain(); + } + + #callNative(): QuickJSHandle { + const ctx = this.#ctx; + return ctx.newFunction('call', (toolHandle, argsHandle) => { + const tool = ctx.getString(toolHandle); + const args = ctx.getString(argsHandle); + const deferred = ctx.newPromise(); + const handle = deferred.handle.dup(); + if (this.#done) { + this.#refuse(deferred, 'cancelled', 'the run has ended'); + } else if (this.#nextId > this.#limits.maxCalls) { + this.#refuse(deferred, 'tool-error', `binding call limit reached: a run may make at most ${this.#limits.maxCalls} calls`); + } else if (args.length > this.#limits.maxArgsChars) { + this.#refuse(deferred, 'invalid-args', `the arguments of ${tool} are larger than ${this.#limits.maxArgsChars} characters of JSON`); + } else { + const id = this.#nextId++; + this.#pending.set(id, deferred); + send({ type: 'call', id, tool, args }); + } + return handle; + }); + } + + #refuse(deferred: QuickJSDeferredPromise, code: string, message: string): void { + const handle = this.#ctx.newString(JSON.stringify({ name: 'ToolError', code, message })); + deferred.reject(handle); + handle.dispose(); + deferred.dispose(); + } + + #logNative(): QuickJSHandle { + const ctx = this.#ctx; + return ctx.newFunction('log', (levelHandle, textHandle) => { + if (this.#logCapped || this.#done) return; + const rawLevel = ctx.getString(levelHandle); + const level = rawLevel === 'info' || rawLevel === 'warn' || rawLevel === 'error' ? rawLevel : 'log'; + let text = ctx.getString(textHandle); + if (text.length > this.#limits.maxLogLineChars) text = `${text.slice(0, this.#limits.maxLogLineChars)}... [truncated]`; + const bytes = Buffer.byteLength(text, 'utf8') + 1; + if (this.#logBytes + bytes > this.#limits.maxLogBytes) { + this.#logCapped = true; + send({ type: 'log', level: 'warn', text: `[console output truncated: the limit of ${this.#limits.maxLogBytes} bytes was reached]` }); + return; + } + this.#logBytes += bytes; + send({ type: 'log', level, text }); + }); + } + + #doneNative(): QuickJSHandle { + const ctx = this.#ctx; + return ctx.newFunction('done', (textHandle) => { + const text = ctx.getString(textHandle); + if (text.startsWith('R')) { + const value = text.slice(1); + if (value.length > this.#limits.maxResultChars) { + return this.#finish({ ok: false, kind: 'error', error: { name: 'ResultTooLarge', message: `the return value is larger than ${this.#limits.maxResultChars} characters of JSON; return less data` } }); + } + return this.#finish({ ok: true, value }); + } + let raw: unknown; + try { + raw = JSON.parse(text.slice(1)); + } catch { + raw = 'the script failed with an unreadable error'; + } + const info = toErrorInfo(raw); + if (info.name === 'InternalError' && isOutOfMemory(info)) return this.#finish({ ok: false, kind: 'oom', error: info }); + // Out of memory can leave QuickJS unable to build an error object; the script then sees `null` thrown. + if (this.#memoryFull()) return this.#finish({ ok: false, kind: 'oom', error: { name: 'InternalError', message: 'out of memory' } }); + this.#finish({ ok: false, kind: 'error', error: info }); + }); + } + + #drain(): void { + if (this.#done) return; + const jobs = this.#rt.executePendingJobs(); + if (jobs.error) return this.#fail(jobs.error); + jobs.dispose(); + if (!this.#done && this.#pending.size === 0 && !this.#rt.hasPendingJob()) { + this.#finish({ + ok: false, + kind: 'error', + error: { name: 'Deadlock', message: 'the script is waiting for a promise that nothing can settle (there are no timers and no pending binding calls)' }, + }); + } + } + + /** The VM threw past the shim: an interrupt (deadline), out of memory, a syntax error or a shim failure. */ + #fail(errorHandle: QuickJSHandle): void { + let raw: unknown; + try { + raw = this.#ctx.dump(errorHandle); + } catch { + raw = 'out of memory'; + } + try { + errorHandle.dispose(); + } catch { + // The process exits after the run; a leaked handle does not matter then. + } + const info = toErrorInfo(raw); + if (Date.now() > this.#deadline || info.message === 'interrupted') { + return this.#finish({ ok: false, kind: 'timeout', error: { name: 'Timeout', message: 'the script did not finish within its time limit' } }); + } + this.#finish({ ok: false, kind: isOutOfMemory(info) || this.#memoryFull() ? 'oom' : 'error', error: info.message === '' ? { ...info, message: 'out of memory' } : info }); + } + + /** A host-side exception (e.g. a WASM trap when an allocation inside the bindings layer fails). */ + #hostFailure(err: unknown): void { + const message = err instanceof Error ? err.message : String(err); + const oom = this.#memoryFull() || /out of memory/i.test(message); + this.#finish({ ok: false, kind: oom ? 'oom' : 'error', error: { name: oom ? 'InternalError' : 'SandboxError', message: oom ? 'out of memory' : message.slice(0, MAX_ERROR_CHARS) } }); + } + + /** True when the WASM memory grew to (nearly) its maximum. */ + #memoryFull(): boolean { + return this.#memory.buffer.byteLength >= this.#memoryMaxBytes * 0.9; + } + + /** + * Sends the outcome and exits. The runtime is not disposed: the process + * ends here, and disposing a runtime with live objects aborts the WASM + * module instead of returning. + */ + #finish(outcome: DoneOutcome): void { + if (this.#done) return; + this.#done = true; + clearTimeout(this.#timer); + process.stdout.write(`${JSON.stringify({ type: 'done', outcome } satisfies ChildMessage)}\n`, () => process.exit(0)); + } +} + +// --------------------------------------------------------------------------- +// Main: read stdin lines, start on the first `start`, route replies. +// --------------------------------------------------------------------------- + +let run: VmRun | undefined; +let started = false; +const early: Extract[] = []; +let buffered = ''; + +function onMessage(message: IncomingMessage): void { + if (message.type === 'start') { + if (started) fatal('received a second start message'); + started = true; + const memory = runMemory(message.limits.memoryBytes); + newQuickJSWASMModuleFromVariant(newVariant(syncVariant(variantModule), { wasmMemory: memory })).then( + (qjs) => { + run = new VmRun(qjs, memory, message); + run.begin(message.code); + for (const reply of early.splice(0)) run.reply(reply); + }, + (err: unknown) => fatal(`could not load QuickJS: ${err instanceof Error ? err.message : String(err)}`), + ); + return; + } + if (run) run.reply(message); + else early.push(message); +} + +process.stdin.setEncoding('utf8'); +process.stdin.on('data', (chunk: string) => { + buffered += chunk; + let nl = buffered.indexOf('\n'); + while (nl !== -1) { + const line = buffered.slice(0, nl); + buffered = buffered.slice(nl + 1); + if (line.trim() !== '') { + let raw: unknown; + try { + raw = JSON.parse(line); + } catch { + fatal('received a message that is not JSON'); + } + const parsed = ParentMessageSchema.safeParse(raw); + if (!parsed.success) fatal('received an invalid message'); + onMessage(parsed.data); + } + nl = buffered.indexOf('\n'); + } +}); +// The parent went away: nothing can reply any more. +process.stdin.on('end', () => process.exit(0)); diff --git a/src/sandbox/index.ts b/src/sandbox/index.ts new file mode 100644 index 0000000..dcdd065 --- /dev/null +++ b/src/sandbox/index.ts @@ -0,0 +1 @@ +export { QuickJsSandbox, DEFAULT_SANDBOX_MEMORY_BYTES, type QuickJsSandboxOptions } from './quickjs-sandbox.js'; diff --git a/src/sandbox/protocol.ts b/src/sandbox/protocol.ts new file mode 100644 index 0000000..b029739 --- /dev/null +++ b/src/sandbox/protocol.ts @@ -0,0 +1,88 @@ +/** + * Wire protocol between the sandbox parent (server process) and the sandbox + * child process. Messages are newline-delimited JSON: parent → child on the + * child's stdin, child → parent on the child's stdout. + * + * Each side validates what it receives. This file holds the parent side: the + * schemas of child messages (the child is treated as hostile) and the types + * of the messages the parent sends. The child (`child.ts`) has no runtime + * import of this file, so it can run from source with Node type stripping. + */ +import { z } from 'zod'; +import type { CallReply } from '../core/types.js'; + +/** Limits of one run, sent to the child in the `start` message. */ +export interface SandboxLimits { + /** QuickJS heap limit (`runtime.setMemoryLimit`). */ + readonly memoryBytes: number; + /** QuickJS stack limit (`runtime.setMaxStackSize`). */ + readonly stackBytes: number; + /** Maximum binding calls per run; later calls reject inside the VM. */ + readonly maxCalls: number; + /** Maximum total console bytes per run; later lines are dropped. */ + readonly maxLogBytes: number; + /** Maximum length of one console line, in characters. */ + readonly maxLogLineChars: number; + /** Maximum length of the JSON-serialized return value, in characters. */ + readonly maxResultChars: number; + /** Maximum length of the JSON-serialized arguments of one call, in characters. */ + readonly maxArgsChars: number; +} + +/** First message of a run: what to execute and with which limits. */ +export interface StartMessage { + readonly type: 'start'; + readonly code: string; + /** Wall-clock budget left for the script when the message was sent. */ + readonly timeoutMs: number; + readonly limits: SandboxLimits; +} + +/** Answer to one binding call. */ +export interface ReplyMessage { + readonly type: 'reply'; + readonly id: number; + readonly reply: CallReply; +} + +export type ParentMessage = StartMessage | ReplyMessage; + +/** Longest tool name a child may send. Real names are at most 5 characters. */ +export const MAX_TOOL_NAME_CHARS = 64; + +const ScriptErrorSchema = z.strictObject({ + name: z.string().max(1_000), + message: z.string().max(100_000), + stack: z.string().max(100_000).optional(), +}); + +/** + * Schema of child → parent messages, built for the limits of one run so that + * every string field is bounded. + */ +export function childMessageSchema(limits: SandboxLimits) { + return z.discriminatedUnion('type', [ + z.strictObject({ + type: z.literal('call'), + id: z.number().int().min(1), + tool: z.string().max(MAX_TOOL_NAME_CHARS), + /** JSON text of the arguments. */ + args: z.string().max(limits.maxArgsChars), + }), + z.strictObject({ + type: z.literal('log'), + level: z.enum(['log', 'info', 'warn', 'error']), + text: z.string().max(limits.maxLogLineChars + 200), + }), + z.strictObject({ + type: z.literal('done'), + outcome: z.discriminatedUnion('ok', [ + /** `value` is the JSON text of the return value. */ + z.strictObject({ ok: z.literal(true), value: z.string().max(limits.maxResultChars) }), + z.strictObject({ ok: z.literal(false), kind: z.enum(['error', 'timeout', 'oom']), error: ScriptErrorSchema }), + ]), + }), + ]); +} + +export type ChildMessage = z.infer>; diff --git a/src/sandbox/quickjs-sandbox.test.ts b/src/sandbox/quickjs-sandbox.test.ts new file mode 100644 index 0000000..b22e091 --- /dev/null +++ b/src/sandbox/quickjs-sandbox.test.ts @@ -0,0 +1,503 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import type { CallReply, LogLevel, SandboxOutcome, ToolResult } from '../core/types.js'; +import { childEntryPath, childEnv, childExecArgv, QuickJsSandbox, type QuickJsSandboxOptions } from './quickjs-sandbox.js'; + +interface Recorded { + readonly outcome: SandboxOutcome; + readonly calls: { tool: string; args: unknown }[]; + readonly logs: { level: LogLevel; text: string }[]; + readonly elapsedMs: number; +} + +type OnCall = (tool: string, args: unknown, index: number) => Promise; + +/** Every binding call succeeds with `{tool, args}` after a host turn. */ +const echo: OnCall = async (tool, args) => { + await new Promise((resolve) => setImmediate(resolve)); + return ok({ tool, args }); +}; + +/** Test replies carry arbitrary data; the sandbox forwards any JSON value. */ +function ok(value: unknown): CallReply { + return { ok: true, value: value as ToolResult }; +} + +async function run( + code: string, + options: { onCall?: OnCall; timeoutMs?: number; memoryBytes?: number; signal?: AbortSignal; sandbox?: QuickJsSandboxOptions } = {}, +): Promise { + const sandbox = new QuickJsSandbox(options.sandbox); + const calls: Recorded['calls'] = []; + const logs: Recorded['logs'] = []; + const onCall = options.onCall ?? echo; + const started = Date.now(); + const outcome = await sandbox.run(code, { + timeoutMs: options.timeoutMs ?? 10_000, + memoryBytes: options.memoryBytes ?? 64 * 1024 * 1024, + signal: options.signal ?? new AbortController().signal, + onCall: (tool, args) => { + calls.push({ tool, args }); + return onCall(tool, args, calls.length - 1); + }, + onLog: (level, text) => logs.push({ level, text }), + }); + return { outcome, calls, logs, elapsedMs: Date.now() - started }; +} + +function value(outcome: SandboxOutcome): unknown { + if (!outcome.ok) throw new Error(`expected ok, got ${outcome.kind}: ${outcome.error.name}: ${outcome.error.message}`); + return outcome.value; +} + +function failure(outcome: SandboxOutcome): Extract { + if (outcome.ok) throw new Error(`expected a failure, got ${JSON.stringify(outcome.value)}`); + return outcome; +} + +function processGone(pid: number): boolean { + try { + process.kill(pid, 0); + return false; + } catch { + return true; + } +} + +describe('QuickJsSandbox: script semantics', () => { + it('runs the code as an async function body and returns JSON', async () => { + const { outcome } = await run('const a = [1, 2, 3]; return { sum: a.reduce((x, y) => x + y, 0), s: "ok", n: null, b: true };'); + expect(value(outcome)).toEqual({ sum: 6, s: 'ok', n: null, b: true }); + }); + + it('returns null when the script returns nothing', async () => { + expect(value((await run('const x = 1;')).outcome)).toBeNull(); + }); + + it('normalizes binding arguments to the contract shapes', async () => { + const { outcome, calls } = await run(` + await bash('ls -la'); + await bash({ command: 'pwd', cwd: 'src', timeoutMs: 5 }); + await read({ path: 'a.txt', offset: 2, limit: 3 }); + await write({ path: 'b.txt', content: 'x' }); + await edit({ path: 'b.txt', oldString: 'x', newString: 'y', replaceAll: true }); + await grep({ pattern: 'TODO', glob: '*.ts', ignoreCase: true }); + await glob({ pattern: '**/*.ts', maxResults: 10 }); + return 'done'; + `); + expect(value(outcome)).toBe('done'); + expect(calls).toEqual([ + { tool: 'bash', args: { command: 'ls -la' } }, + { tool: 'bash', args: { command: 'pwd', cwd: 'src', timeoutMs: 5 } }, + { tool: 'read', args: { path: 'a.txt', offset: 2, limit: 3 } }, + { tool: 'write', args: { path: 'b.txt', content: 'x' } }, + { tool: 'edit', args: { path: 'b.txt', oldString: 'x', newString: 'y', replaceAll: true } }, + { tool: 'grep', args: { pattern: 'TODO', glob: '*.ts', ignoreCase: true } }, + { tool: 'glob', args: { pattern: '**/*.ts', maxResults: 10 } }, + ]); + }); + + it('passes the binding result into the script', async () => { + const { outcome } = await run('const r = await read({ path: "x" }); return r.args.path + ":" + r.tool;'); + expect(value(outcome)).toBe('x:read'); + }); + + it('rehydrates binding errors as Error objects the script can catch', async () => { + const { outcome } = await run( + ` + const out = []; + for (const path of ['denied', 'missing']) { + try { await read({ path }); } catch (e) { + out.push({ isError: e instanceof Error, name: e.name, message: e.message, code: e.code, source: e.source ?? null, reason: e.reason ?? null }); + } + } + return out; + `, + { + onCall: async (_tool, args, index) => + index === 0 + ? { ok: false, error: { name: 'PermissionDenied', code: 'denied', source: 'hook', message: `blocked ${JSON.stringify(args)}` } } + : { ok: false, error: { name: 'ToolError', code: 'not-found', message: 'no such file' } }, + }, + ); + expect(value(outcome)).toEqual([ + { isError: true, name: 'PermissionDenied', message: 'blocked {"path":"denied"}', code: 'denied', source: 'hook', reason: 'blocked {"path":"denied"}' }, + { isError: true, name: 'ToolError', message: 'no such file', code: 'not-found', source: null, reason: null }, + ]); + }); + + it('reports an uncaught throw with the script frames only', async () => { + const { outcome } = await run('function inner() { throw new TypeError("bad thing"); }\ninner();'); + const f = failure(outcome); + expect(f.kind).toBe('error'); + expect(f.error.name).toBe('TypeError'); + expect(f.error.message).toBe('bad thing'); + expect(f.error.stack).toContain('script.js:1'); + expect(f.error.stack).not.toContain('shim.js'); + }); + + it('reports a syntax error', async () => { + const f = failure((await run('return (;')).outcome); + expect(f.kind).toBe('error'); + expect(f.error.name).toBe('SyntaxError'); + }); + + it('reports thrown non-Error values', async () => { + expect(failure((await run('throw "plain";')).outcome).error).toEqual({ name: 'Error', message: 'plain' }); + expect(failure((await run('throw { a: 1 };')).outcome).error.message).toBe('Uncaught { a: 1 }'); + }); + + it('converts non-JSON return values to descriptive strings', async () => { + const { outcome } = await run(` + const cyclic = { name: 'c' }; cyclic.self = cyclic; + return { fn: function named() {}, arrow: () => 1, sym: Symbol('s'), big: 12n, nan: NaN, inf: -Infinity, + cyclic, date: new Date(0), err: new RangeError('r'), undef: undefined, arr: [undefined, 1], map: new Map([[1, 2]]) }; + `); + expect(value(outcome)).toEqual({ + fn: '[Function: named]', + arrow: '[Function: arrow]', + sym: 'Symbol(s)', + big: '12n', + nan: 'NaN', + inf: '-Infinity', + cyclic: { name: 'c', self: '[Circular]' }, + date: '1970-01-01T00:00:00.000Z', + err: 'RangeError: r', + arr: [null, 1], + map: {}, + }); + }); + + it('turns a throwing getter into a description instead of crashing', async () => { + const { outcome } = await run('return { get bad() { throw new Error("no"); }, ok: 1 };'); + expect(value(outcome)).toEqual({ bad: '[threw: no]', ok: 1 }); + }); + + it('formats console output like Node and keeps the level', async () => { + const { logs } = await run(` + console.log('a', 1, { k: 'v', n: [1, 2] }, null, undefined); + console.info('i'); console.warn('w'); console.error(new Error('boom')); + `); + expect(logs).toEqual([ + { level: 'log', text: "a 1 { k: 'v', n: [ 1, 2 ] } null undefined" }, + { level: 'info', text: 'i' }, + { level: 'warn', text: 'w' }, + { level: 'error', text: 'Error: boom' }, + ]); + }); + + it('fails fast when the script waits on a promise nothing can settle', async () => { + const { outcome, elapsedMs } = await run('await new Promise(() => {});', { timeoutMs: 10_000 }); + expect(failure(outcome).error.name).toBe('Deadlock'); + expect(elapsedMs).toBeLessThan(5_000); + }); + + it('rejects a binding argument that is not JSON-serializable without calling the host', async () => { + const { outcome, calls } = await run('const a = {}; a.a = a; try { await read(a); } catch (e) { return e.name + ": " + (e.message.includes("JSON") ? "json" : e.message); }'); + expect(value(outcome)).toBe('TypeError: json'); + expect(calls).toEqual([]); + }); +}); + +describe('QuickJsSandbox: no ambient authority', () => { + it('exposes no host objects, module loading or timers', async () => { + const { outcome, calls } = await run(` + const names = ['require', 'process', 'fetch', 'Deno', 'Bun', 'std', 'os', 'module', 'exports', 'Buffer', + 'setTimeout', 'setInterval', 'setImmediate', 'queueMicrotask', 'performance', 'XMLHttpRequest', 'WebSocket', + 'importScripts', 'print', 'scriptArgs', '__acm_call', 'hostCall']; + const types = {}; + for (const n of names) types[n] = typeof globalThis[n]; + const viaFunction = new Function('return this')(); + const viaEval = (0, eval)('this'); + const extra = (g) => Object.getOwnPropertyNames(g).filter((k) => !STANDARD.includes(k)); + let dynamicImport; + try { await import('fs'); dynamicImport = 'loaded'; } catch (e) { dynamicImport = 'rejected'; } + let nodeImport; + try { await import('node:child_process'); nodeImport = 'loaded'; } catch (e) { nodeImport = 'rejected'; } + return { types, same: viaFunction === globalThis && viaEval === globalThis, extraFn: extra(viaFunction), extraEval: extra(viaEval), dynamicImport, nodeImport }; + `.replace( + 'STANDARD', + JSON.stringify([ + 'Object', 'Function', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'InternalError', + 'AggregateError', 'Iterator', 'Array', 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'decodeURI', 'decodeURIComponent', 'encodeURI', + 'encodeURIComponent', 'escape', 'unescape', 'Infinity', 'NaN', 'undefined', 'Number', 'Boolean', 'String', 'Math', 'Reflect', 'Symbol', + 'eval', 'globalThis', 'Date', 'RegExp', 'JSON', 'Proxy', 'Map', 'Set', 'WeakMap', 'WeakSet', 'ArrayBuffer', 'SharedArrayBuffer', + 'Uint8ClampedArray', 'Int8Array', 'Uint8Array', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'BigInt64Array', + 'BigUint64Array', 'Float16Array', 'Float32Array', 'Float64Array', 'DataView', 'Promise', 'BigInt', 'WeakRef', 'FinalizationRegistry', + 'console', 'bash', 'read', 'write', 'edit', 'grep', 'glob', + ]), + )); + const result = value(outcome); + expect(result).toEqual({ + types: Object.fromEntries( + ['require', 'process', 'fetch', 'Deno', 'Bun', 'std', 'os', 'module', 'exports', 'Buffer', 'setTimeout', 'setInterval', 'setImmediate', + 'queueMicrotask', 'performance', 'XMLHttpRequest', 'WebSocket', 'importScripts', 'print', 'scriptArgs', '__acm_call', 'hostCall'].map((n) => [n, 'undefined']), + ), + same: true, + extraFn: [], + extraEval: [], + dynamicImport: 'rejected', + nodeImport: 'rejected', + }); + expect(calls).toEqual([]); + }); + + it('starts the child with an env that has none of the server secrets', () => { + const env = childEnv({ ACM_TEST_CANARY: 'secret', PATH: '/bin', HOME: '/home/x', GITHUB_TOKEN: 't' }, 'linux'); + expect(env).toEqual({}); + expect(childEnv({ ACM_TEST_CANARY: 'secret', SystemRoot: 'C:\\Windows' }, 'win32')).toEqual({ SystemRoot: 'C:\\Windows' }); + }); + + it.runIf(process.allowedNodeEnvironmentFlags.has('--permission'))('runs the child process under the Node permission model', () => { + const target = join(tmpdir(), `acm-permission-probe-${process.pid}`); + const probe = `const r = {}; const fs = require('fs'); + try { fs.writeFileSync(${JSON.stringify(target)}, 'x'); r.write = 'allowed'; } catch (e) { r.write = e.code; } + try { require('child_process').execFileSync(process.execPath, ['-e', '0']); r.spawn = 'allowed'; } catch (e) { r.spawn = e.code; } + try { new Function('return 1')(); r.codegen = 'allowed'; } catch (e) { r.codegen = e.name; } + r.env = Object.keys(process.env).filter((k) => !/^systemroot$/i.test(k)); + console.log(JSON.stringify(r));`; + const flags = childExecArgv(childEntryPath(), 256).filter((flag) => flag !== '--experimental-strip-types'); + const out = spawnSync(process.execPath, [...flags, '-e', probe], { env: childEnv(), encoding: 'utf8' }); + expect(JSON.parse(out.stdout)).toEqual({ write: 'ERR_ACCESS_DENIED', spawn: 'ERR_ACCESS_DENIED', codegen: 'EvalError', env: [] }); + expect(existsSync(target)).toBe(false); + }); + + it('never lets the script observe a canary secret from the server env', async () => { + const canary = `canary-${Math.random().toString(36).slice(2)}-${Date.now()}`; + process.env.ACM_TEST_CANARY = canary; + let childEnviron = ''; + try { + let pid = 0; + const recorded = await run( + ` + const seen = []; + const scan = (o, depth) => { if (depth > 3 || o === null || (typeof o !== 'object' && typeof o !== 'function')) return; + for (const k of Object.getOwnPropertyNames(o)) { seen.push(k); try { scan(o[k], depth + 1); } catch {} } }; + scan(globalThis, 0); + try { await bash({ command: 'echo $ACM_TEST_CANARY' }); } catch (e) { seen.push(e.message, String(e.stack)); } + try { await read({ path: '/proc/self/environ' }); } catch (e) { seen.push(e.message); } + try { null.x; } catch (e) { seen.push(String(e.stack)); } + console.log(seen.join(' ')); + return seen.join(' '); + `, + { + sandbox: { onSpawn: (p) => (pid = p) }, + onCall: async (tool) => { + if (process.platform === 'linux' && pid > 0 && childEnviron === '') childEnviron = readFileSync(`/proc/${pid}/environ`, 'utf8'); + return { ok: false, error: { name: 'ToolError', code: 'tool-error', message: `${tool} failed` } }; + }, + }, + ); + const everything = JSON.stringify(recorded); + expect(recorded.outcome.ok).toBe(true); + expect(everything).not.toContain(canary); + if (process.platform === 'linux') { + expect(childEnviron).not.toContain(canary); + expect(childEnviron).not.toContain('PATH='); + } + } finally { + delete process.env.ACM_TEST_CANARY; + } + }); +}); + +describe('QuickJsSandbox: prototype pollution', () => { + it('keeps host prototypes intact and parses hostile keys as own data', async () => { + const { outcome } = await run(` + Object.prototype.polluted = 1; + Array.prototype.map = function () { return 'hijacked'; }; + JSON.stringify = () => '"hijacked"'; + Promise.prototype.then = function () { throw new Error('hijacked then'); }; + const viaParse = JSON.parse('{"__proto__": {"injected": true}, "constructor": {"prototype": {"injected": true}}}'); + const literal = { ['__proto__']: { injected: true }, constructor: { prototype: { injected: true } }, list: [1, 2] }; + return { viaParse, literal }; + `); + const result = value(outcome); + expect(({} as Record).polluted).toBeUndefined(); + expect([1].map((x) => x + 1)).toEqual([2]); + expect(Object.prototype).not.toHaveProperty('injected'); + const top = result as Record>; + for (const key of ['viaParse', 'literal'] as const) { + const obj = top[key]; + expect(obj).toBeDefined(); + if (!obj) continue; + expect(Object.getPrototypeOf(obj)).toBe(Object.prototype); + expect(Object.keys(obj)).toContain('__proto__'); + expect((obj as { injected?: unknown }).injected).toBeUndefined(); + expect(({} as { injected?: unknown }).injected).toBeUndefined(); + expect(Object.hasOwn(obj, 'polluted')).toBe(false); + } + }); + + it('keeps bindings working after the script overrides intrinsics', async () => { + const { outcome } = await run(` + JSON.parse = () => 'hijacked'; + JSON.stringify = () => 'hijacked'; + Promise.prototype.then = function () { throw new Error('hijacked then'); }; + const r = read({ path: 'p' }); + return 'called'; + `); + expect(value(outcome)).toBe('called'); + }); +}); + +describe('QuickJsSandbox: resource abuse', () => { + it('stops an infinite loop with outcome timeout within the deadline plus a small margin', async () => { + const { outcome, elapsedMs } = await run('for (;;) {}', { timeoutMs: 1_000 }); + expect(failure(outcome).kind).toBe('timeout'); + expect(elapsedMs).toBeLessThan(1_000 + 1_000); + }); + + it('stops a loop that catches every error', async () => { + const { outcome, elapsedMs } = await run('for (;;) { try { for (;;) {} } catch (e) {} }', { timeoutMs: 800 }); + expect(failure(outcome).kind).toBe('timeout'); + expect(elapsedMs).toBeLessThan(800 + 1_000); + }); + + it('times out while a binding never replies', async () => { + const { outcome, elapsedMs } = await run('await read({ path: "slow" });', { timeoutMs: 600, onCall: () => new Promise(() => undefined) }); + expect(failure(outcome).kind).toBe('timeout'); + expect(elapsedMs).toBeLessThan(600 + 1_000); + }); + + it('reports an allocation bomb as oom', async () => { + const arrays = await run('const a = []; for (let i = 0; ; i++) a.push("x".repeat(100000) + i);', { memoryBytes: 32 * 1024 * 1024 }); + expect(failure(arrays.outcome).kind).toBe('oom'); + const objects = await run('const a = []; for (;;) a.push({ a: 1, b: [1, 2, 3] });', { memoryBytes: 32 * 1024 * 1024 }); + expect(failure(objects.outcome).kind).toBe('oom'); + const single = await run('return "x".repeat(1e9).length;', { memoryBytes: 32 * 1024 * 1024 }); + expect(failure(single.outcome).kind).toBe('oom'); + }); + + it('enforces memoryBytes as the real heap limit', async () => { + const fill = (mib: number): string => `const a = []; for (let i = 0; i < ${mib * 10}; i++) a.push("x".repeat(100000) + i); return a.length;`; + expect(value((await run(fill(16), { memoryBytes: 48 * 1024 * 1024 })).outcome)).toBe(160); + expect(failure((await run(fill(96), { memoryBytes: 48 * 1024 * 1024 })).outcome).kind).toBe('oom'); + }); + + it('turns deep recursion into a script error, not a crash', async () => { + const f = failure((await run('function f(n) { return f(n + 1) + 1; } return f(0);')).outcome); + expect(f.kind).toBe('error'); + expect(f.error.name).toBe('RangeError'); + const caught = await run('function f() { f(); } try { f(); } catch (e) { return e.name; }'); + expect(value(caught.outcome)).toBe('RangeError'); + }); + + it('refuses binding calls after the cap and never forwards them', async () => { + const { outcome, calls } = await run( + ` + const settled = await Promise.allSettled(Array.from({ length: 10000 }, (_, i) => glob({ pattern: String(i) }))); + const rejected = settled.filter((s) => s.status === 'rejected'); + return { fulfilled: settled.length - rejected.length, rejected: rejected.length, sample: rejected[0].reason.message, code: rejected[0].reason.code }; + `, + { onCall: async () => ok({ files: [], truncated: false }) }, + ); + expect(value(outcome)).toEqual({ fulfilled: 2000, rejected: 8000, sample: expect.stringContaining('at most 2000 calls'), code: 'tool-error' }); + expect(calls).toHaveLength(2000); + }); + + it('caps console spam', async () => { + const { logs, outcome } = await run('for (let i = 0; i < 200000; i++) console.log("spam line " + i + " " + "y".repeat(80));', { + sandbox: { maxLogBytes: 256 * 1024 }, + }); + expect(outcome.ok).toBe(true); + const bytes = logs.reduce((n, l) => n + Buffer.byteLength(l.text) + 1, 0); + expect(bytes).toBeLessThanOrEqual(256 * 1024 + 1024); + expect(logs.at(-1)?.text).toContain('console output truncated'); + }); + + it('cuts a single huge console line', async () => { + const { logs } = await run('console.log("z".repeat(500000));'); + expect(logs).toHaveLength(1); + expect(logs[0]?.text.length).toBeLessThan(10_100); + expect(logs[0]?.text).toContain('[truncated]'); + }); + + it('bounds a gigantic return value', async () => { + const str = failure((await run('return "x".repeat(5 * 1024 * 1024);')).outcome); + expect(str.error.name).toBe('ResultTooLarge'); + const arr = await run('return new Array(1e8);'); + expect(failure(arr.outcome).error.name).toBe('ResultTooLarge'); + expect(arr.elapsedMs).toBeLessThan(5_000); + }); +}); + +describe('QuickJsSandbox: concurrency', () => { + it('resolves Promise.all of 200 bindings answered in reverse order', async () => { + const waiting: (() => void)[] = []; + const { outcome } = await run('return await Promise.all(Array.from({ length: 200 }, (_, i) => read({ path: "f" + i })));', { + onCall: (_tool, args, index) => + new Promise((resolve) => { + waiting.push(() => resolve(ok({ echo: args, index }))); + if (waiting.length === 200) { + for (const answer of [...waiting].reverse()) setImmediate(answer); + } + }), + }); + const result = value(outcome) as { echo: { path: string }; index: number }[]; + expect(result).toHaveLength(200); + result.forEach((r, i) => { + expect(r.echo.path).toBe(`f${i}`); + expect(r.index).toBe(i); + }); + }); + + it('keeps running when one binding inside Promise.allSettled rejects', async () => { + const { outcome } = await run( + 'const s = await Promise.allSettled([read({ path: "a" }), read({ path: "b" }), read({ path: "c" })]); return s.map((x) => x.status + ":" + (x.status === "fulfilled" ? x.value.path : x.reason.code));', + { + onCall: async (_tool, args) => { + const path = (args as { path: string }).path; + await new Promise((resolve) => setTimeout(resolve, path === 'a' ? 20 : 1)); + return path === 'b' ? { ok: false, error: { name: 'ToolError', code: 'not-found', message: 'missing' } } : ok({ path }); + }, + }, + ); + expect(value(outcome)).toEqual(['fulfilled:a', 'rejected:not-found', 'fulfilled:c']); + }); +}); + +describe('QuickJsSandbox: cancellation', () => { + it('kills the child during a pending binding and forwards no later call', async () => { + const controller = new AbortController(); + let pid = 0; + const started = Date.now(); + const { outcome, calls } = await run('await read({ path: "first" }); await read({ path: "second" }); return "finished";', { + signal: controller.signal, + sandbox: { onSpawn: (p) => (pid = p) }, + onCall: async () => { + setTimeout(() => controller.abort(), 10); + await new Promise((resolve) => setTimeout(resolve, 100)); + return ok({ late: true }); + }, + }); + expect(failure(outcome).kind).toBe('killed'); + expect(pid).toBeGreaterThan(0); + while (!processGone(pid) && Date.now() - started < 1_000) await new Promise((resolve) => setTimeout(resolve, 10)); + expect(processGone(pid)).toBe(true); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(calls).toEqual([{ tool: 'read', args: { path: 'first' } }]); + }); + + it('does not start a child when the signal is already aborted', async () => { + const controller = new AbortController(); + controller.abort(); + let spawned = false; + const { outcome } = await run('return 1;', { signal: controller.signal, sandbox: { onSpawn: () => (spawned = true) } }); + expect(failure(outcome).kind).toBe('killed'); + expect(spawned).toBe(false); + }); + + it('never reuses a child across runs', async () => { + const pids: number[] = []; + const sandbox = { onSpawn: (p: number) => pids.push(p) }; + await run('globalThis.leak = 42; return 1;', { sandbox }); + const second = await run('return typeof globalThis.leak;', { sandbox }); + expect(value(second.outcome)).toBe('undefined'); + expect(pids).toHaveLength(2); + expect(pids[0]).not.toBe(pids[1]); + }); +}); diff --git a/src/sandbox/quickjs-sandbox.ts b/src/sandbox/quickjs-sandbox.ts new file mode 100644 index 0000000..0fdb62f --- /dev/null +++ b/src/sandbox/quickjs-sandbox.ts @@ -0,0 +1,208 @@ +import { spawn } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { basename, dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { errorMessage } from '../core/errors.js'; +import type { Sandbox, SandboxOutcome, SandboxRunOptions } from '../core/types.js'; +import type { ParentMessage, SandboxLimits } from './protocol.js'; +import { ChildSession, killedOutcome } from './session.js'; + +/** Default QuickJS heap limit when `memoryBytes` is not usable. */ +export const DEFAULT_SANDBOX_MEMORY_BYTES = 128 * 1024 * 1024; + +/** Limits and process settings of `QuickJsSandbox`. Every field has a default. */ +export interface QuickJsSandboxOptions { + /** Maximum binding calls per run. Default 2,000. */ + readonly maxCalls?: number; + /** Maximum console bytes per run. Default 1 MiB. */ + readonly maxLogBytes?: number; + /** Maximum characters of one console line. Default 10,000. */ + readonly maxLogLineChars?: number; + /** Maximum characters of the JSON return value. Default 1 MiB. */ + readonly maxResultChars?: number; + /** Maximum characters of the JSON arguments of one call. Default 4 MiB. */ + readonly maxArgsChars?: number; + /** QuickJS stack limit. Default 256 KiB (deeper values overflow the host stack of the WASM build). */ + readonly stackBytes?: number; + /** `--max-old-space-size` of the child process, in MiB. Default 256. */ + readonly childHeapMb?: number; + /** Called with the pid of each child process (tests use it to check the child is gone). */ + readonly onSpawn?: (pid: number) => void; +} + +const DEFAULTS = { + maxCalls: 2_000, + maxLogBytes: 1024 * 1024, + maxLogLineChars: 10_000, + maxResultChars: 1024 * 1024, + maxArgsChars: 4 * 1024 * 1024, + stackBytes: 256 * 1024, + childHeapMb: 256, +} as const; + +const here = dirname(fileURLToPath(import.meta.url)); + +/** The child entry: compiled `child.js` next to this file, or `child.ts` when running from source. */ +export function childEntryPath(): string { + const compiled = join(here, 'child.js'); + return existsSync(compiled) ? compiled : join(here, 'child.ts'); +} + +/** + * Environment of the child: nothing from the server env except what Node + * itself needs to start on Windows. No tokens, no PATH, no HOME. + */ +export function childEnv(parentEnv: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): Record { + const env: Record = {}; + if (platform === 'win32') { + for (const key of ['SystemRoot', 'SYSTEMROOT']) { + const value = parentEnv[key]; + if (value !== undefined) env[key] = value; + } + } + return env; +} + +function packageRoot(start: string): string { + let dir = start; + for (;;) { + if (existsSync(join(dir, 'package.json'))) return dir; + const parent = dirname(dir); + if (parent === dir) return start; + dir = parent; + } +} + +function nodeModulesDirOf(file: string): string { + let dir = dirname(file); + for (;;) { + if (basename(dir) === 'node_modules') return dir; + const parent = dirname(dir); + if (parent === dir) return dirname(file); + dir = parent; + } +} + +/** Directories the child may read under the Node permission model: this package and its runtime dependencies. */ +function readableRoots(): string[] { + const require = createRequire(import.meta.url); + const roots = new Set([packageRoot(here)]); + for (const spec of ['quickjs-emscripten-core', '@jitl/quickjs-ng-wasmfile-release-sync', 'zod']) { + try { + roots.add(nodeModulesDirOf(require.resolve(spec))); + } catch { + // Not resolvable with CommonJS conditions: the child fails to start and the run ends `killed`. + } + } + return [...roots]; +} + +function supportsFlag(flag: string): boolean { + return process.allowedNodeEnvironmentFlags.has(flag); +} + +/** Node flags of the child. */ +export function childExecArgv(entry: string, heapMb: number): string[] { + const args = [`--max-old-space-size=${heapMb}`, '--disallow-code-generation-from-strings']; + if (entry.endsWith('.ts') && !('typescript' in process.features && process.features.typescript)) args.push('--experimental-strip-types'); + if (supportsFlag('--permission')) { + args.push('--permission'); + for (const root of readableRoots()) args.push(`--allow-fs-read=${root}`); + } + return args; +} + +function positive(value: number | undefined, fallback: number): number { + return value !== undefined && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback; +} + +/** + * The real sandbox: each run starts a fresh Node child process (minimal env, + * bounded heap, Node permission model when available) that runs the script + * in a QuickJS-ng WASM VM. The parent enforces the deadline and cancellation + * with SIGKILL and validates every message from the child. A child is never + * reused. + */ +export class QuickJsSandbox implements Sandbox { + readonly #options: QuickJsSandboxOptions; + readonly #entry: string; + + constructor(options: QuickJsSandboxOptions = {}) { + this.#options = options; + this.#entry = childEntryPath(); + } + + run(code: string, opts: SandboxRunOptions): Promise { + const startedAt = Date.now(); + if (opts.signal.aborted) return Promise.resolve(killedOutcome('the run was stopped before the script started')); + const o = this.#options; + const limits: SandboxLimits = { + memoryBytes: positive(opts.memoryBytes, DEFAULT_SANDBOX_MEMORY_BYTES), + stackBytes: positive(o.stackBytes, DEFAULTS.stackBytes), + maxCalls: positive(o.maxCalls, DEFAULTS.maxCalls), + maxLogBytes: positive(o.maxLogBytes, DEFAULTS.maxLogBytes), + maxLogLineChars: positive(o.maxLogLineChars, DEFAULTS.maxLogLineChars), + maxResultChars: positive(o.maxResultChars, DEFAULTS.maxResultChars), + maxArgsChars: positive(o.maxArgsChars, DEFAULTS.maxArgsChars), + }; + const timeoutMs = positive(opts.timeoutMs, 1); + // Each string field is bounded in characters; JSON escaping turns one character into at most 6 bytes. + const maxFrameBytes = 6 * Math.max(limits.maxArgsChars, limits.maxResultChars, limits.maxLogLineChars + 200) + 64 * 1024; + + let child: ReturnType; + try { + child = spawn(process.execPath, [...childExecArgv(this.#entry, positive(o.childHeapMb, DEFAULTS.childHeapMb)), this.#entry], { + env: childEnv(), + cwd: here, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true, + }); + } catch (err) { + return Promise.resolve(killedOutcome(`could not start the sandbox process: ${errorMessage(err)}`)); + } + const { stdin, stdout, stderr } = child; + if (!stdin || !stdout || !stderr) { + child.kill('SIGKILL'); + return Promise.resolve(killedOutcome('the sandbox process has no stdio pipes')); + } + if (child.pid !== undefined) o.onSpawn?.(child.pid); + + const write = (message: ParentMessage): void => { + if (!stdin.destroyed) stdin.write(`${JSON.stringify(message)}\n`); + }; + const session = new ChildSession({ + limits, + maxFrameBytes, + hooks: { + onCall: (tool, args) => opts.onCall(tool, args), + onLog: (level, text) => opts.onLog(level, text), + send: write, + kill: () => { + child.kill('SIGKILL'); + stdin.destroy(); + }, + }, + }); + + stdout.on('data', (chunk: Buffer) => session.feed(chunk)); + stderr.on('data', (chunk: Buffer) => session.stderr(chunk)); + stdin.on('error', () => undefined); + child.on('error', (err) => session.kill(`sandbox process error: ${errorMessage(err)}`)); + child.on('close', (exitCode, signal) => session.exited(exitCode, signal)); + + const timer = setTimeout( + () => session.finish({ ok: false, kind: 'timeout', error: { name: 'Timeout', message: `the script did not finish within ${timeoutMs} ms` } }), + timeoutMs, + ); + const onAbort = (): void => session.kill('the run was stopped'); + opts.signal.addEventListener('abort', onAbort, { once: true }); + + write({ type: 'start', code, timeoutMs: Math.max(1, timeoutMs - (Date.now() - startedAt)), limits }); + + return session.outcome.finally(() => { + clearTimeout(timer); + opts.signal.removeEventListener('abort', onAbort); + }); + } +} diff --git a/src/sandbox/session.test.ts b/src/sandbox/session.test.ts new file mode 100644 index 0000000..934226b --- /dev/null +++ b/src/sandbox/session.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from 'vitest'; +import type { CallReply, LogLevel, SandboxOutcome, ToolResult } from '../core/types.js'; +import type { ParentMessage, SandboxLimits } from './protocol.js'; +import { ChildSession } from './session.js'; + +const LIMITS: SandboxLimits = { + memoryBytes: 1024 * 1024, + stackBytes: 64 * 1024, + maxCalls: 3, + maxLogBytes: 100, + maxLogLineChars: 50, + maxResultChars: 500, + maxArgsChars: 200, +}; + +function setup(onCall?: (tool: string, args: unknown) => Promise) { + const sent: ParentMessage[] = []; + const logs: { level: LogLevel; text: string }[] = []; + const calls: { tool: string; args: unknown }[] = []; + let kills = 0; + const session = new ChildSession({ + limits: LIMITS, + maxFrameBytes: 1_000, + hooks: { + onCall: (tool, args) => { + calls.push({ tool, args }); + return onCall ? onCall(tool, args) : Promise.resolve({ ok: true, value: { files: [], truncated: false } satisfies ToolResult }); + }, + onLog: (level, text) => logs.push({ level, text }), + send: (m) => sent.push(m), + kill: () => kills++, + }, + }); + const line = (message: unknown): void => session.feed(Buffer.from(`${JSON.stringify(message)}\n`)); + return { session, sent, logs, calls, line, kills: () => kills }; +} + +async function killed(session: ChildSession): Promise { + const outcome: SandboxOutcome = await session.outcome; + if (outcome.ok || outcome.kind !== 'killed') throw new Error(`expected killed, got ${JSON.stringify(outcome)}`); + return outcome.error.message; +} + +const tick = (): Promise => new Promise((resolve) => setImmediate(resolve)); + +describe('ChildSession: valid traffic', () => { + it('forwards calls, replies with the same id, passes logs and settles on done', async () => { + const t = setup(); + t.line({ type: 'call', id: 1, tool: 'glob', args: '{"pattern":"*.ts"}' }); + t.line({ type: 'log', level: 'warn', text: 'careful' }); + await tick(); + expect(t.calls).toEqual([{ tool: 'glob', args: { pattern: '*.ts' } }]); + expect(t.sent).toEqual([{ type: 'reply', id: 1, reply: { ok: true, value: { files: [], truncated: false } } }]); + expect(t.logs).toEqual([{ level: 'warn', text: 'careful' }]); + t.line({ type: 'done', outcome: { ok: true, value: '{"a":[1,2]}' } }); + expect(await t.session.outcome).toEqual({ ok: true, value: { a: [1, 2] } }); + expect(t.kills()).toBe(1); + }); + + it('reassembles messages split across chunks and several messages in one chunk', async () => { + const t = setup(); + const text = `${JSON.stringify({ type: 'log', level: 'log', text: 'one' })}\n${JSON.stringify({ type: 'log', level: 'log', text: 'two' })}\n`; + t.session.feed(Buffer.from(text.slice(0, 7))); + t.session.feed(Buffer.from(text.slice(7, 40))); + t.session.feed(Buffer.from(text.slice(40))); + expect(t.logs.map((l) => l.text)).toEqual(['one', 'two']); + }); + + it('passes error outcomes through', async () => { + const t = setup(); + t.line({ type: 'done', outcome: { ok: false, kind: 'oom', error: { name: 'InternalError', message: 'out of memory' } } }); + expect(await t.session.outcome).toEqual({ ok: false, kind: 'oom', error: { name: 'InternalError', message: 'out of memory' } }); + }); + + it('parses hostile keys in the return value as own data', async () => { + const t = setup(); + t.line({ type: 'done', outcome: { ok: true, value: '{"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted":true}}}' } }); + const outcome = await t.session.outcome; + expect(outcome.ok).toBe(true); + const result = outcome.ok ? outcome.value : undefined; + expect(Object.getPrototypeOf(result)).toBe(Object.prototype); + expect(Object.keys(result as object)).toEqual(['__proto__', 'constructor']); + expect(({} as { polluted?: unknown }).polluted).toBeUndefined(); + }); + + it('drops log output past the cap without killing the child', () => { + const t = setup(); + for (let i = 0; i < 100; i++) t.line({ type: 'log', level: 'log', text: 'x'.repeat(40) }); + expect(t.session.finished).toBe(false); + const bytes = t.logs.reduce((n, l) => n + l.text.length + 1, 0); + expect(bytes).toBeLessThanOrEqual(LIMITS.maxLogBytes + 1_024); + expect(t.logs.length).toBeLessThan(100); + }); +}); + +describe('ChildSession: hostile child messages', () => { + it('kills on a line larger than the frame limit, even without a newline', async () => { + const t = setup(); + t.session.feed(Buffer.alloc(600, 0x61)); + expect(t.session.finished).toBe(false); + t.session.feed(Buffer.alloc(600, 0x61)); + expect(await killed(t.session)).toContain('larger than 1000 bytes'); + expect(t.kills()).toBe(1); + }); + + it('kills on an oversize string field', async () => { + const t = setup(); + t.line({ type: 'log', level: 'log', text: 'y'.repeat(300) }); + expect(await killed(t.session)).toContain('invalid message'); + }); + + it('kills on a line that is not JSON', async () => { + const t = setup(); + t.session.feed(Buffer.from('{"type": "call", \n')); + expect(await killed(t.session)).toContain('not JSON'); + }); + + it.each([ + ['unknown type', { type: 'exec', command: 'rm -rf /' }], + ['missing fields', { type: 'call', id: 1 }], + ['extra field', { type: 'log', level: 'log', text: 'x', extra: 1 }], + ['bad level', { type: 'log', level: 'debug', text: 'x' }], + ['non-integer id', { type: 'call', id: 1.5, tool: 'read', args: '{}' }], + ['outcome kind the child may not claim', { type: 'done', outcome: { ok: false, kind: 'killed', error: { name: 'x', message: 'y' } } }], + ['array instead of object', [1, 2, 3]], + ['null', null], + ])('kills on %s', async (_label, message) => { + const t = setup(); + t.line(message); + expect(await killed(t.session)).toContain('invalid message'); + expect(t.calls).toEqual([]); + }); + + it('kills on a call id out of sequence', async () => { + const t = setup(); + t.line({ type: 'call', id: 2, tool: 'read', args: '{}' }); + expect(await killed(t.session)).toContain('expected 1'); + expect(t.calls).toEqual([]); + }); + + it('kills on a repeated call id', async () => { + const t = setup(); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + expect(await killed(t.session)).toContain('expected 2'); + expect(t.calls).toHaveLength(1); + }); + + it('kills when the child exceeds the call cap', async () => { + const t = setup(); + for (let id = 1; id <= 4; id++) t.line({ type: 'call', id, tool: 'read', args: '{}' }); + expect(await killed(t.session)).toContain('limit of 3'); + expect(t.calls).toHaveLength(3); + }); + + it('kills on call arguments that are not JSON', async () => { + const t = setup(); + t.line({ type: 'call', id: 1, tool: 'read', args: '{nope' }); + expect(await killed(t.session)).toContain('not JSON'); + expect(t.calls).toEqual([]); + }); + + it('kills on a return value that is not JSON', async () => { + const t = setup(); + t.line({ type: 'done', outcome: { ok: true, value: 'undefined' } }); + expect(await killed(t.session)).toContain('not JSON'); + }); + + it('ignores everything after the outcome and sends no late replies', async () => { + let release: (reply: CallReply) => void = () => undefined; + const t = setup(() => new Promise((resolve) => (release = resolve))); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + t.session.kill('stopped by test'); + t.line({ type: 'call', id: 2, tool: 'read', args: '{}' }); + t.line({ type: 'log', level: 'log', text: 'late' }); + release({ ok: true, value: { files: [], truncated: false } }); + await tick(); + expect(await killed(t.session)).toBe('stopped by test'); + expect(t.calls).toHaveLength(1); + expect(t.sent).toEqual([]); + expect(t.logs).toEqual([]); + expect(t.kills()).toBe(1); + }); + + it('turns an unexpected exit into killed with the stderr tail', async () => { + const t = setup(); + t.session.stderr(Buffer.from('fatal: something broke\n')); + t.session.exited(134, null); + const message = await killed(t.session); + expect(message).toContain('exited unexpectedly (code 134)'); + expect(message).toContain('something broke'); + }); + + it('answers a throwing onCall with a tool error instead of crashing', async () => { + const t = setup(() => { + throw new Error('dispatcher bug'); + }); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + await tick(); + expect(t.sent).toEqual([{ type: 'reply', id: 1, reply: { ok: false, error: { name: 'ToolError', code: 'tool-error', message: 'dispatcher bug' } } }]); + }); +}); diff --git a/src/sandbox/session.ts b/src/sandbox/session.ts new file mode 100644 index 0000000..ed7ad83 --- /dev/null +++ b/src/sandbox/session.ts @@ -0,0 +1,200 @@ +import type { CallReply, LogLevel, SandboxOutcome } from '../core/types.js'; +import { errorMessage } from '../core/errors.js'; +import { childMessageSchema, type ChildMessage, type ParentMessage, type SandboxLimits } from './protocol.js'; + +/** What a `ChildSession` needs from the outside world. */ +export interface SessionHooks { + /** Forwards a binding call to the dispatcher. Untrusted `tool` and `args`. */ + onCall(tool: string, args: unknown): Promise; + onLog(level: LogLevel, text: string): void; + /** Writes one message to the child. */ + send(message: ParentMessage): void; + /** Kills the child (SIGKILL). Called exactly once, when the session ends. */ + kill(): void; +} + +export interface SessionOptions { + readonly limits: SandboxLimits; + /** Longest line accepted from the child, in bytes. A longer line kills the child. */ + readonly maxFrameBytes: number; + readonly hooks: SessionHooks; +} + +/** Bytes of log output tolerated above `maxLogBytes` (the child's own "truncated" note). */ +const LOG_SLACK_BYTES = 1_024; +const STDERR_TAIL_CHARS = 2_000; + +/** Builds a `killed` outcome. */ +export function killedOutcome(message: string): SandboxOutcome { + return { ok: false, kind: 'killed', error: { name: 'Killed', message } }; +} + +/** + * Parent side of one sandbox run. It reads the child's stdout as + * newline-delimited JSON and treats every message as hostile: an oversize + * line, invalid JSON, an unknown message type, an unexpected call id, more + * calls than the cap or invalid argument JSON kills the child with outcome + * `killed`. It forwards valid calls to `onCall`, logs to `onLog` (capped), and + * settles `outcome` once. After the outcome is settled nothing reaches the + * hooks any more: later messages and late `onCall` replies are dropped. + */ +export class ChildSession { + readonly outcome: Promise; + readonly #limits: SandboxLimits; + readonly #maxFrameBytes: number; + readonly #hooks: SessionHooks; + readonly #schema: ReturnType; + #resolve!: (outcome: SandboxOutcome) => void; + #finished = false; + #chunks: Buffer[] = []; + #chunkBytes = 0; + #nextCallId = 1; + #logBytes = 0; + #stderr = ''; + + constructor(options: SessionOptions) { + this.#limits = options.limits; + this.#maxFrameBytes = options.maxFrameBytes; + this.#hooks = options.hooks; + this.#schema = childMessageSchema(options.limits); + this.outcome = new Promise((resolve) => { + this.#resolve = resolve; + }); + } + + get finished(): boolean { + return this.#finished; + } + + /** Number of binding calls forwarded to `onCall`. */ + get callCount(): number { + return this.#nextCallId - 1; + } + + /** Feeds raw bytes from the child's stdout. */ + feed(chunk: Buffer): void { + let rest = chunk; + while (!this.#finished) { + const nl = rest.indexOf(0x0a); + if (nl === -1) { + this.#chunkBytes += rest.length; + if (this.#chunkBytes > this.#maxFrameBytes) return this.kill(`sandbox sent a message larger than ${this.#maxFrameBytes} bytes`); + if (rest.length > 0) this.#chunks.push(rest); + return; + } + const head = rest.subarray(0, nl); + if (this.#chunkBytes + head.length > this.#maxFrameBytes) { + return this.kill(`sandbox sent a message larger than ${this.#maxFrameBytes} bytes`); + } + const line = this.#chunks.length === 0 ? head : Buffer.concat([...this.#chunks, head]); + this.#chunks = []; + this.#chunkBytes = 0; + rest = rest.subarray(nl + 1); + this.handleLine(line.toString('utf8')); + } + } + + /** Handles one complete line from the child. */ + handleLine(line: string): void { + if (this.#finished) return; + if (line.trim() === '') return; + let raw: unknown; + try { + raw = JSON.parse(line); + } catch { + return this.kill('sandbox sent a message that is not JSON'); + } + const parsed = this.#schema.safeParse(raw); + if (!parsed.success) return this.kill(`sandbox sent an invalid message: ${parsed.error.issues[0]?.message ?? 'unknown issue'}`); + this.#handle(parsed.data); + } + + /** Keeps the tail of the child's stderr for the `killed` message of an unexpected exit. */ + stderr(chunk: Buffer): void { + this.#stderr = (this.#stderr + chunk.toString('utf8')).slice(-STDERR_TAIL_CHARS); + } + + /** The child exited. Before an outcome, that is a crash. */ + exited(code: number | null, signal: string | null): void { + if (this.#finished) return; + const how = signal !== null ? `signal ${signal}` : `code ${String(code)}`; + const tail = this.#stderr.trim(); + this.kill(`sandbox process exited unexpectedly (${how})${tail ? `: ${tail}` : ''}`); + } + + /** Ends the session with `outcome` and kills the child. Idempotent. */ + finish(outcome: SandboxOutcome): void { + if (this.#finished) return; + this.#finished = true; + this.#chunks = []; + try { + this.#hooks.kill(); + } finally { + this.#resolve(outcome); + } + } + + kill(reason: string): void { + this.finish(killedOutcome(reason)); + } + + #handle(message: ChildMessage): void { + switch (message.type) { + case 'call': + return this.#call(message.id, message.tool, message.args); + case 'log': + return this.#log(message.level, message.text); + case 'done': + return this.#done(message.outcome); + } + } + + #call(id: number, tool: string, argsJson: string): void { + if (id !== this.#nextCallId) return this.kill(`sandbox sent call id ${id}, expected ${this.#nextCallId}`); + if (id > this.#limits.maxCalls) return this.kill(`sandbox exceeded the limit of ${this.#limits.maxCalls} binding calls`); + let args: unknown; + try { + args = JSON.parse(argsJson); + } catch { + return this.kill('sandbox sent call arguments that are not JSON'); + } + this.#nextCallId++; + let pending: Promise; + try { + pending = this.#hooks.onCall(tool, args); + } catch (err) { + pending = Promise.reject(err); + } + pending + .catch((err: unknown): CallReply => ({ ok: false, error: { name: 'ToolError', code: 'tool-error', message: errorMessage(err) } })) + .then((reply) => { + if (this.#finished) return; + try { + this.#hooks.send({ type: 'reply', id, reply }); + } catch (err) { + this.kill(`could not send a reply to the sandbox: ${errorMessage(err)}`); + } + }); + } + + #log(level: LogLevel, text: string): void { + const bytes = Buffer.byteLength(text, 'utf8') + 1; + if (this.#logBytes + bytes > this.#limits.maxLogBytes + LOG_SLACK_BYTES) return; + this.#logBytes += bytes; + this.#hooks.onLog(level, text); + } + + #done(outcome: Extract['outcome']): void { + if (!outcome.ok) { + const { name, message, stack } = outcome.error; + return this.finish({ ok: false, kind: outcome.kind, error: stack === undefined ? { name, message } : { name, message, stack } }); + } + let value: unknown; + try { + value = JSON.parse(outcome.value); + } catch { + return this.kill('sandbox sent a return value that is not JSON'); + } + this.finish({ ok: true, value }); + } +} From 204b82353e579e64186cde1cdc46c1237711c6e0 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:32:04 -0300 Subject: [PATCH 04/43] Expect forward slashes in changedFiles on every platform Co-Authored-By: Claude Opus 5.5 --- src/tools/integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/integration.test.ts b/src/tools/integration.test.ts index 74f8933..7d8b89a 100644 --- a/src/tools/integration.test.ts +++ b/src/tools/integration.test.ts @@ -34,7 +34,7 @@ describe('NodeToolRuntime in the run pipeline', () => { ]); const result = await runScript({ code, transaction: false, timeoutMs: 10_000 }, deps()); expect(result.ok).toBe(true); - expect(result.changedFiles).toEqual(['a.txt', path.join('b', 'c.txt')]); + expect(result.changedFiles).toEqual(['a.txt', 'b/c.txt']); expect(result.diff).toContain('-alpha\n+beta\n'); expect(result.diff).toContain('--- /dev/null\n+++ b/b/c.txt\n'); expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('beta\n'); From 131c8a251163a147493ed19fc33c54391d8bab08 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:34:32 -0300 Subject: [PATCH 05/43] Fix the sandbox on macOS and Windows Lower the default QuickJS stack to 128 KiB: 256 KiB overflowed the Node stack on macOS with Node 22. A host stack overflow now ends the run as a RangeError script error. The permission-model test allows the variables the OS layer adds to every child env (libuv on Windows, macOS's encoding hint). Co-Authored-By: Claude Opus 5.5 --- src/sandbox/child.ts | 4 ++++ src/sandbox/quickjs-sandbox.test.ts | 17 +++++++++++++++-- src/sandbox/quickjs-sandbox.ts | 4 ++-- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/sandbox/child.ts b/src/sandbox/child.ts index 9e1d16c..7cda85e 100644 --- a/src/sandbox/child.ts +++ b/src/sandbox/child.ts @@ -557,6 +557,10 @@ class VmRun { /** A host-side exception (e.g. a WASM trap when an allocation inside the bindings layer fails). */ #hostFailure(err: unknown): void { const message = err instanceof Error ? err.message : String(err); + // Deep recursion that outruns the Node stack before QuickJS's own check: the run ends, as a script error. + if (err instanceof RangeError && /call stack/i.test(message)) { + return this.#finish({ ok: false, kind: 'error', error: { name: 'RangeError', message: 'Maximum call stack size exceeded' } }); + } const oom = this.#memoryFull() || /out of memory/i.test(message); this.#finish({ ok: false, kind: oom ? 'oom' : 'error', error: { name: oom ? 'InternalError' : 'SandboxError', message: oom ? 'out of memory' : message.slice(0, MAX_ERROR_CHARS) } }); } diff --git a/src/sandbox/quickjs-sandbox.test.ts b/src/sandbox/quickjs-sandbox.test.ts index b22e091..b4506e7 100644 --- a/src/sandbox/quickjs-sandbox.test.ts +++ b/src/sandbox/quickjs-sandbox.test.ts @@ -202,6 +202,19 @@ describe('QuickJsSandbox: script semantics', () => { }); }); +/** + * Variables the OS layer adds to every child env even when the parent passes + * an empty one: libuv on Windows copies these required ones, macOS adds its + * text-encoding hint. None of them is a server secret. + */ +const PLATFORM_ENV = new Set( + process.platform === 'win32' + ? ['HOMEDRIVE', 'HOMEPATH', 'LOGONSERVER', 'PATH', 'SYSTEMDRIVE', 'SYSTEMROOT', 'TEMP', 'USERDOMAIN', 'USERNAME', 'USERPROFILE', 'WINDIR'] + : process.platform === 'darwin' + ? ['__CF_USER_TEXT_ENCODING'] + : [], +); + describe('QuickJsSandbox: no ambient authority', () => { it('exposes no host objects, module loading or timers', async () => { const { outcome, calls } = await run(` @@ -257,10 +270,10 @@ describe('QuickJsSandbox: no ambient authority', () => { try { fs.writeFileSync(${JSON.stringify(target)}, 'x'); r.write = 'allowed'; } catch (e) { r.write = e.code; } try { require('child_process').execFileSync(process.execPath, ['-e', '0']); r.spawn = 'allowed'; } catch (e) { r.spawn = e.code; } try { new Function('return 1')(); r.codegen = 'allowed'; } catch (e) { r.codegen = e.name; } - r.env = Object.keys(process.env).filter((k) => !/^systemroot$/i.test(k)); + r.env = Object.keys(process.env).filter((k) => !PLATFORM_ENV.has(k.toUpperCase())); console.log(JSON.stringify(r));`; const flags = childExecArgv(childEntryPath(), 256).filter((flag) => flag !== '--experimental-strip-types'); - const out = spawnSync(process.execPath, [...flags, '-e', probe], { env: childEnv(), encoding: 'utf8' }); + const out = spawnSync(process.execPath, [...flags, '-e', probe.replace('PLATFORM_ENV', `new Set(${JSON.stringify([...PLATFORM_ENV])})`)], { env: childEnv(), encoding: 'utf8' }); expect(JSON.parse(out.stdout)).toEqual({ write: 'ERR_ACCESS_DENIED', spawn: 'ERR_ACCESS_DENIED', codegen: 'EvalError', env: [] }); expect(existsSync(target)).toBe(false); }); diff --git a/src/sandbox/quickjs-sandbox.ts b/src/sandbox/quickjs-sandbox.ts index 0fdb62f..108ab68 100644 --- a/src/sandbox/quickjs-sandbox.ts +++ b/src/sandbox/quickjs-sandbox.ts @@ -23,7 +23,7 @@ export interface QuickJsSandboxOptions { readonly maxResultChars?: number; /** Maximum characters of the JSON arguments of one call. Default 4 MiB. */ readonly maxArgsChars?: number; - /** QuickJS stack limit. Default 256 KiB (deeper values overflow the host stack of the WASM build). */ + /** QuickJS stack limit. Default 128 KiB: the WASM build runs on the Node stack, and 256 KiB already overflows it on macOS with Node 22. */ readonly stackBytes?: number; /** `--max-old-space-size` of the child process, in MiB. Default 256. */ readonly childHeapMb?: number; @@ -37,7 +37,7 @@ const DEFAULTS = { maxLogLineChars: 10_000, maxResultChars: 1024 * 1024, maxArgsChars: 4 * 1024 * 1024, - stackBytes: 256 * 1024, + stackBytes: 128 * 1024, childHeapMb: 256, } as const; From 9cd2af7a0028ec84968691c3c2e39390a6f143cb Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:39:37 -0300 Subject: [PATCH 06/43] Add reproducible benchmark harness: native vs agent-code-mode bench/ runs coding-agent tasks on Claude Code and Codex CLI with native tools, Codex code mode and agent-code-mode, from a deterministic fixture repo, and reports turns, tokens, cost, wall time and pass rate per arm. - fixture/generate.ts: seeded 96-file ES-module project, tests under node --test, byte-identical per seed (hash pinned in a test) - tasks/T1..T8: prompts, bug injection, verifiers and reference solutions - lib/claude.ts, lib/codex.ts: arm commands and configs, transcript parsers (Claude result event; Codex --json usage plus model requests and tool calls from the rollout), tool-surface checks per arm - run.ts: seeded interleaved order, fresh git workspace per run, isolated hosts (Claude --setting-sources project; Codex temp CODEX_HOME with a copied auth file, always deleted), resumable, --dry-run - report.ts: summary.json and a Markdown table (median, min-max) - parser-fixtures: sanitized real native T1 runs from both hosts Co-Authored-By: Claude Opus 5.5 --- bench/.gitignore | 1 + bench/fixture/generate.ts | 481 +++++++++++++++++ bench/hooks/protect-file.mjs | 37 ++ bench/lib/claude.ts | 180 +++++++ bench/lib/codex.ts | 308 +++++++++++ bench/lib/pricing.ts | 29 + bench/lib/proc.ts | 65 +++ bench/lib/record.ts | 139 +++++ bench/lib/rng.ts | 40 ++ bench/lib/sanitize.ts | 66 +++ bench/lib/stats.ts | 15 + bench/lib/workspace.ts | 87 +++ bench/parser-fixtures/claude-A.jsonl | 6 + bench/parser-fixtures/claude-B.jsonl | 6 + bench/parser-fixtures/codex-A.jsonl | 6 + bench/parser-fixtures/codex-A.requests.jsonl | 3 + bench/parser-fixtures/codex-B.jsonl | 7 + bench/parser-fixtures/codex-B.requests.jsonl | 3 + bench/parser-fixtures/codex-C.jsonl | 7 + bench/parser-fixtures/codex-C.requests.jsonl | 5 + bench/parser-fixtures/codex-catalog.json | 64 +++ bench/parser-fixtures/codex-surfaces.json | 55 ++ bench/pricing.json | 14 + bench/report.ts | 167 ++++++ bench/run.ts | 523 +++++++++++++++++++ bench/tasks/T1/solution/apply.ts | 5 + bench/tasks/T1/verify.ts | 9 + bench/tasks/T2/solution/apply.ts | 11 + bench/tasks/T2/verify.ts | 11 + bench/tasks/T3/solution/apply.ts | 5 + bench/tasks/T3/verify.ts | 9 + bench/tasks/T4/solution/apply.ts | 6 + bench/tasks/T4/verify.ts | 21 + bench/tasks/T5/solution/apply.ts | 12 + bench/tasks/T5/verify.ts | 38 ++ bench/tasks/T6/solution/apply.ts | 16 + bench/tasks/T6/verify.ts | 39 ++ bench/tasks/T7/solution/apply.ts | 13 + bench/tasks/T7/verify.ts | 1 + bench/tasks/T8/solution/apply.ts | 12 + bench/tasks/T8/verify.ts | 22 + bench/tasks/checks.ts | 82 +++ bench/tasks/index.ts | 112 ++++ bench/tasks/setup.ts | 20 + bench/tasks/types.ts | 39 ++ bench/test/fixture.test.ts | 54 ++ bench/test/hook.test.ts | 28 + bench/test/parsers.test.ts | 119 +++++ bench/test/proc.test.ts | 46 ++ bench/test/report.test.ts | 104 ++++ bench/test/run.test.ts | 86 +++ bench/test/sanitize.test.ts | 42 ++ bench/test/verifiers.test.ts | 80 +++ bench/tsconfig.json | 12 + package.json | 4 +- vitest.config.ts | 3 +- 56 files changed, 3372 insertions(+), 3 deletions(-) create mode 100644 bench/.gitignore create mode 100644 bench/fixture/generate.ts create mode 100644 bench/hooks/protect-file.mjs create mode 100644 bench/lib/claude.ts create mode 100644 bench/lib/codex.ts create mode 100644 bench/lib/pricing.ts create mode 100644 bench/lib/proc.ts create mode 100644 bench/lib/record.ts create mode 100644 bench/lib/rng.ts create mode 100644 bench/lib/sanitize.ts create mode 100644 bench/lib/stats.ts create mode 100644 bench/lib/workspace.ts create mode 100644 bench/parser-fixtures/claude-A.jsonl create mode 100644 bench/parser-fixtures/claude-B.jsonl create mode 100644 bench/parser-fixtures/codex-A.jsonl create mode 100644 bench/parser-fixtures/codex-A.requests.jsonl create mode 100644 bench/parser-fixtures/codex-B.jsonl create mode 100644 bench/parser-fixtures/codex-B.requests.jsonl create mode 100644 bench/parser-fixtures/codex-C.jsonl create mode 100644 bench/parser-fixtures/codex-C.requests.jsonl create mode 100644 bench/parser-fixtures/codex-catalog.json create mode 100644 bench/parser-fixtures/codex-surfaces.json create mode 100644 bench/pricing.json create mode 100644 bench/report.ts create mode 100644 bench/run.ts create mode 100644 bench/tasks/T1/solution/apply.ts create mode 100644 bench/tasks/T1/verify.ts create mode 100644 bench/tasks/T2/solution/apply.ts create mode 100644 bench/tasks/T2/verify.ts create mode 100644 bench/tasks/T3/solution/apply.ts create mode 100644 bench/tasks/T3/verify.ts create mode 100644 bench/tasks/T4/solution/apply.ts create mode 100644 bench/tasks/T4/verify.ts create mode 100644 bench/tasks/T5/solution/apply.ts create mode 100644 bench/tasks/T5/verify.ts create mode 100644 bench/tasks/T6/solution/apply.ts create mode 100644 bench/tasks/T6/verify.ts create mode 100644 bench/tasks/T7/solution/apply.ts create mode 100644 bench/tasks/T7/verify.ts create mode 100644 bench/tasks/T8/solution/apply.ts create mode 100644 bench/tasks/T8/verify.ts create mode 100644 bench/tasks/checks.ts create mode 100644 bench/tasks/index.ts create mode 100644 bench/tasks/setup.ts create mode 100644 bench/tasks/types.ts create mode 100644 bench/test/fixture.test.ts create mode 100644 bench/test/hook.test.ts create mode 100644 bench/test/parsers.test.ts create mode 100644 bench/test/proc.test.ts create mode 100644 bench/test/report.test.ts create mode 100644 bench/test/run.test.ts create mode 100644 bench/test/sanitize.test.ts create mode 100644 bench/test/verifiers.test.ts create mode 100644 bench/tsconfig.json diff --git a/bench/.gitignore b/bench/.gitignore new file mode 100644 index 0000000..3c1b3b2 --- /dev/null +++ b/bench/.gitignore @@ -0,0 +1 @@ +.work/ diff --git a/bench/fixture/generate.ts b/bench/fixture/generate.ts new file mode 100644 index 0000000..ceaec30 --- /dev/null +++ b/bench/fixture/generate.ts @@ -0,0 +1,481 @@ +import { createHash } from 'node:crypto'; +import { mkdir, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { Rng } from '../lib/rng.ts'; + +/** + * Deterministic fixture repo for the benchmark tasks: a small ES-module + * "orders" project (about 96 files) with tests that run under `node --test` + * and need no install. The same seed gives byte-identical files everywhere. + */ + +export const DEFAULT_FIXTURE_SEED = 1115; + +/** Files of a workspace tree, keyed by POSIX relative path. */ +export type Tree = Map; + +export interface CustomerTotal { + readonly customer: string; + readonly totalCents: number; +} + +/** Facts the verifiers check answers and edits against. */ +export interface FixtureFacts { + readonly seed: number; + /** T1: `service.retryLimit` in config/app.json. */ + readonly retryLimit: number; + /** T3: the two functions whose signatures are asked. */ + readonly signatures: readonly { readonly name: string; readonly file: string; readonly signature: string }[]; + /** T4: customers by paid total, highest first (all of them). */ + readonly customerTotals: readonly CustomerTotal[]; + /** T5: the exported symbol to rename and the files that use it. */ + readonly renameFrom: string; + readonly renameTo: string; + readonly renameFiles: readonly string[]; + /** T4/T6: order files and which of them are paid. */ + readonly orderFiles: readonly string[]; + readonly paidOrderFiles: readonly string[]; + /** T8: handler files and the protected one. */ + readonly handlerFiles: readonly string[]; + readonly protectedFile: string; +} + +export interface Fixture { + readonly files: Tree; + readonly facts: FixtureFacts; +} + +const CUSTOMERS = [ + 'Acme Corp', 'Globex', 'Initech', 'Umbrella Labs', 'Stark Supply', 'Wayne Freight', 'Hooli', 'Vandelay Imports', + 'Soylent Foods', 'Tyrell Systems', 'Cyberdyne Retail', 'Wonka Sweets', +]; + +const FEATURES = [ + 'invoice', 'receipt', 'refund', 'quote', 'cart', 'checkout', 'coupon', 'gift-card', 'loyalty', 'payout', + 'statement', 'subscription', 'tax-summary', 'tip', 'wallet', 'budget', 'deposit', 'ledger', +]; + +const HANDLERS = ['orders', 'payments', 'shipping', 'returns', 'inventory', 'customers', 'reports', 'webhooks', 'search', 'health']; + +const SKUS = ['SKU-APPLE', 'SKU-BREAD', 'SKU-CHEESE', 'SKU-DATES', 'SKU-EGGS', 'SKU-FLOUR', 'SKU-GRAPES', 'SKU-HONEY']; + +function camel(name: string): string { + return name.replace(/-([a-z])/g, (_m, c: string) => c.toUpperCase()); +} + +function pascal(name: string): string { + const c = camel(name); + return c.charAt(0).toUpperCase() + c.slice(1); +} + +function json(value: unknown): string { + return `${JSON.stringify(value, null, 2)}\n`; +} + +interface Order { + id: string; + customer: string; + status: 'paid' | 'refunded' | 'pending'; + createdAt: string; + items: { sku: string; qty: number; unitPriceCents: number }[]; +} + +function orderTotal(order: Order): number { + return order.items.reduce((sum, item) => sum + item.qty * item.unitPriceCents, 0); +} + +function buildOrders(rng: Rng): Order[] { + const notPaid = new Set(rng.shuffle(Array.from({ length: 50 }, (_v, i) => i)).slice(0, 10)); + const orders: Order[] = []; + for (let i = 0; i < 50; i++) { + const n = rng.int(1, 4); + const items = Array.from({ length: n }, () => ({ sku: rng.pick(SKUS), qty: rng.int(1, 9), unitPriceCents: rng.int(150, 9_900) })); + const day = String(rng.int(1, 28)).padStart(2, '0'); + const month = String(rng.int(1, 9)).padStart(2, '0'); + orders.push({ + id: `ORD-${String(i + 1).padStart(3, '0')}`, + customer: rng.pick(CUSTOMERS), + status: notPaid.has(i) ? (i % 2 === 0 ? 'refunded' : 'pending') : 'paid', + createdAt: `2026-${month}-${day}`, + items, + }); + } + return orders; +} + +function customerTotals(orders: readonly Order[]): CustomerTotal[] { + const totals = new Map(); + for (const order of orders) if (order.status === 'paid') totals.set(order.customer, (totals.get(order.customer) ?? 0) + orderTotal(order)); + return [...totals.entries()] + .map(([customer, totalCents]) => ({ customer, totalCents })) + .sort((a, b) => b.totalCents - a.totalCents || a.customer.localeCompare(b.customer)); +} + +/** True when the top 4 totals are distinct, so "top 3" has one answer. */ +function topIsUnambiguous(totals: readonly CustomerTotal[]): boolean { + const top = totals.slice(0, 4).map((t) => t.totalCents); + return new Set(top).size === top.length && top.length >= 4; +} + +const MONEY_JS = `/** Money helpers. Amounts are integer cents. */ + +const SYMBOLS = { USD: '$', EUR: '€', GBP: '£' }; + +export function formatCurrency(cents, currency = 'USD') { + const symbol = SYMBOLS[currency] ?? \`\${currency} \`; + const sign = cents < 0 ? '-' : ''; + const abs = Math.abs(cents); + return \`\${sign}\${symbol}\${Math.floor(abs / 100)}.\${String(abs % 100).padStart(2, '0')}\`; +} + +export function sumCents(values) { + return values.reduce((sum, value) => sum + value, 0); +} +`; + +const STRINGS_JS = `/** String helpers. */ + +export function slugify(text) { + return text + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +export function titleCase(text) { + return text.replace(/\\b([a-z])/g, (_m, c) => c.toUpperCase()); +} + +export function truncate(text, max, ellipsis = '…') { + if (text.length <= max) return text; + return text.slice(0, max - ellipsis.length) + ellipsis; +} +`; + +function shippingJs(baseCents: number, perItemCents: number): string { + return `/** Shipping quotes. */ + +const ZONE_FACTOR = { domestic: 1, nearby: 1.5, international: 3 }; + +export function computeShippingQuote(order, zone, options = {}) { + const factor = ZONE_FACTOR[zone]; + if (factor === undefined) throw new Error(\`unknown zone: \${zone}\`); + const items = order.items.reduce((n, item) => n + item.qty, 0); + let cents = Math.round((${baseCents} + items * ${perItemCents}) * factor); + if (options.express) cents *= 2; + return cents; +} +`; +} + +const SKU_JS = `/** SKU helpers. */ + +export function normalizeSku(raw, strict = false) { + const value = String(raw).trim().toUpperCase().replace(/\\s+/g, '-'); + if (strict && !/^SKU-[A-Z0-9-]+$/.test(value)) throw new Error(\`invalid sku: \${raw}\`); + return value.startsWith('SKU-') ? value : \`SKU-\${value}\`; +} + +export function skuFamily(sku) { + return normalizeSku(sku).split('-')[1] ?? ''; +} +`; + +const DATES_JS = `/** Date helpers (UTC). */ + +export function addBusinessDays(isoDate, days) { + const date = new Date(\`\${isoDate}T00:00:00Z\`); + let left = days; + while (left > 0) { + date.setUTCDate(date.getUTCDate() + 1); + const day = date.getUTCDay(); + if (day !== 0 && day !== 6) left--; + } + return date.toISOString().slice(0, 10); +} +`; + +const PARSE_JS = `/** Parses "sku;qty;unitPriceCents" lines. */ + +export function parseLine(line) { + const [sku, qty, price] = line.split(';').map((part) => part.trim()); + return { sku, qty: Number(qty), unitPriceCents: Number(price) }; +} + +export function parseLines(text) { + return text + .split('\\n') + .map((line) => line.trim()) + .filter((line) => line !== '' && !line.startsWith('#')) + .map(parseLine); +} +`; + +const VALIDATE_JS = `/** Drops lines that cannot be billed. */ + +export function isBillable(line) { + return typeof line.sku === 'string' && line.sku !== '' && Number.isInteger(line.qty) && line.qty > 0 && line.unitPriceCents >= 0; +} + +export function billable(lines) { + return lines.filter(isBillable); +} +`; + +const TOTAL_JS = `/** Totals with an optional percentage discount. */ + +export function subtotal(lines) { + return lines.reduce((sum, line) => sum + line.qty * line.unitPriceCents, 0); +} + +export function total(lines, discountPercent = 0) { + const gross = subtotal(lines); + const discount = Math.round((gross * discountPercent) / 100); + return gross - discount; +} +`; + +const PIPELINE_INDEX_JS = `import { parseLines } from './parse.js'; +import { billable } from './validate.js'; +import { total } from './total.js'; + +/** Parses a price list, keeps billable lines and returns the total in cents. */ +export function runPipeline(text, discountPercent = 0) { + const lines = billable(parseLines(text)); + return { lines: lines.length, totalCents: total(lines, discountPercent) }; +} +`; + +function featureJs(name: string, rng: Rng): string { + const fn = `describe${pascal(name)}`; + const fee = rng.int(0, 499); + return `import { formatCurrency } from '../lib/money.js'; + +/** Human-readable ${name.replace(/-/g, ' ')} line. */ +export function ${fn}(order) { + const cents = order.items.reduce((sum, item) => sum + item.qty * item.unitPriceCents, 0) + ${fee}; + return \`${name} \${order.id}: \${formatCurrency(cents)}\`; +} +`; +} + +function handlerJs(name: string): string { + return `import { formatCurrency } from '../lib/money.js'; + +export const TIMEOUT_MS = 3000; + +/** Handles ${name} requests. */ +export function handle${pascal(name)}(request) { + const amount = request.amountCents ?? 0; + return { route: '/${name}', timeoutMs: TIMEOUT_MS, amount: formatCurrency(amount) }; +} +`; +} + +const MONEY_TEST = `import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { formatCurrency, sumCents } from '../src/lib/money.js'; + +test('formats dollars and cents', () => { + assert.equal(formatCurrency(123456), '$1234.56'); + assert.equal(formatCurrency(5), '$0.05'); +}); + +test('formats negative amounts and other currencies', () => { + assert.equal(formatCurrency(-250, 'EUR'), '-€2.50'); + assert.equal(formatCurrency(100, 'JPY'), 'JPY 1.00'); +}); + +test('sums cents', () => { + assert.equal(sumCents([1, 2, 3]), 6); +}); +`; + +const STRINGS_TEST = `import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { slugify, titleCase, truncate } from '../src/lib/strings.js'; + +test('slugify collapses separators', () => { + assert.equal(slugify(' Hello, World! '), 'hello-world'); +}); + +test('titleCase capitalizes words', () => { + assert.equal(titleCase('fresh green apples'), 'Fresh Green Apples'); +}); + +test('truncate keeps the result within max', () => { + assert.equal(truncate('abcdefghij', 5), 'abcd…'); + assert.equal(truncate('abc', 5), 'abc'); +}); +`; + +const PIPELINE_TEST = `import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { parseLine } from '../src/pipeline/parse.js'; +import { runPipeline } from '../src/pipeline/index.js'; + +const LIST = [ + '# sku;qty;unitPriceCents', + 'SKU-APPLE;2;150', + 'SKU-BREAD ; 1 ; 300', + 'SKU-EGGS;0;999', + 'SKU-HONEY;3;1000', +].join('\\n'); + +test('parseLine reads the three fields', () => { + assert.deepEqual(parseLine('SKU-APPLE;2;150'), { sku: 'SKU-APPLE', qty: 2, unitPriceCents: 150 }); +}); + +test('parseLine trims whitespace around fields', () => { + assert.deepEqual(parseLine(' SKU-BREAD ; 1 ; 300 '), { sku: 'SKU-BREAD', qty: 1, unitPriceCents: 300 }); +}); + +test('pipeline drops lines with zero quantity', () => { + assert.equal(runPipeline(LIST).lines, 3); +}); + +test('pipeline applies the discount', () => { + assert.equal(runPipeline(LIST, 10).totalCents, 3240); +}); + +test('pipeline totals the price list', () => { + assert.equal(runPipeline(LIST).totalCents, 3600); +}); +`; + +function featuresTest(features: readonly string[]): string { + const picked = features.slice(0, 3); + const imports = picked.map((f) => `import { describe${pascal(f)} } from '../src/features/${f}.js';`).join('\n'); + const checks = picked.map((f) => ` assert.match(describe${pascal(f)}(order), /^${f} ORD-T: \\$\\d+\\.\\d\\d$/);`).join('\n'); + return `import { test } from 'node:test'; +import assert from 'node:assert/strict'; +${imports} + +const order = { id: 'ORD-T', items: [{ sku: 'SKU-APPLE', qty: 2, unitPriceCents: 150 }] }; + +test('feature descriptions include a formatted amount', () => { +${checks} +}); +`; +} + +const HANDLERS_TEST = `import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { handleOrders } from '../src/handlers/orders.js'; +import { handleHealth } from '../src/handlers/health.js'; + +test('handlers report their route and a positive timeout', () => { + const res = handleOrders({ amountCents: 1999 }); + assert.equal(res.route, '/orders'); + assert.equal(res.amount, '$19.99'); + assert.ok(handleHealth({}).timeoutMs > 0); +}); +`; + +/** Generates the fixture tree and its facts from a seed. */ +export function generateFixture(seed: number = DEFAULT_FIXTURE_SEED): Fixture { + const rng = new Rng(seed); + const files: Tree = new Map(); + + const retryLimit = rng.int(3, 12); + files.set('package.json', json({ name: 'acme-orders', version: '1.0.0', private: true, type: 'module', scripts: { test: 'node --test' } })); + files.set('README.md', '# acme-orders\n\nOrder tooling for the Acme storefront. Run the tests with `npm test` (Node >= 22, no install needed).\n'); + files.set( + 'config/app.json', + json({ + service: { name: 'acme-orders', port: rng.int(3000, 9000), retryLimit, timeoutMs: rng.int(2, 9) * 1000 }, + features: { refunds: true, giftCards: rng.next() < 0.5, loyalty: true }, + logging: { level: 'info', retainDays: rng.int(7, 90) }, + }), + ); + files.set('config/regions.json', json({ regions: ['domestic', 'nearby', 'international'], defaultRegion: 'domestic', retryLimit: retryLimit + 5 })); + + files.set('src/lib/money.js', MONEY_JS); + files.set('src/lib/strings.js', STRINGS_JS); + files.set('src/lib/shipping.js', shippingJs(rng.int(300, 900), rng.int(50, 250))); + files.set('src/lib/sku.js', SKU_JS); + files.set('src/lib/dates.js', DATES_JS); + + files.set('src/pipeline/parse.js', PARSE_JS); + files.set('src/pipeline/validate.js', VALIDATE_JS); + files.set('src/pipeline/total.js', TOTAL_JS); + files.set('src/pipeline/index.js', PIPELINE_INDEX_JS); + + for (const feature of FEATURES) files.set(`src/features/${feature}.js`, featureJs(feature, rng)); + for (const handler of HANDLERS) files.set(`src/handlers/${handler}.js`, handlerJs(handler)); + + files.set('test/money.test.js', MONEY_TEST); + files.set('test/strings.test.js', STRINGS_TEST); + files.set('test/pipeline.test.js', PIPELINE_TEST); + files.set('test/features.test.js', featuresTest(FEATURES)); + files.set('test/handlers.test.js', HANDLERS_TEST); + + // Regenerate orders until the top 3 customers are unambiguous (deterministic: same rng stream). + let orders = buildOrders(rng); + while (!topIsUnambiguous(customerTotals(orders))) orders = buildOrders(rng); + const orderFiles: string[] = []; + for (const order of orders) { + const file = `data/orders/${order.id.toLowerCase()}.json`; + orderFiles.push(file); + files.set(file, json(order)); + } + + const sorted = new Map([...files.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); + const renameFiles = [...sorted.entries()].filter(([, text]) => /\bformatCurrency\b/.test(text)).map(([file]) => file); + const protectedHandler = HANDLERS[rng.int(1, HANDLERS.length - 2)] ?? 'reports'; + + return { + files: sorted, + facts: { + seed, + retryLimit, + signatures: [ + { name: 'computeShippingQuote', file: 'src/lib/shipping.js', signature: 'computeShippingQuote(order, zone, options = {})' }, + { name: 'normalizeSku', file: 'src/lib/sku.js', signature: 'normalizeSku(raw, strict = false)' }, + ], + customerTotals: customerTotals(orders), + renameFrom: 'formatCurrency', + renameTo: 'formatMoney', + renameFiles, + orderFiles, + paidOrderFiles: orders.filter((o) => o.status === 'paid').map((o) => `data/orders/${o.id.toLowerCase()}.json`), + handlerFiles: HANDLERS.map((h) => `src/handlers/${h}.js`), + protectedFile: `src/handlers/${protectedHandler}.js`, + }, + }; +} + +/** SHA-256 over the sorted (path, content) pairs. */ +export function treeHash(files: ReadonlyMap): string { + const hash = createHash('sha256'); + for (const file of [...files.keys()].sort()) { + hash.update(file); + hash.update('\0'); + hash.update(files.get(file) ?? ''); + hash.update('\0'); + } + return hash.digest('hex'); +} + +/** Writes a tree under `dir` (which must exist or be creatable). */ +export async function writeTree(dir: string, files: ReadonlyMap): Promise { + for (const [file, text] of files) { + const target = path.join(dir, ...file.split('/')); + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, text, 'utf8'); + } +} + +// `node bench/fixture/generate.ts [seed]` writes the fixture and prints its hash. +if (process.argv[1] !== undefined && path.resolve(process.argv[1]) === import.meta.filename) { + const dir = process.argv[2]; + if (dir === undefined) { + process.stderr.write('usage: node bench/fixture/generate.ts [seed]\n'); + process.exitCode = 2; + } else { + const seed = process.argv[3] === undefined ? DEFAULT_FIXTURE_SEED : Number(process.argv[3]); + const fixture = generateFixture(seed); + await writeTree(dir, fixture.files); + process.stdout.write(`${fixture.files.size} files, sha256 ${treeHash(fixture.files)}\n`); + } +} diff --git a/bench/hooks/protect-file.mjs b/bench/hooks/protect-file.mjs new file mode 100644 index 0000000..a1a39dc --- /dev/null +++ b/bench/hooks/protect-file.mjs @@ -0,0 +1,37 @@ +#!/usr/bin/env node +// Example PreToolUse hook for the benchmark (task T8). Works for Claude Code and Codex CLI. +// Usage in a hook command: node protect-file.mjs [...more] +// Blocks (exit 2, reason on stderr) any tool call whose input mentions a protected path or its +// file name: Write/Edit file paths, Bash commands and Codex apply_patch text alike. +import path from 'node:path'; + +const protectedPaths = process.argv.slice(2).map((p) => p.replace(/\\/g, '/')); + +function strings(value, out = []) { + if (typeof value === 'string') out.push(value.replace(/\\/g, '/')); + else if (Array.isArray(value)) for (const v of value) strings(v, out); + else if (value !== null && typeof value === 'object') for (const v of Object.values(value)) strings(v, out); + return out; +} + +let raw = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('data', (chunk) => (raw += chunk)); +process.stdin.on('end', () => { + let input; + try { + input = JSON.parse(raw); + } catch { + process.stderr.write('protect-file: hook input is not JSON\n'); + process.exit(2); + } + const texts = strings(input && typeof input === 'object' ? input.tool_input : undefined); + for (const p of protectedPaths) { + const base = path.posix.basename(p); + if (texts.some((t) => t.includes(p) || new RegExp(`(^|[^A-Za-z0-9_.-])${base.replace(/[.]/g, '\\.')}($|[^A-Za-z0-9_.-])`).test(t))) { + process.stderr.write(`${p} is protected by the repository policy; this change is denied.\n`); + process.exit(2); + } + } + process.exit(0); +}); diff --git a/bench/lib/claude.ts b/bench/lib/claude.ts new file mode 100644 index 0000000..69e5d71 --- /dev/null +++ b/bench/lib/claude.ts @@ -0,0 +1,180 @@ +import { z } from 'zod'; +import type { ArmId, ParsedRun, ToolCalls } from './record.ts'; + +/** Native file and shell tools of Claude Code. Using one of them in the agent-code-mode arm is a fallback. */ +export const CLAUDE_NATIVE_TOOLS = ['Bash', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep', 'NotebookEdit']; +export const CLAUDE_RUN_TOOL = 'mcp__agent-code-mode__run'; + +export interface ClaudeCommandOptions { + readonly arm: ArmId; + readonly model: string; + readonly effort: string; + readonly maxTurns: number; + /** Settings file passed with `--settings` (permissions and hooks). */ + readonly settingsFile: string; + /** MCP config file passed with `--mcp-config`. */ + readonly mcpConfigFile: string; +} + +/** Arguments for `claude`; the prompt goes on stdin. */ +export function claudeArgs(o: ClaudeCommandOptions): string[] { + const args = [ + '-p', + '--output-format', 'stream-json', + '--verbose', + '--model', o.model, + '--effort', o.effort, + '--max-turns', String(o.maxTurns), + '--setting-sources', 'project', + '--no-session-persistence', + '--permission-mode', 'default', + '--settings', o.settingsFile, + '--strict-mcp-config', + '--mcp-config', o.mcpConfigFile, + ]; + if (o.arm === 'A') args.push('--allowedTools', 'Bash,Read,Write,Edit,Glob,Grep'); + else args.push('--allowedTools', CLAUDE_RUN_TOOL, '--disallowedTools', 'Bash,Read,Write,Edit,Glob,Grep,NotebookEdit'); + return args; +} + +/** The `--mcp-config` content for an arm: no servers for A, the agent-code-mode server for B. */ +export function claudeMcpConfig(arm: ArmId, serverEntry: string): unknown { + if (arm === 'A') return { mcpServers: {} }; + return { mcpServers: { 'agent-code-mode': { type: 'stdio', command: process.execPath, args: [serverEntry, 'serve', '--host', 'claude'] } } }; +} + +const UsageEvent = z.object({ + input_tokens: z.number(), + output_tokens: z.number(), + cache_creation_input_tokens: z.number().optional(), + cache_read_input_tokens: z.number().optional(), + output_tokens_details: z.object({ thinking_tokens: z.number().optional() }).passthrough().optional(), +}).passthrough(); + +const ResultEvent = z.object({ + type: z.literal('result'), + subtype: z.string(), + is_error: z.boolean(), + num_turns: z.number().int(), + duration_ms: z.number(), + total_cost_usd: z.number(), + result: z.string().optional(), + usage: UsageEvent, + modelUsage: z.record(z.string(), z.unknown()).optional(), +}).passthrough(); + +const ContentBlock = z.object({ type: z.string() }).passthrough(); +const ToolUse = z.object({ type: z.literal('tool_use'), id: z.string(), name: z.string() }).passthrough(); +const ToolResult = z.object({ type: z.literal('tool_result'), tool_use_id: z.string(), content: z.unknown() }).passthrough(); +const MessageEvent = z.object({ type: z.enum(['assistant', 'user']), message: z.object({ content: z.union([z.string(), z.array(ContentBlock)]) }).passthrough() }).passthrough(); +const InitEvent = z.object({ type: z.literal('system'), subtype: z.literal('init'), model: z.string(), tools: z.array(z.string()).optional() }).passthrough(); + +/** The agent-code-mode `run` result as the server returns it (only the fields the bench reads). */ +const RunResultText = z.object({ calls: z.array(z.object({ tool: z.string(), decision: z.string() }).passthrough()) }).passthrough(); + +function textOf(content: unknown): string { + if (typeof content === 'string') return content; + if (Array.isArray(content)) { + return content + .map((c) => { + const parsed = z.object({ type: z.literal('text'), text: z.string() }).safeParse(c); + return parsed.success ? parsed.data.text : ''; + }) + .join(''); + } + return ''; +} + +function parseJson(line: string): unknown { + try { + return JSON.parse(line); + } catch { + return undefined; + } +} + +export function classifyClaudeTool(name: string): 'native' | 'run' | 'other' { + if (name === CLAUDE_RUN_TOOL) return 'run'; + if (CLAUDE_NATIVE_TOOLS.includes(name)) return 'native'; + return 'other'; +} + +/** Parses a `claude -p --output-format stream-json --verbose` transcript. Throws when there is no result event. */ +export function parseClaudeTranscript(text: string): ParsedRun { + const lines = text.split('\n'); + const seenToolUse = new Set(); + const runToolUses = new Set(); + const calls: ToolCalls = { native: 0, run: 0, codeMode: 0, other: 0, byName: {} }; + const inner: Record = {}; + let innerTotal = 0; + let innerSeen = false; + let model: string | null = null; + let availableTools: string[] | null = null; + let result: z.infer | undefined; + const evidence: Record = { result: [], toolUse: [], innerCalls: [] }; + + lines.forEach((line, i) => { + if (line.trim() === '') return; + const event = parseJson(line); + const init = InitEvent.safeParse(event); + if (init.success) { + model = init.data.model; + availableTools = init.data.tools ?? null; + evidence['init'] = [i + 1]; + return; + } + const res = ResultEvent.safeParse(event); + if (res.success) { + result = res.data; + evidence['result'] = [i + 1]; + return; + } + const msg = MessageEvent.safeParse(event); + if (!msg.success || typeof msg.data.message.content === 'string') return; + for (const block of msg.data.message.content) { + const use = ToolUse.safeParse(block); + if (use.success && msg.data.type === 'assistant' && !seenToolUse.has(use.data.id)) { + seenToolUse.add(use.data.id); + const kind = classifyClaudeTool(use.data.name); + calls[kind] += 1; + calls.byName[use.data.name] = (calls.byName[use.data.name] ?? 0) + 1; + if (kind === 'run') runToolUses.add(use.data.id); + evidence['toolUse']?.push(i + 1); + } + const tr = ToolResult.safeParse(block); + if (tr.success && runToolUses.has(tr.data.tool_use_id)) { + const parsed = RunResultText.safeParse(parseJson(textOf(tr.data.content))); + if (parsed.success) { + innerSeen = true; + for (const call of parsed.data.calls) { + innerTotal += 1; + inner[call.tool] = (inner[call.tool] ?? 0) + 1; + } + evidence['innerCalls']?.push(i + 1); + } + } + } + }); + + if (result === undefined) throw new Error('no result event in the Claude transcript'); + const r: z.infer = result; + return { + turns: r.num_turns, + hostDurationMs: r.duration_ms, + usage: { + input: r.usage.input_tokens, + output: r.usage.output_tokens, + cacheCreation: r.usage.cache_creation_input_tokens ?? 0, + cacheRead: r.usage.cache_read_input_tokens ?? 0, + reasoning: r.usage.output_tokens_details?.thinking_tokens ?? null, + }, + hostCostUsd: r.total_cost_usd, + model: model ?? (r.modelUsage ? (Object.keys(r.modelUsage)[0] ?? null) : null), + finalAnswer: r.result ?? '', + toolCalls: calls, + innerCalls: innerSeen ? { total: innerTotal, byTool: inner } : null, + availableTools, + hostError: r.is_error ? `${r.subtype}` : null, + evidence, + }; +} diff --git a/bench/lib/codex.ts b/bench/lib/codex.ts new file mode 100644 index 0000000..8c18468 --- /dev/null +++ b/bench/lib/codex.ts @@ -0,0 +1,308 @@ +import { z } from 'zod'; +import type { ArmId, ParsedRun, ToolCalls } from './record.ts'; + +/** + * Codex CLI 0.169 facts the arms depend on (checked with `codex debug prompt-input`, no model calls): + * - Every model in the shipped catalog has `tool_mode: "code_mode_only"`: the model only sees `exec` + * (JavaScript that calls nested tools). `features.code_mode` does not change that. + * - A catalog with `tool_mode: "direct"` (config `model_catalog_json`) gives the classic direct tools + * (`exec_command`, `apply_patch`, ...). That is the native arm. + * - `features.shell_tool = false` removes `exec_command`/`write_stdin`; `apply_patch_tool_type: null` + * in the catalog removes `apply_patch`. Together they leave no native file/shell tool (arm C). + * - MCP tools are listed behind `tool_search`; approval is set per server with `default_tools_approval_mode`. + */ + +/** Model-visible native tool names in direct mode. */ +export const CODEX_NATIVE_TOOLS = ['exec_command', 'write_stdin', 'apply_patch', 'shell', 'local_shell', 'container.exec']; +export const CODEX_CODE_MODE_TOOLS = ['exec', 'wait']; +export const CODEX_SERVER_NAME = 'agent-code-mode'; + +export interface CodexHomeOptions { + readonly arm: ArmId; + readonly model: string; + readonly effort: string; + readonly codexHome: string; + /** Path of the catalog override file (arms A and C). */ + readonly catalogFile: string | null; + readonly serverEntry: string; + readonly nodePath: string; +} + +function tomlString(value: string): string { + return JSON.stringify(value); +} + +/** `config.toml` for the temporary CODEX_HOME of one run. */ +export function codexConfigToml(o: CodexHomeOptions): string { + const lines = [ + `model = ${tomlString(o.model)}`, + `model_reasoning_effort = ${tomlString(o.effort)}`, + 'approval_policy = "never"', + 'sandbox_mode = "workspace-write"', + 'suppress_unstable_features_warning = true', + ]; + if (o.catalogFile !== null) lines.push(`model_catalog_json = ${tomlString(o.catalogFile)}`); + lines.push('', '[features]', 'hooks = true'); + if (o.arm === 'B') lines.push('code_mode = true'); + if (o.arm === 'C') { + lines.push('shell_tool = false'); + lines.push( + '', + `[mcp_servers.${CODEX_SERVER_NAME}]`, + `command = ${tomlString(o.nodePath)}`, + `args = [${[o.serverEntry, 'serve', '--host', 'codex'].map(tomlString).join(', ')}]`, + 'default_tools_approval_mode = "approve"', + '', + `[mcp_servers.${CODEX_SERVER_NAME}.env]`, + `CODEX_HOME = ${tomlString(o.codexHome)}`, + ); + } + return `${lines.join('\n')}\n`; +} + +const CatalogSchema = z.object({ models: z.array(z.object({ slug: z.string() }).passthrough()) }).passthrough(); + +/** The catalog override for an arm, from the raw `codex debug models` output; null when the arm uses the shipped catalog. */ +export function catalogForArm(arm: ArmId, rawCatalog: string): string | null { + if (arm === 'B') return null; + const catalog = CatalogSchema.parse(JSON.parse(rawCatalog)); + const models = catalog.models.map((m) => ({ ...m, tool_mode: 'direct', ...(arm === 'C' ? { apply_patch_tool_type: null } : {}) })); + return `${JSON.stringify({ ...catalog, models })}\n`; +} + +export function catalogHasModel(rawCatalog: string, model: string): boolean { + return CatalogSchema.parse(JSON.parse(rawCatalog)).models.some((m) => m.slug === model); +} + +/** `hooks.json` for the temporary CODEX_HOME when a task installs the protect-file hook. */ +export function codexHooksJson(matcher: string, command: string): string { + return `${JSON.stringify({ hooks: { PreToolUse: [{ matcher, hooks: [{ type: 'command', command, timeout: 30 }] }] } }, null, 2)}\n`; +} + +/** Arguments for `codex`; the prompt goes on stdin (`-`). */ +export function codexArgs(workspace: string, withHooks: boolean): string[] { + return ['exec', '--json', '-C', workspace, ...(withHooks ? ['--dangerously-bypass-hook-trust'] : []), '-']; +} + +// --- Rollout extraction ------------------------------------------------------------------------ + +const RolloutLine = z.object({ type: z.string(), payload: z.unknown() }).passthrough(); +const TokenRecord = z.object({ + usage: z.object({ input_tokens: z.number(), cached_input_tokens: z.number(), output_tokens: z.number() }).passthrough(), +}).passthrough(); +const CallItem = z.object({ + type: z.enum(['function_call', 'custom_tool_call']), + name: z.string(), + namespace: z.string().optional(), + arguments: z.string().optional(), + input: z.string().optional(), +}).passthrough(); + +/** + * Keeps only what the bench needs from a Codex rollout file (which also holds account ids and the + * full prompt): one `request` line per model response with its usage, one `call` line per tool call + * the model made, in order. + */ +export function extractCodexRequests(rollout: string): string { + const out: string[] = []; + for (const line of rollout.split('\n')) { + if (line.trim() === '') continue; + let raw: unknown; + try { + raw = JSON.parse(line); + } catch { + continue; + } + const entry = RolloutLine.safeParse(raw); + if (!entry.success) continue; + if (entry.data.type === 'token_usage_record') { + const rec = TokenRecord.safeParse(entry.data.payload); + if (rec.success) out.push(JSON.stringify({ kind: 'request', usage: rec.data.usage })); + } else if (entry.data.type === 'response_item') { + const call = CallItem.safeParse(entry.data.payload); + if (call.success) { + const args = (call.data.arguments ?? call.data.input ?? '').slice(0, 4000); + out.push(JSON.stringify({ kind: 'call', type: call.data.type, name: call.data.name, ...(call.data.namespace ? { namespace: call.data.namespace } : {}), args })); + } + } + } + return out.length > 0 ? `${out.join('\n')}\n` : ''; +} + +// --- Transcript parsing ------------------------------------------------------------------------ + +const TurnCompleted = z.object({ + type: z.literal('turn.completed'), + usage: z.object({ + input_tokens: z.number(), + cached_input_tokens: z.number(), + cache_write_input_tokens: z.number().optional(), + output_tokens: z.number(), + reasoning_output_tokens: z.number().optional(), + }).passthrough(), +}).passthrough(); +const ItemEvent = z.object({ type: z.literal('item.completed'), item: z.object({ type: z.string() }).passthrough() }).passthrough(); +const AgentMessage = z.object({ type: z.literal('agent_message'), text: z.string() }).passthrough(); +const McpItem = z.object({ type: z.literal('mcp_tool_call'), server: z.string(), tool: z.string(), result: z.unknown().optional() }).passthrough(); +const Failure = z.object({ type: z.enum(['turn.failed', 'error']), error: z.object({ message: z.string() }).passthrough().optional(), message: z.string().optional() }).passthrough(); +const RequestLine = z.object({ kind: z.literal('request'), usage: TokenRecord.shape.usage }); +const CallLine = z.object({ kind: z.literal('call'), type: z.string(), name: z.string(), namespace: z.string().optional() }); +const RunResultText = z.object({ calls: z.array(z.object({ tool: z.string() }).passthrough()) }).passthrough(); +const McpResult = z.object({ content: z.array(z.object({ type: z.string(), text: z.string().optional() }).passthrough()) }).passthrough(); + +export function classifyCodexTool(name: string, namespace?: string): 'native' | 'run' | 'codeMode' | 'other' { + const full = namespace ? `${namespace}.${name}` : name; + if (/agent[-_]?code[-_]?mode/.test(full) && /run$/.test(full)) return 'run'; + if (CODEX_CODE_MODE_TOOLS.includes(name)) return 'codeMode'; + if (CODEX_NATIVE_TOOLS.includes(name)) return 'native'; + return 'other'; +} + +function parseJson(line: string): unknown { + try { + return JSON.parse(line); + } catch { + return undefined; + } +} + +/** + * Parses a `codex exec --json` transcript plus the requests file extracted from the rollout. + * Usage is summed over `turn.completed` events; `input` is uncached input (input − cached − cache write), + * `output` includes reasoning tokens (OpenAI usage semantics). Turns are model requests, counted from + * the rollout; null without it. Throws when there is no `turn.completed` event. + */ +export function parseCodexTranscript(json: string, requests: string | null): ParsedRun { + const evidence: Record = { turnCompleted: [], agentMessage: [], innerItems: [], requests: [], calls: [] }; + let input = 0; + let cached = 0; + let cacheWrite = 0; + let output = 0; + let reasoning: number | null = null; + let finalAnswer = ''; + let hostError: string | null = null; + let innerItems = 0; + const innerByType: Record = {}; + const runInner: Record = {}; + let runInnerTotal = 0; + let runInnerSeen = false; + const jsonCalls: ToolCalls = { native: 0, run: 0, codeMode: 0, other: 0, byName: {} }; + + json.split('\n').forEach((line, i) => { + if (line.trim() === '') return; + const event = parseJson(line); + const turn = TurnCompleted.safeParse(event); + if (turn.success) { + const u = turn.data.usage; + input += u.input_tokens; + cached += u.cached_input_tokens; + cacheWrite += u.cache_write_input_tokens ?? 0; + output += u.output_tokens; + if (u.reasoning_output_tokens !== undefined) reasoning = (reasoning ?? 0) + u.reasoning_output_tokens; + evidence['turnCompleted']?.push(i + 1); + return; + } + const fail = Failure.safeParse(event); + if (fail.success && fail.data.type === 'turn.failed') hostError = fail.data.error?.message ?? fail.data.message ?? 'turn failed'; + const item = ItemEvent.safeParse(event); + if (!item.success) return; + const msg = AgentMessage.safeParse(item.data.item); + if (msg.success) { + finalAnswer = msg.data.text; + evidence['agentMessage'] = [i + 1]; + return; + } + const type = item.data.item.type; + if (type === 'command_execution' || type === 'file_change' || type === 'mcp_tool_call' || type === 'web_search') { + innerItems += 1; + innerByType[type] = (innerByType[type] ?? 0) + 1; + evidence['innerItems']?.push(i + 1); + } + const mcp = McpItem.safeParse(item.data.item); + if (mcp.success) { + const name = `mcp__${mcp.data.server}__${mcp.data.tool}`; + const kind = mcp.data.server === CODEX_SERVER_NAME && mcp.data.tool === 'run' ? 'run' : 'other'; + jsonCalls[kind] += 1; + jsonCalls.byName[name] = (jsonCalls.byName[name] ?? 0) + 1; + const result = McpResult.safeParse(mcp.data.result); + if (kind === 'run' && result.success) { + const text = result.data.content.map((c) => c.text ?? '').join(''); + const log = RunResultText.safeParse(parseJson(text)); + if (log.success) { + runInnerSeen = true; + for (const c of log.data.calls) { + runInnerTotal += 1; + runInner[c.tool] = (runInner[c.tool] ?? 0) + 1; + } + } + } + } else if (type === 'command_execution' || type === 'file_change') { + jsonCalls.native += 1; + jsonCalls.byName[type] = (jsonCalls.byName[type] ?? 0) + 1; + } + }); + if ((evidence['turnCompleted']?.length ?? 0) === 0) throw new Error('no turn.completed event in the Codex transcript'); + + let turns: number | null = null; + let calls = jsonCalls; + if (requests !== null && requests.trim() !== '') { + turns = 0; + calls = { native: 0, run: 0, codeMode: 0, other: 0, byName: {} }; + requests.split('\n').forEach((line, i) => { + if (line.trim() === '') return; + const value = parseJson(line); + if (RequestLine.safeParse(value).success) { + turns = (turns ?? 0) + 1; + evidence['requests']?.push(i + 1); + return; + } + const call = CallLine.safeParse(value); + if (call.success) { + const kind = classifyCodexTool(call.data.name, call.data.namespace); + calls[kind] += 1; + const name = call.data.namespace ? `${call.data.namespace}.${call.data.name}` : call.data.name; + calls.byName[name] = (calls.byName[name] ?? 0) + 1; + evidence['calls']?.push(i + 1); + } + }); + } + + const innerCalls = runInnerSeen + ? { total: runInnerTotal, byTool: runInner } + : calls.codeMode > 0 + ? { total: innerItems, byTool: innerByType } + : null; + + return { + turns, + hostDurationMs: null, + usage: { input: Math.max(0, input - cached - cacheWrite), output, cacheCreation: cacheWrite, cacheRead: cached, reasoning }, + hostCostUsd: null, + model: null, + finalAnswer, + toolCalls: calls, + innerCalls, + availableTools: null, + hostError, + evidence, + }; +} + +const PromptItem = z.object({ type: z.string(), tools: z.array(z.unknown()).optional() }).passthrough(); +const ToolEntry = z.object({ type: z.string(), name: z.string().optional(), tools: z.array(z.unknown()).optional() }).passthrough(); + +/** Model-visible tool names (namespace.name) from `codex debug prompt-input` output. */ +export function codexToolSurface(promptInput: string): string[] { + const items = z.array(PromptItem).parse(JSON.parse(promptInput)); + const names: string[] = []; + const walk = (tools: readonly unknown[], prefix: string): void => { + for (const raw of tools) { + const t = ToolEntry.safeParse(raw); + if (!t.success) continue; + if (t.data.type === 'namespace' && t.data.tools) walk(t.data.tools, `${prefix}${t.data.name ?? ''}.`); + else names.push(`${prefix}${t.data.name ?? t.data.type}`); + } + }; + for (const item of items) if (item.type === 'additional_tools' && item.tools) walk(item.tools, ''); + return names; +} diff --git a/bench/lib/pricing.ts b/bench/lib/pricing.ts new file mode 100644 index 0000000..157fcbe --- /dev/null +++ b/bench/lib/pricing.ts @@ -0,0 +1,29 @@ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { z } from 'zod'; +import type { Usage } from './record.ts'; + +const PriceSchema = z.object({ + input: z.number().nonnegative(), + cachedInput: z.number().nonnegative(), + cacheWrite5m: z.number().nonnegative().optional(), + output: z.number().nonnegative(), + date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + source: z.string().url(), +}); +export const PricingSchema = z.object({ currency: z.literal('USD'), unit: z.literal('per 1M tokens'), note: z.string(), models: z.record(z.string(), PriceSchema) }); +export type Pricing = z.infer; + +export const PRICING_FILE = path.join(import.meta.dirname, '..', 'pricing.json'); + +export function loadPricing(file: string = PRICING_FILE): Pricing { + return PricingSchema.parse(JSON.parse(readFileSync(file, 'utf8'))); +} + +/** Cost in USD from usage (uncached input, cache reads, cache writes, output). Null when the model has no price. */ +export function costFromUsage(pricing: Pricing, model: string, usage: Usage): number | null { + const p = pricing.models[model]; + if (p === undefined) return null; + const write = p.cacheWrite5m ?? p.input; + return (usage.input * p.input + usage.cacheRead * p.cachedInput + usage.cacheCreation * write + usage.output * p.output) / 1_000_000; +} diff --git a/bench/lib/proc.ts b/bench/lib/proc.ts new file mode 100644 index 0000000..fbdc365 --- /dev/null +++ b/bench/lib/proc.ts @@ -0,0 +1,65 @@ +import { spawn } from 'node:child_process'; +import { createWriteStream } from 'node:fs'; + +export interface ProcessSpec { + readonly command: string; + readonly args: readonly string[]; + readonly cwd: string; + readonly env: Readonly>; + readonly timeoutMs: number; + /** stdout is streamed into this file. */ + readonly stdoutFile: string; + readonly stderrFile: string; + readonly stdin?: string; +} + +export interface ProcessOutcome { + readonly exitCode: number | null; + readonly signal: string | null; + readonly timedOut: boolean; + /** Wall time measured by the harness, from spawn to exit. */ + readonly wallMs: number; +} + +/** Runs a process with a wall timeout; on timeout kills its whole process group. */ +export function runProcess(spec: ProcessSpec): Promise { + return new Promise((resolve, reject) => { + const out = createWriteStream(spec.stdoutFile); + const err = createWriteStream(spec.stderrFile); + const started = performance.now(); + const child = spawn(spec.command, [...spec.args], { + cwd: spec.cwd, + env: Object.fromEntries(Object.entries(spec.env).filter((e): e is [string, string] => e[1] !== undefined)), + stdio: ['pipe', 'pipe', 'pipe'], + detached: process.platform !== 'win32', + }); + let timedOut = false; + const kill = (): void => { + timedOut = true; + try { + if (process.platform !== 'win32' && child.pid !== undefined) process.kill(-child.pid, 'SIGKILL'); + else child.kill('SIGKILL'); + } catch { + child.kill('SIGKILL'); + } + }; + const timer = setTimeout(kill, spec.timeoutMs); + child.stdout.pipe(out); + child.stderr.pipe(err); + child.on('error', (e) => { + clearTimeout(timer); + reject(e); + }); + child.on('close', (exitCode, signal) => { + clearTimeout(timer); + const wallMs = Math.round(performance.now() - started); + let pending = 2; + const done = (): void => { + if (--pending === 0) resolve({ exitCode, signal, timedOut, wallMs }); + }; + out.end(done); + err.end(done); + }); + child.stdin.end(spec.stdin ?? ''); + }); +} diff --git a/bench/lib/record.ts b/bench/lib/record.ts new file mode 100644 index 0000000..265de2d --- /dev/null +++ b/bench/lib/record.ts @@ -0,0 +1,139 @@ +import { z } from 'zod'; + +/** Arms per host. Claude: A native, B agent-code-mode. Codex: A native, B Codex code mode, C agent-code-mode. */ +export const HOST_ARMS = { claude: ['A', 'B'], codex: ['A', 'B', 'C'] } as const; +export type ArmId = 'A' | 'B' | 'C'; + +export const ARM_LABELS: Readonly>>> = { + claude: { A: 'native tools', B: 'agent-code-mode (strict)' }, + codex: { A: 'native tools (direct)', B: 'Codex code mode', C: 'agent-code-mode (strict)' }, +}; + +const Counts = z.record(z.string(), z.number().int().nonnegative()); + +export const UsageSchema = z.object({ + input: z.number().nonnegative(), + output: z.number().nonnegative(), + cacheCreation: z.number().nonnegative(), + cacheRead: z.number().nonnegative(), + /** Reasoning tokens when the host reports them separately (already included in `output` on Codex). */ + reasoning: z.number().nonnegative().nullable(), +}); +export type Usage = z.infer; + +export const ToolCallsSchema = z.object({ + /** Native file/shell tool calls made by the model (Bash, Read, Edit, exec_command, apply_patch...). */ + native: z.number().int().nonnegative(), + /** agent-code-mode `run` calls. */ + run: z.number().int().nonnegative(), + /** Codex code-mode `exec`/`wait` calls. */ + codeMode: z.number().int().nonnegative(), + /** Anything else (ToolSearch, Task, tool_search...). */ + other: z.number().int().nonnegative(), + byName: Counts, +}); +export type ToolCalls = z.infer; + +/** Metrics parsed from one host transcript. Every number comes from a host event, never an estimate. */ +export const ParsedRunSchema = z.object({ + /** Claude `num_turns`; Codex number of model requests (rollout token records). */ + turns: z.number().int().nonnegative().nullable(), + /** Host-reported duration (Claude `duration_ms`), null when the host does not report one. */ + hostDurationMs: z.number().nonnegative().nullable(), + usage: UsageSchema.nullable(), + /** Claude `total_cost_usd`; null for Codex (computed from pricing.json by the runner). */ + hostCostUsd: z.number().nonnegative().nullable(), + model: z.string().nullable(), + finalAnswer: z.string(), + toolCalls: ToolCallsSchema, + /** Calls made inside scripts: agent-code-mode call log or Codex code-mode nested items. Null when not observable. */ + innerCalls: z.object({ total: z.number().int().nonnegative(), byTool: Counts }).nullable(), + /** Tools the model could call: Claude `init` event; Codex `codex debug prompt-input` (set by the runner). */ + availableTools: z.array(z.string()).nullable(), + /** Host-reported error, e.g. a Claude result with `is_error`. */ + hostError: z.string().nullable(), + /** Where the numbers came from: transcript line numbers (1-based) of the source events. */ + evidence: z.record(z.string(), z.array(z.number().int().positive())), +}); +export type ParsedRun = z.infer; + +export const RunRecordSchema = z.object({ + schema: z.literal(1), + id: z.string(), + host: z.enum(['claude', 'codex']), + arm: z.enum(['A', 'B', 'C']), + armLabel: z.string(), + task: z.string(), + run: z.number().int().positive(), + round: z.number().int().positive(), + orderIndex: z.number().int().nonnegative(), + dryRun: z.boolean(), + model: z.string(), + effort: z.string(), + startedAt: z.string(), + exitCode: z.number().int().nullable(), + timedOut: z.boolean(), + wallMs: z.number().nonnegative(), + parsed: ParsedRunSchema.nullable(), + parseError: z.string().nullable(), + costUsd: z.number().nonnegative().nullable(), + costSource: z.enum(['host', 'pricing.json', 'none']), + verify: z.object({ pass: z.boolean(), details: z.array(z.string()) }), + /** The arm used agent-code-mode but the model also used native file/shell tools. */ + fallback: z.boolean(), + /** False when the observed tool usage does not match the arm label, or the run did not complete. */ + valid: z.boolean(), + invalidReasons: z.array(z.string()), + files: z.record(z.string(), z.string()), +}); +export type RunRecord = z.infer; + +export interface ArmCheck { + readonly fallback: boolean; + readonly reasons: readonly string[]; +} + +/** Checks that observed tool usage matches the arm. */ +export function checkArm(host: 'claude' | 'codex', arm: ArmId, calls: ToolCalls): ArmCheck { + const reasons: string[] = []; + const total = calls.native + calls.run + calls.codeMode + calls.other; + const acm = (host === 'claude' && arm === 'B') || (host === 'codex' && arm === 'C'); + if (acm) { + if (calls.run === 0) reasons.push('agent-code-mode arm made no run call'); + if (calls.codeMode > 0) reasons.push('agent-code-mode arm used Codex code mode'); + return { fallback: calls.native > 0, reasons }; + } + if (calls.run > 0) reasons.push('arm made agent-code-mode run calls'); + if (host === 'codex' && arm === 'B') { + if (calls.codeMode === 0 && total > 0) reasons.push('Codex code-mode arm made tool calls outside exec'); + if (calls.native > 0) reasons.push('Codex code-mode arm made direct native tool calls'); + } else if (calls.codeMode > 0) { + reasons.push('native arm used Codex code mode'); + } + return { fallback: false, reasons }; +} + +const CLAUDE_NATIVE = ['Bash', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep', 'NotebookEdit']; +const CODEX_NATIVE = ['exec_command', 'write_stdin', 'apply_patch', 'shell', 'local_shell']; + +/** Checks that the tools the model could see match the arm (a config error shows up here before any tool call). */ +export function checkSurface(host: 'claude' | 'codex', arm: ArmId, tools: readonly string[]): string[] { + const reasons: string[] = []; + const base = tools.map((t) => t.slice(t.lastIndexOf('.') + 1)); + const has = (name: string): boolean => base.includes(name) || tools.includes(name); + if (host === 'claude') { + const run = has('mcp__agent-code-mode__run'); + const native = CLAUDE_NATIVE.filter(has); + if (arm === 'A' && run) reasons.push('native arm sees the run tool'); + if (arm === 'A' && !has('Bash')) reasons.push('native arm does not see Bash'); + if (arm === 'B' && !run) reasons.push('agent-code-mode arm does not see the run tool (server not connected?)'); + if (arm === 'B' && native.length > 0) reasons.push(`agent-code-mode arm sees native tools: ${native.join(', ')}`); + return reasons; + } + const native = CODEX_NATIVE.filter(has); + const exec = has('exec'); + if (arm === 'A' && (exec || !has('exec_command'))) reasons.push('native arm is not in direct tool mode'); + if (arm === 'B' && (!exec || native.length > 0)) reasons.push('Codex code-mode arm is not in code_mode_only'); + if (arm === 'C' && (exec || native.length > 0)) reasons.push(`agent-code-mode arm sees native or code-mode tools: ${[...native, ...(exec ? ['exec'] : [])].join(', ')}`); + return reasons; +} diff --git a/bench/lib/rng.ts b/bench/lib/rng.ts new file mode 100644 index 0000000..f59a434 --- /dev/null +++ b/bench/lib/rng.ts @@ -0,0 +1,40 @@ +/** Small deterministic PRNG (mulberry32). Same seed, same sequence, on every platform. */ +export class Rng { + private state: number; + + constructor(seed: number) { + this.state = seed >>> 0; + } + + /** Float in [0, 1). */ + next(): number { + this.state = (this.state + 0x6d2b79f5) >>> 0; + let t = this.state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + } + + /** Integer in [min, max], both inclusive. */ + int(min: number, max: number): number { + return min + Math.floor(this.next() * (max - min + 1)); + } + + pick(items: readonly T[]): T { + const item = items[Math.floor(this.next() * items.length)]; + if (item === undefined) throw new Error('pick from an empty list'); + return item; + } + + /** Fisher-Yates shuffle into a new array. */ + shuffle(items: readonly T[]): T[] { + const out = [...items]; + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(this.next() * (i + 1)); + const a = out[i] as T; + out[i] = out[j] as T; + out[j] = a; + } + return out; + } +} diff --git a/bench/lib/sanitize.ts b/bench/lib/sanitize.ts new file mode 100644 index 0000000..0e39ba3 --- /dev/null +++ b/bench/lib/sanitize.ts @@ -0,0 +1,66 @@ +import os from 'node:os'; + +export interface SanitizeContext { + /** Absolute paths replaced by a label, e.g. the workspace by ``. Longest first wins. */ + readonly paths: readonly { readonly path: string; readonly label: string }[]; + readonly home: string; + readonly username: string; + readonly hostname: string; +} + +export function defaultSanitizeContext(paths: SanitizeContext['paths']): SanitizeContext { + let username = ''; + try { + username = os.userInfo().username; + } catch { + username = process.env['USER'] ?? process.env['USERNAME'] ?? ''; + } + return { paths, home: os.homedir(), username, hostname: os.hostname() }; +} + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Forms a path takes in transcripts: as is, with forward slashes (also inside file:// URLs), + * JSON-escaped, and dash-encoded the way Claude Code names its per-project folders. + */ +function pathForms(p: string): string[] { + const forms = new Set([p, p.replace(/\\/g, '/'), JSON.stringify(p).slice(1, -1), p.replace(/[\\/.:]/g, '-')]); + return [...forms].filter((f) => f.length > 1).sort((a, b) => b.length - a.length); +} + +const SECRET_PATTERNS: readonly [RegExp, string][] = [ + [/\bsk-ant-[A-Za-z0-9_-]{10,}/g, ''], + [/\bsk-[A-Za-z0-9_-]{16,}/g, ''], + [/\bgh[pousr]_[A-Za-z0-9]{20,}/g, ''], + [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, ''], + [/\bxox[abpr]-[A-Za-z0-9-]{10,}/g, ''], + [/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, ''], + [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/g, '$1 '], + [/("(?:access_token|refresh_token|id_token|api_key|apiKey|token|password|secret)"\s*:\s*")[^"]+(")/gi, '$1$2'], + [/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, ''], +]; + +/** + * Removes what identifies the machine or the person from a transcript: known absolute paths + * (workspace, repo, temp homes), the home directory, the username, the hostname, emails and + * token-shaped strings. Tool names, workspace-relative arguments and usage numbers stay. + */ +export function sanitize(text: string, ctx: SanitizeContext): string { + let out = text; + const labeled = [...ctx.paths, ...(ctx.home.length > 1 ? [{ path: ctx.home, label: '~' }] : [])] + .flatMap((p) => pathForms(p.path).map((form) => ({ form, label: p.label }))) + .sort((a, b) => b.form.length - a.form.length); + for (const { form, label } of labeled) out = out.split(form).join(label); + for (const [pattern, replacement] of SECRET_PATTERNS) out = out.replace(pattern, replacement); + // Generic home-directory paths of any user (e.g. in error messages). + out = out.replace(/\/(home|Users)\/[^/\s"'\\]+/g, '/$1/'); + out = out.replace(/-(home|Users)-[^-\s"'/\\]+/g, '-$1-'); + out = out.replace(/([A-Za-z]:\\\\?Users\\\\?)[^\\\s"']+/g, '$1'); + for (const [word, label] of [[ctx.hostname, ''], [ctx.username, '']] as const) { + if (word.length >= 3) out = out.replace(new RegExp(`(? a - b); + const mid = Math.floor(sorted.length / 2); + const median = sorted.length % 2 === 1 ? (sorted[mid] as number) : ((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2; + return { median, min: sorted[0] as number, max: sorted[sorted.length - 1] as number, n: sorted.length }; +} diff --git a/bench/lib/workspace.ts b/bench/lib/workspace.ts new file mode 100644 index 0000000..d4c65e1 --- /dev/null +++ b/bench/lib/workspace.ts @@ -0,0 +1,87 @@ +import { execFileSync } from 'node:child_process'; +import { mkdir, readdir } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { generateFixture, writeTree, type Fixture, type Tree } from '../fixture/generate.ts'; +import { HOOKS_DIR } from '../tasks/index.ts'; +import type { TaskDef } from '../tasks/types.ts'; + +export type HostId = 'claude' | 'codex'; + +/** Native tools the Claude workspace allows (arm A uses them; arm B's inner calls are checked against the same rules). */ +export const CLAUDE_ALLOWED_TOOLS = ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'mcp__agent-code-mode__run']; + +/** Claude PreToolUse matcher for the protect-file hook. */ +export const CLAUDE_HOOK_MATCHER = 'Write|Edit|MultiEdit|NotebookEdit|Bash'; +/** Codex PreToolUse matcher for the protect-file hook (`Write|Edit` also match apply_patch). */ +export const CODEX_HOOK_MATCHER = 'Bash|apply_patch|Write|Edit'; + +export function hookCommand(protectedFile: string): string { + const script = path.join(HOOKS_DIR, 'protect-file.mjs'); + return `node ${JSON.stringify(script)} ${JSON.stringify(protectedFile)}`; +} + +/** The project settings written into a Claude workspace. */ +export function claudeProjectSettings(task: TaskDef, fixture: Fixture): unknown { + const settings: Record = { permissions: { allow: CLAUDE_ALLOWED_TOOLS }, autoMemoryEnabled: false }; + if (task.protectedHook) { + settings['hooks'] = { + PreToolUse: [{ matcher: CLAUDE_HOOK_MATCHER, hooks: [{ type: 'command', command: hookCommand(fixture.facts.protectedFile), timeout: 30 }] }], + }; + } + return settings; +} + +/** The tree committed in a fresh workspace: fixture, task setup and, for Claude, project settings. */ +export function initialTree(task: TaskDef, host: HostId, fixture: Fixture): Tree { + const tree = new Map(task.setup(fixture.files, fixture.facts)); + if (host === 'claude') tree.set('.claude/settings.json', `${JSON.stringify(claudeProjectSettings(task, fixture), null, 2)}\n`); + return new Map([...tree.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); +} + +const GIT_DATE = '2026-01-01T00:00:00Z'; + +function git(cwd: string, args: readonly string[]): string { + return execFileSync('git', ['-c', 'core.autocrlf=false', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=.git/no-hooks', ...args], { + cwd, + encoding: 'utf8', + env: { + ...process.env, + GIT_CONFIG_GLOBAL: path.join(os.tmpdir(), 'agent-code-mode-bench-no-gitconfig'), + GIT_CONFIG_NOSYSTEM: '1', + GIT_AUTHOR_NAME: 'bench', + GIT_AUTHOR_EMAIL: 'bench@example.invalid', + GIT_COMMITTER_NAME: 'bench', + GIT_COMMITTER_EMAIL: 'bench@example.invalid', + GIT_AUTHOR_DATE: GIT_DATE, + GIT_COMMITTER_DATE: GIT_DATE, + }, + }); +} + +export interface Workspace { + readonly dir: string; + readonly initial: Tree; + readonly fixture: Fixture; + /** Commit of the initial tree (stable across machines). */ + readonly baseCommit: string; +} + +/** Creates a fresh workspace at `dir` (must not exist or be empty): writes the tree, `git init` and one commit. */ +export async function createWorkspace(dir: string, task: TaskDef, host: HostId, fixtureSeed: number): Promise { + await mkdir(dir, { recursive: true }); + if ((await readdir(dir)).length > 0) throw new Error(`workspace dir is not empty: ${dir}`); + const fixture = generateFixture(fixtureSeed); + const initial = initialTree(task, host, fixture); + await writeTree(dir, initial); + git(dir, ['init', '-q', '-b', 'main']); + git(dir, ['add', '-A']); + git(dir, ['commit', '-q', '--no-verify', '-m', `fixture ${fixtureSeed} for ${task.id}`]); + return { dir, initial, fixture, baseCommit: git(dir, ['rev-parse', 'HEAD']).trim() }; +} + +/** `git status --porcelain` and the diff against the initial commit, for inspection. */ +export function workspaceDiff(dir: string): { status: string; diff: string } { + git(dir, ['add', '-A', '-N']); + return { status: git(dir, ['status', '--porcelain']), diff: git(dir, ['diff', 'HEAD']) }; +} diff --git a/bench/parser-fixtures/claude-A.jsonl b/bench/parser-fixtures/claude-A.jsonl new file mode 100644 index 0000000..346bc81 --- /dev/null +++ b/bench/parser-fixtures/claude-A.jsonl @@ -0,0 +1,6 @@ +{"type":"system","subtype":"init","cwd":"","session_id":"1171680e-6883-4bec-8e1b-ad45a7fbe8cb","tools":["Task","Bash","CronCreate","CronDelete","CronList","DesignSync","Edit","EnterWorktree","ExitWorktree","Glob","Grep","ListAgents","Monitor","NotebookEdit","PushNotification","Read","RemoteTrigger","ReportFindings","ScheduleWakeup","SendMessage","Skill","TaskStop","ToolSearch","WebFetch","WebSearch","Workflow","Write"],"mcp_servers":[],"model":"claude-haiku-5-5","permissionMode":"default","slash_commands":["deep-research","design","design-sync","dataviz","update-config","verify","debug","code-review","simplify","batch","fewer-permission-prompts","doctor","loop","schedule","claude-api","workflow-authoring","run","run-skill-generator","plugin-authoring","advisor","agents","auto-mode-setup","autocompact","clear","color","compact","config","output-style","context","effort","fast","focus","heapdump","init","mcp","import","model","__remote-workflow","workflow-launch-exec","reload-plugins","reload-skills","rename","ultrareview","security-review","usage-credits","extra-usage","usage","insights","recap","skill-doctor","goal","design-consent","design-revoke","list-agents","team-onboarding"],"terminal_slash_commands":["doctor","color","focus","reload-plugins"],"apiKeySource":"none","claude_code_version":"2.1.325","output_style":"default","agents":["claude","Explore","general-purpose","Plan","statusline-setup"],"skills":["deep-research","design","design-sync","dataviz","update-config","verify","debug","code-review","simplify","batch","fewer-permission-prompts","doctor","loop","schedule","claude-api","workflow-authoring","run","run-skill-generator","plugin-authoring"],"plugins":[{"name":"cc-plugin-agents-md","path":"builtin","source":"cc-plugin-agents-md@builtin"},{"name":"cc-plugin-telemetry","path":"builtin","source":"cc-plugin-telemetry@builtin"},{"name":"cc-plugin-privacy","path":"builtin","source":"cc-plugin-privacy@builtin"},{"name":"cc-plugin-plugin-authoring","path":"builtin","source":"cc-plugin-plugin-authoring@builtin"}],"capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1"],"analytics_disabled":false,"product_feedback_disabled":false,"uuid":"b50d84fc-6947-4438-91df-de09f411d41a","original_cwd":"","additional_directories":[],"messaging_socket_path":"/tmp/cc-socks/267871.sock","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","per_turn_effort_active":true,"ultrathink_available":false,"ultrathink_typed_raises":false,"view_mode":"default"} +{"type":"assistant","message":{"model":"claude-haiku-5-5","id":"msg_011Ch5bVWnxptriPQCa1Yypf","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01GmP1Eqy1G1J2FhVK378AU8","name":"Read","input":{"file_path":"/config/app.json"},"caller":{"type":"direct"}}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":16797,"cache_read_input_tokens":12932,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":16797},"output_tokens":20,"service_tier":"standard","inference_geo":"global","speed":"standard"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"1171680e-6883-4bec-8e1b-ad45a7fbe8cb","uuid":"bb3988ea-50d0-4865-8a36-47319dcbeb40","timestamp":"2026-11-15T23:39:03.547Z","request_id":"req_011Ch5bVWZ5KJGbpTWHtWgpc","wire_tool_inputs":{"toolu_01GmP1Eqy1G1J2FhVK378AU8":{"file_path":"/config/app.json"}}} +{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","resetsAt":1795086000,"rateLimitType":"seven_day","utilization":0.9,"overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false,"surpassedThreshold":0.75,"unifiedWindows":{"seven_day":{"utilization":0.9,"resetsAt":1795086000,"status":"allowed_warning","surpassedThreshold":0.75}},"overageEnabled":false},"uuid":"5ad7a7fe-f410-40e4-9c6d-1ef0863f78ff","session_id":"1171680e-6883-4bec-8e1b-ad45a7fbe8cb"} +{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01GmP1Eqy1G1J2FhVK378AU8","type":"tool_result","content":"1\t{\n2\t \"service\": {\n3\t \"name\": \"acme-orders\",\n4\t \"port\": 6993,\n5\t \"retryLimit\": 7,\n6\t \"timeoutMs\": 2000\n7\t },\n8\t \"features\": {\n9\t \"refunds\": true,\n10\t \"giftCards\": true,\n11\t \"loyalty\": true\n12\t },\n13\t \"logging\": {\n14\t \"level\": \"info\",\n15\t \"retainDays\": 65\n16\t }\n17\t}\n18\t"}]},"parent_tool_use_id":null,"session_id":"1171680e-6883-4bec-8e1b-ad45a7fbe8cb","uuid":"72f82cc8-b431-4a8c-a129-5233b79224df","timestamp":"2026-11-15T23:39:03.577Z","tool_use_result":{"type":"text","file":{"filePath":"/config/app.json","content":"{\n \"service\": {\n \"name\": \"acme-orders\",\n \"port\": 6993,\n \"retryLimit\": 7,\n \"timeoutMs\": 2000\n },\n \"features\": {\n \"refunds\": true,\n \"giftCards\": true,\n \"loyalty\": true\n },\n \"logging\": {\n \"level\": \"info\",\n \"retainDays\": 65\n }\n}\n","numLines":18,"startLine":1,"totalLines":18}},"tool_result_meta":[{"id":"toolu_01GmP1Eqy1G1J2FhVK378AU8","permission_decision":{"decision":"accept","source":"config","reason_type":"rule"}}]} +{"type":"assistant","message":{"model":"claude-haiku-5-5","id":"msg_011Ch5bVeR6d4FwS5RE4dv9v","type":"message","role":"assistant","content":[{"type":"text","text":"`service.retryLimit` em `config/app.json` está definido como 7. Não alterei nenhum arquivo.\n\nANSWER: 7"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":320,"cache_read_input_tokens":29729,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":320},"output_tokens":8,"service_tier":"standard","inference_geo":"global","speed":"standard"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"1171680e-6883-4bec-8e1b-ad45a7fbe8cb","uuid":"2e5ab5d2-c4b5-4cf8-a77c-e209a0be7ced","timestamp":"2026-11-15T23:39:04.986Z","request_id":"req_011Ch5bVeBTqD9MzQUoRohxT"} +{"duration_api_ms":3174,"stop_reason":"end_turn","session_id":"1171680e-6883-4bec-8e1b-ad45a7fbe8cb","total_cost_usd":0.00394041,"usage":{"input_tokens":4,"cache_creation_input_tokens":17117,"cache_read_input_tokens":42661,"output_tokens":180,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":17117,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[{"input_tokens":2,"output_tokens":49,"cache_read_input_tokens":29729,"cache_creation_input_tokens":320,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":320},"type":"message"}],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-haiku-5-5":{"inputTokens":4,"outputTokens":180,"cacheReadInputTokens":42661,"cacheCreationInputTokens":17117,"webSearchRequests":0,"costUSD":0.00394041,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":17117,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":false,"num_turns":2,"subtype":"success","api_error_status":null,"result":"`service.retryLimit` em `config/app.json` está definido como 7. Não alterei nenhum arquivo.\n\nANSWER: 7","ttft_ms":2380,"type":"result","duration_ms":3833,"uuid":"5f6e525f-3c69-4ef1-8258-be23c2b6e00c","ttft_stream_ms":1962,"time_to_request_ms":633,"first_content_frame_ms":1962,"queued_turn_count":0,"result_index":0,"model_usage_since_last_result":{"claude-haiku-5-5":{"inputTokens":4,"outputTokens":180,"cacheReadInputTokens":42661,"cacheCreationInputTokens":17117,"webSearchRequests":0,"costUSD":0.00394041,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":17117,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}},"credential_expires_at":"2026-12-02T21:22:59.919Z"} diff --git a/bench/parser-fixtures/claude-B.jsonl b/bench/parser-fixtures/claude-B.jsonl new file mode 100644 index 0000000..023228c --- /dev/null +++ b/bench/parser-fixtures/claude-B.jsonl @@ -0,0 +1,6 @@ +{"type": "bench_note", "note": "Synthetic canned transcript (hand-written, not a model run) for --dry-run and parser tests."} +{"type": "system", "subtype": "init", "cwd": "", "session_id": "00000000-0000-4000-8000-000000000001", "tools": ["Task", "ToolSearch", "mcp__agent-code-mode__run"], "mcp_servers": [{"name": "agent-code-mode", "status": "connected"}], "model": "claude-sonnet-5-5", "permissionMode": "default"} +{"type": "assistant", "message": {"id": "msg_1", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_1", "name": "mcp__agent-code-mode__run", "input": {"code": "const cfg = JSON.parse(await read('config/app.json'));\nawait grep('retryLimit', 'config');\nawait read('config/regions.json');\nreturn cfg.service.retryLimit;"}}], "usage": {"input_tokens": 3, "output_tokens": 60, "cache_creation_input_tokens": 15000, "cache_read_input_tokens": 11000}}, "session_id": "00000000-0000-4000-8000-000000000001"} +{"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": [{"type": "text", "text": "{\"ok\": true, \"result\": 7, \"logs\": [], \"calls\": [{\"id\": \"c1\", \"tool\": \"read\", \"summary\": \"read config/app.json\", \"decision\": \"allowed\", \"durationMs\": 2}, {\"id\": \"c2\", \"tool\": \"grep\", \"summary\": \"grep retryLimit\", \"decision\": \"allowed\", \"durationMs\": 4}, {\"id\": \"c3\", \"tool\": \"read\", \"summary\": \"read config/regions.json\", \"decision\": \"allowed\", \"durationMs\": 1}], \"changedFiles\": [], \"diff\": \"\", \"warnings\": []}"}]}]}, "session_id": "00000000-0000-4000-8000-000000000001"} +{"type": "assistant", "message": {"id": "msg_2", "role": "assistant", "content": [{"type": "text", "text": "service.retryLimit is 7.\n\nANSWER: 7"}], "usage": {"input_tokens": 2, "output_tokens": 12, "cache_creation_input_tokens": 400, "cache_read_input_tokens": 26000}}, "session_id": "00000000-0000-4000-8000-000000000001"} +{"type": "result", "subtype": "success", "is_error": false, "duration_ms": 5200, "duration_api_ms": 4100, "num_turns": 2, "result": "service.retryLimit is 7.\n\nANSWER: 7", "session_id": "00000000-0000-4000-8000-000000000001", "total_cost_usd": 0.0521, "usage": {"input_tokens": 5, "cache_creation_input_tokens": 15400, "cache_read_input_tokens": 37000, "output_tokens": 72, "output_tokens_details": {"thinking_tokens": 0}}, "modelUsage": {"claude-sonnet-5-5": {"inputTokens": 5, "outputTokens": 72}}, "permission_denials": []} diff --git a/bench/parser-fixtures/codex-A.jsonl b/bench/parser-fixtures/codex-A.jsonl new file mode 100644 index 0000000..8f1b334 --- /dev/null +++ b/bench/parser-fixtures/codex-A.jsonl @@ -0,0 +1,6 @@ +{"type":"thread.started","thread_id":"01a1e193-8128-7343-894f-bf5fb1dc2bd9"} +{"type":"turn.started"} +{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"/usr/bin/bash -lc \"rg -n '\\\"retryLimit\\\"' config/app.json\"","aggregated_output":"","exit_code":null,"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_0","type":"command_execution","command":"/usr/bin/bash -lc \"rg -n '\\\"retryLimit\\\"' config/app.json\"","aggregated_output":"5: \"retryLimit\": 7,\n","exit_code":0,"status":"completed"}} +{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"`service.retryLimit` is `7`.\n\nANSWER: 7"}} +{"type":"turn.completed","usage":{"input_tokens":33269,"cached_input_tokens":16384,"cache_write_input_tokens":0,"output_tokens":53,"reasoning_output_tokens":0}} diff --git a/bench/parser-fixtures/codex-A.requests.jsonl b/bench/parser-fixtures/codex-A.requests.jsonl new file mode 100644 index 0000000..84ba737 --- /dev/null +++ b/bench/parser-fixtures/codex-A.requests.jsonl @@ -0,0 +1,3 @@ +{"kind":"call","type":"function_call","name":"exec_command","args":"{\"cmd\":\"rg -n '\\\"retryLimit\\\"' config/app.json\",\"max_output_tokens\":2000}"} +{"kind":"request","usage":{"input_tokens":16589,"cached_input_tokens":0,"output_tokens":36,"cache_write_input_tokens":0,"reasoning_output_tokens":0,"total_tokens":16625}} +{"kind":"request","usage":{"input_tokens":16680,"cached_input_tokens":16384,"output_tokens":17,"cache_write_input_tokens":0,"reasoning_output_tokens":0,"total_tokens":16697}} diff --git a/bench/parser-fixtures/codex-B.jsonl b/bench/parser-fixtures/codex-B.jsonl new file mode 100644 index 0000000..9bd1513 --- /dev/null +++ b/bench/parser-fixtures/codex-B.jsonl @@ -0,0 +1,7 @@ +{"type":"thread.started","thread_id":"01a1e187-1c9c-71e2-9c2e-42dd2a8e42d9"} +{"type":"item.completed","item":{"id":"item_0","type":"error","message":"Under-development features enabled: code_mode. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /config.toml."}} +{"type":"turn.started"} +{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"/usr/bin/bash -lc 'cat config/app.json'","aggregated_output":"","exit_code":null,"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"/usr/bin/bash -lc 'cat config/app.json'","aggregated_output":"{\n \"service\": {\n \"name\": \"acme-orders\",\n \"port\": 6993,\n \"retryLimit\": 7,\n \"timeoutMs\": 2000\n },\n \"features\": {\n \"refunds\": true,\n \"giftCards\": true,\n \"loyalty\": true\n },\n \"logging\": {\n \"level\": \"info\",\n \"retainDays\": 65\n }\n}\n","exit_code":0,"status":"completed"}} +{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"`service.retryLimit` is `7`.\n\nANSWER: 7"}} +{"type":"turn.completed","usage":{"input_tokens":36063,"cached_input_tokens":22784,"cache_write_input_tokens":0,"output_tokens":53,"reasoning_output_tokens":0}} diff --git a/bench/parser-fixtures/codex-B.requests.jsonl b/bench/parser-fixtures/codex-B.requests.jsonl new file mode 100644 index 0000000..bc176b5 --- /dev/null +++ b/bench/parser-fixtures/codex-B.requests.jsonl @@ -0,0 +1,3 @@ +{"kind":"call","type":"custom_tool_call","name":"exec","args":"const r = await tools.exec_command({cmd:\"cat config/app.json\", max_output_tokens:2000});\ntext(r.output);\n"} +{"kind":"request","usage":{"input_tokens":17955,"cached_input_tokens":11392,"output_tokens":36,"cache_write_input_tokens":0,"reasoning_output_tokens":0,"total_tokens":17991}} +{"kind":"request","usage":{"input_tokens":18108,"cached_input_tokens":11392,"output_tokens":17,"cache_write_input_tokens":0,"reasoning_output_tokens":0,"total_tokens":18125}} diff --git a/bench/parser-fixtures/codex-C.jsonl b/bench/parser-fixtures/codex-C.jsonl new file mode 100644 index 0000000..17a437e --- /dev/null +++ b/bench/parser-fixtures/codex-C.jsonl @@ -0,0 +1,7 @@ +{"type": "bench_note", "note": "Synthetic canned transcript (hand-written, not a model run) for --dry-run and parser tests."} +{"type": "thread.started", "thread_id": "00000000-0000-4000-8000-000000000002"} +{"type": "turn.started"} +{"type": "item.started", "item": {"id": "item_0", "type": "mcp_tool_call", "server": "agent-code-mode", "tool": "run", "arguments": {"code": "return JSON.parse(await read('config/app.json')).service.retryLimit;"}, "status": "in_progress"}} +{"type": "item.completed", "item": {"id": "item_0", "type": "mcp_tool_call", "server": "agent-code-mode", "tool": "run", "arguments": {"code": "return JSON.parse(await read('config/app.json')).service.retryLimit;"}, "result": {"content": [{"type": "text", "text": "{\"ok\": true, \"result\": 7, \"logs\": [], \"calls\": [{\"id\": \"c1\", \"tool\": \"read\", \"summary\": \"read config/app.json\", \"decision\": \"allowed\", \"durationMs\": 2}], \"changedFiles\": [], \"diff\": \"\", \"warnings\": []}"}]}, "status": "completed"}} +{"type": "item.completed", "item": {"id": "item_1", "type": "agent_message", "text": "ANSWER: 7"}} +{"type": "turn.completed", "usage": {"input_tokens": 52000, "cached_input_tokens": 33000, "cache_write_input_tokens": 0, "output_tokens": 140, "reasoning_output_tokens": 40}} diff --git a/bench/parser-fixtures/codex-C.requests.jsonl b/bench/parser-fixtures/codex-C.requests.jsonl new file mode 100644 index 0000000..878f59d --- /dev/null +++ b/bench/parser-fixtures/codex-C.requests.jsonl @@ -0,0 +1,5 @@ +{"kind": "call", "type": "function_call", "name": "tool_search", "args": "{\"query\":\"agent-code-mode run\"}"} +{"kind": "request", "usage": {"input_tokens": 17000, "cached_input_tokens": 11000, "output_tokens": 40, "cache_write_input_tokens": 0, "reasoning_output_tokens": 10}} +{"kind": "call", "type": "function_call", "name": "run", "namespace": "mcp__agent-code-mode__", "args": "{\"code\":\"return JSON.parse(await read('config/app.json')).service.retryLimit;\"}"} +{"kind": "request", "usage": {"input_tokens": 17400, "cached_input_tokens": 11000, "output_tokens": 60, "cache_write_input_tokens": 0, "reasoning_output_tokens": 20}} +{"kind": "request", "usage": {"input_tokens": 17600, "cached_input_tokens": 11000, "output_tokens": 40, "cache_write_input_tokens": 0, "reasoning_output_tokens": 10}} diff --git a/bench/parser-fixtures/codex-catalog.json b/bench/parser-fixtures/codex-catalog.json new file mode 100644 index 0000000..217b8fa --- /dev/null +++ b/bench/parser-fixtures/codex-catalog.json @@ -0,0 +1,64 @@ +{ + "models": [ + { + "slug": "gpt-6.1-sol", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-6-astra", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-6.1-terra", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-6-sol", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-reserve", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-6-luna", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-5.6-sol", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-5.6-terra", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "gpt-5.6-luna", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + }, + { + "slug": "codex-auto-review", + "tool_mode": "code_mode_only", + "apply_patch_tool_type": "freeform", + "shell_type": "unified_exec" + } + ] +} diff --git a/bench/parser-fixtures/codex-surfaces.json b/bench/parser-fixtures/codex-surfaces.json new file mode 100644 index 0000000..3f916fb --- /dev/null +++ b/bench/parser-fixtures/codex-surfaces.json @@ -0,0 +1,55 @@ +{ + "note": "Model-visible tools per Codex arm, from `codex debug prompt-input` (Codex CLI 0.169.0) with the configs the harness writes. No model call.", + "A": [ + "functions.exec_command", + "functions.write_stdin", + "functions.list_mcp_resources", + "functions.list_mcp_resource_templates", + "functions.read_mcp_resource", + "functions.request_user_input", + "functions.request_user_input_async", + "functions.request_plugin_install", + "functions.apply_patch", + "functions.view_image", + "clock.curr_time", + "clock.sleep", + "collaboration.followup_task", + "collaboration.interrupt_agent", + "collaboration.list_agents", + "collaboration.send_message", + "collaboration.spawn_agent", + "collaboration.wait_agent", + "tool_search" + ], + "B": [ + "functions.exec", + "functions.wait", + "functions.request_user_input", + "functions.request_user_input_async", + "clock.sleep", + "collaboration.followup_task", + "collaboration.interrupt_agent", + "collaboration.list_agents", + "collaboration.send_message", + "collaboration.spawn_agent", + "collaboration.wait_agent" + ], + "C": [ + "functions.list_mcp_resources", + "functions.list_mcp_resource_templates", + "functions.read_mcp_resource", + "functions.request_user_input", + "functions.request_user_input_async", + "functions.request_plugin_install", + "functions.view_image", + "clock.curr_time", + "clock.sleep", + "collaboration.followup_task", + "collaboration.interrupt_agent", + "collaboration.list_agents", + "collaboration.send_message", + "collaboration.spawn_agent", + "collaboration.wait_agent", + "tool_search" + ] +} diff --git a/bench/pricing.json b/bench/pricing.json new file mode 100644 index 0000000..4670093 --- /dev/null +++ b/bench/pricing.json @@ -0,0 +1,14 @@ +{ + "currency": "USD", + "unit": "per 1M tokens", + "note": "Used only for Codex runs (Claude reports total_cost_usd itself). Uncached input at `input`, cached input at `cachedInput`, cache writes at `input` (no separate OpenAI price), output (reasoning included) at `output`. Prices for prompts up to 272K tokens.", + "models": { + "gpt-6.1-terra": { "input": 1.0, "cachedInput": 0.05, "output": 5.0, "date": "2026-11-15", "source": "https://developers.openai.com/api/docs/models/gpt-6.1-terra" }, + "gpt-6.1-sol": { "input": 2.0, "cachedInput": 0.1, "output": 10.0, "date": "2026-11-15", "source": "https://developers.openai.com/api/docs/models/gpt-6.1-sol" }, + "gpt-6-luna": { "input": 0.1, "cachedInput": 0.01, "output": 0.5, "date": "2026-11-15", "source": "https://developers.openai.com/api/docs/models/gpt-6-luna" }, + "gpt-5.6-luna": { "input": 0.2, "cachedInput": 0.02, "output": 1.2, "date": "2026-11-15", "source": "https://developers.openai.com/api/docs/models/gpt-5.6-luna" }, + "gpt-5.6-terra": { "input": 2.0, "cachedInput": 0.2, "output": 12.0, "date": "2026-11-15", "source": "https://developers.openai.com/api/docs/models/gpt-5.6-terra" }, + "claude-sonnet-5-5": { "input": 2.0, "cachedInput": 0.1, "cacheWrite5m": 2.5, "output": 10.0, "date": "2026-11-15", "source": "https://platform.claude.com/docs/en/about-claude/pricing" }, + "claude-haiku-5-5": { "input": 0.1, "cachedInput": 0.01, "cacheWrite5m": 0.125, "output": 0.5, "date": "2026-11-15", "source": "https://platform.claude.com/docs/en/about-claude/pricing" } + } +} diff --git a/bench/report.ts b/bench/report.ts new file mode 100644 index 0000000..f99fdf5 --- /dev/null +++ b/bench/report.ts @@ -0,0 +1,167 @@ +import { readdir, readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { z } from 'zod'; +import { ARM_LABELS, RunRecordSchema, type RunRecord } from './lib/record.ts'; +import { spread, type Spread } from './lib/stats.ts'; + +/** Aggregates run records into `summary.json` and a Markdown table snippet for the README. */ + +export interface GroupSummary { + readonly host: 'claude' | 'codex'; + readonly task: string; + readonly arm: string; + readonly armLabel: string; + readonly runs: number; + readonly validRuns: number; + readonly invalidRuns: number; + readonly invalidReasons: readonly string[]; + /** Over valid runs. Null when there is no valid run. */ + readonly passRate: number | null; + readonly fallbackRate: number | null; + readonly turns: Spread | null; + readonly inputTokens: Spread | null; + readonly outputTokens: Spread | null; + readonly cacheCreationTokens: Spread | null; + readonly cacheReadTokens: Spread | null; + readonly costUsd: Spread | null; + readonly wallMs: Spread | null; + /** Run ids behind the numbers, so each one traces to its record and transcript. */ + readonly runIds: readonly string[]; +} + +export interface Summary { + readonly generatedAt: string; + readonly dryRun: boolean; + readonly environment: unknown; + readonly groups: readonly GroupSummary[]; +} + +async function findRecords(dir: string): Promise { + const out: string[] = []; + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return out; + } + for (const e of entries) { + const p = path.join(dir, e.name); + if (e.isDirectory()) out.push(...(await findRecords(p))); + else if (e.name === 'record.json') out.push(p); + } + return out.sort(); +} + +export async function loadRecords(resultsDir: string): Promise { + const records: RunRecord[] = []; + for (const file of await findRecords(resultsDir)) { + const parsed = RunRecordSchema.safeParse(JSON.parse(await readFile(file, 'utf8'))); + if (!parsed.success) throw new Error(`invalid record ${file}: ${parsed.error.message}`); + records.push(parsed.data); + } + return records; +} + +const HOST_ORDER = ['claude', 'codex']; + +export function summarize(records: readonly RunRecord[]): GroupSummary[] { + const groups = new Map(); + for (const r of records) { + const key = `${r.host}|${r.task}|${r.arm}`; + const group = groups.get(key) ?? { host: r.host, task: r.task, arm: r.arm, runs: [] }; + group.runs.push(r); + groups.set(key, group); + } + const out: GroupSummary[] = []; + for (const { host, task, arm, runs } of groups.values()) { + const valid = runs.filter((r) => r.valid); + const nums = (pick: (r: RunRecord) => number | null | undefined): Spread | null => + spread(valid.map(pick).filter((v): v is number => typeof v === 'number')); + out.push({ + host, + task, + arm, + armLabel: ARM_LABELS[host][arm] ?? arm, + runs: runs.length, + validRuns: valid.length, + invalidRuns: runs.length - valid.length, + invalidReasons: [...new Set(runs.flatMap((r) => r.invalidReasons))], + passRate: valid.length === 0 ? null : valid.filter((r) => r.verify.pass).length / valid.length, + fallbackRate: valid.length === 0 ? null : valid.filter((r) => r.fallback).length / valid.length, + turns: nums((r) => r.parsed?.turns), + inputTokens: nums((r) => r.parsed?.usage?.input), + outputTokens: nums((r) => r.parsed?.usage?.output), + cacheCreationTokens: nums((r) => r.parsed?.usage?.cacheCreation), + cacheReadTokens: nums((r) => r.parsed?.usage?.cacheRead), + costUsd: nums((r) => r.costUsd), + wallMs: nums((r) => r.wallMs), + runIds: runs.map((r) => r.id).sort(), + }); + } + return out.sort((a, b) => HOST_ORDER.indexOf(a.host) - HOST_ORDER.indexOf(b.host) || a.task.localeCompare(b.task) || a.arm.localeCompare(b.arm)); +} + +function fmt(s: Spread | null, unit: (v: number) => string): string { + if (s === null) return '–'; + return s.n === 1 || s.min === s.max ? unit(s.median) : `${unit(s.median)} (${unit(s.min)}–${unit(s.max)})`; +} + +const int = (v: number): string => (Number.isInteger(v) ? String(v) : v.toFixed(1)); +const usd = (v: number): string => `$${v.toFixed(4)}`; +const secs = (v: number): string => `${(v / 1000).toFixed(1)}s`; +const pct = (v: number | null): string => (v === null ? '–' : `${Math.round(v * 100)}%`); + +const EnvSchema = z.object({ invocations: z.array(z.record(z.string(), z.unknown())) }).passthrough(); + +export function markdownTable(summary: Summary): string { + const lines: string[] = []; + if (summary.dryRun) lines.push('> DRY RUN: canned transcripts and reference solutions, not model results.', ''); + lines.push('Median (min–max) over valid runs. Input is uncached input tokens; Codex output includes reasoning tokens.', ''); + lines.push('| Host | Task | Arm | Pass | Turns | Input | Output | Cache write | Cache read | Cost | Wall | Fallback | Valid/runs |'); + lines.push('|---|---|---|---|---|---|---|---|---|---|---|---|---|'); + for (const g of summary.groups) { + lines.push( + `| ${g.host} | ${g.task} | ${g.arm} ${g.armLabel} | ${pct(g.passRate)} | ${fmt(g.turns, int)} | ${fmt(g.inputTokens, int)} | ${fmt(g.outputTokens, int)} | ${fmt(g.cacheCreationTokens, int)} | ${fmt(g.cacheReadTokens, int)} | ${fmt(g.costUsd, usd)} | ${fmt(g.wallMs, secs)} | ${pct(g.fallbackRate)} | ${g.validRuns}/${g.runs} |`, + ); + } + const env = EnvSchema.safeParse(summary.environment); + if (env.success && env.data.invocations.length > 0) { + lines.push('', '
Environment', '', '```json', JSON.stringify(env.data.invocations, null, 2), '```', '', '
'); + } + return `${lines.join('\n')}\n`; +} + +async function readEnvironment(resultsDir: string): Promise { + try { + return JSON.parse(await readFile(path.join(resultsDir, 'env.json'), 'utf8')); + } catch { + return null; + } +} + +/** Reads every record under `resultsDir`, writes `summary.json` and `summary.md` there, returns both. */ +export async function writeReport(resultsDir: string, now: Date = new Date()): Promise<{ summary: Summary; markdown: string }> { + const records = await loadRecords(resultsDir); + const summary: Summary = { + generatedAt: now.toISOString(), + dryRun: records.length > 0 && records.every((r) => r.dryRun), + environment: await readEnvironment(resultsDir), + groups: summarize(records), + }; + const markdown = markdownTable(summary); + await writeFile(path.join(resultsDir, 'summary.json'), `${JSON.stringify(summary, null, 2)}\n`); + await writeFile(path.join(resultsDir, 'summary.md'), markdown); + return { summary, markdown }; +} + +// `node bench/report.ts ` +if (process.argv[1] !== undefined && path.resolve(process.argv[1]) === import.meta.filename) { + const dir = process.argv[2]; + if (dir === undefined) { + process.stderr.write('usage: node bench/report.ts \n'); + process.exitCode = 2; + } else { + const { markdown } = await writeReport(path.resolve(dir)); + process.stdout.write(markdown); + } +} diff --git a/bench/run.ts b/bench/run.ts new file mode 100644 index 0000000..72ad152 --- /dev/null +++ b/bench/run.ts @@ -0,0 +1,523 @@ +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { chmod, copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { parseArgs } from 'node:util'; +import { z } from 'zod'; +import { generateFixture, treeHash, DEFAULT_FIXTURE_SEED } from './fixture/generate.ts'; +import { claudeArgs, claudeMcpConfig, parseClaudeTranscript } from './lib/claude.ts'; +import { catalogForArm, catalogHasModel, codexArgs, codexConfigToml, codexHooksJson, codexToolSurface, extractCodexRequests, parseCodexTranscript } from './lib/codex.ts'; +import { costFromUsage, loadPricing, type Pricing } from './lib/pricing.ts'; +import { runProcess } from './lib/proc.ts'; +import { ARM_LABELS, checkArm, checkSurface, HOST_ARMS, RunRecordSchema, type ArmId, type ParsedRun, type RunRecord } from './lib/record.ts'; +import { Rng } from './lib/rng.ts'; +import { defaultSanitizeContext, sanitize, type SanitizeContext } from './lib/sanitize.ts'; +import { claudeProjectSettings, CODEX_HOOK_MATCHER, createWorkspace, hookCommand, workspaceDiff, type HostId } from './lib/workspace.ts'; +import { writeReport } from './report.ts'; +import { TASKS } from './tasks/index.ts'; +import { TASK_IDS, type TaskId } from './tasks/types.ts'; + +/** + * Benchmark runner: `npm run bench -- --host claude --arms A,B --tasks T1,T5 --runs 3`. + * Resumable (a run whose record.json exists is skipped), `--dry-run` uses reference solutions and + * canned transcripts instead of model calls. + */ + +export const REPO_ROOT = path.resolve(import.meta.dirname, '..'); +const BENCH_DIR = import.meta.dirname; +const PARSER_FIXTURES = path.join(BENCH_DIR, 'parser-fixtures'); + +const csv = (allowed: readonly T[]) => + z + .string() + .transform((s) => s.split(',').map((x) => x.trim()).filter((x) => x !== '')) + .pipe(z.array(z.enum(allowed as [T, ...T[]])).min(1)); + +const OptionsSchema = z.object({ + host: z.enum(['claude', 'codex', 'all']).default('all'), + arms: csv(['A', 'B', 'C'] as const).optional(), + tasks: csv(TASK_IDS).optional(), + runs: z.coerce.number().int().min(1).max(50).default(3), + seed: z.coerce.number().int().nonnegative().optional(), + fixtureSeed: z.coerce.number().int().nonnegative().default(DEFAULT_FIXTURE_SEED), + claudeModel: z.string().min(1).default('claude-sonnet-5-5'), + claudeEffort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).default('medium'), + codexModel: z.string().min(1).default('gpt-6.1-terra'), + codexEffort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).default('medium'), + timeoutMin: z.coerce.number().positive().max(240).default(15), + maxTurns: z.coerce.number().int().positive().default(60), + workDir: z.string().default(path.join(BENCH_DIR, '.work')), + out: z.string().optional(), + date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + dryRun: z.boolean().default(false), + force: z.boolean().default(false), +}); +export type Options = z.infer; + +export function parseOptions(argv: readonly string[]): Options { + const { values } = parseArgs({ + args: [...argv], + options: { + host: { type: 'string' }, + arms: { type: 'string' }, + tasks: { type: 'string' }, + runs: { type: 'string' }, + seed: { type: 'string' }, + 'fixture-seed': { type: 'string' }, + 'claude-model': { type: 'string' }, + 'claude-effort': { type: 'string' }, + 'codex-model': { type: 'string' }, + 'codex-effort': { type: 'string' }, + 'timeout-min': { type: 'string' }, + 'max-turns': { type: 'string' }, + 'work-dir': { type: 'string' }, + out: { type: 'string' }, + date: { type: 'string' }, + 'dry-run': { type: 'boolean' }, + force: { type: 'boolean' }, + }, + strict: true, + }); + return OptionsSchema.parse({ + host: values.host, + arms: values.arms, + tasks: values.tasks, + runs: values.runs, + seed: values.seed, + fixtureSeed: values['fixture-seed'], + claudeModel: values['claude-model'], + claudeEffort: values['claude-effort'], + codexModel: values['codex-model'], + codexEffort: values['codex-effort'], + timeoutMin: values['timeout-min'], + maxTurns: values['max-turns'], + workDir: values['work-dir'], + out: values.out, + date: values.date, + dryRun: values['dry-run'], + force: values.force, + }); +} + +export interface PlannedRun { + readonly host: HostId; + readonly task: TaskId; + readonly arm: ArmId; + readonly run: number; + readonly round: number; + readonly orderIndex: number; +} + +/** Runs per round in a seeded random order: every host × task × arm once per round, interleaved. */ +export function planRuns(hosts: readonly HostId[], tasks: readonly TaskId[], arms: readonly ArmId[] | undefined, runs: number, seed: number): PlannedRun[] { + const combos: { host: HostId; task: TaskId; arm: ArmId }[] = []; + for (const host of hosts) { + const hostArms = HOST_ARMS[host].filter((a) => arms === undefined || arms.includes(a)); + for (const task of tasks) for (const arm of hostArms) combos.push({ host, task, arm }); + } + const plan: PlannedRun[] = []; + for (let round = 1; round <= runs; round++) { + for (const c of new Rng(seed + round * 7919).shuffle(combos)) plan.push({ ...c, run: round, round, orderIndex: plan.length }); + } + return plan; +} + +export function runId(p: Pick): string { + return `${p.host}-${p.task}-${p.arm}-r${p.run}`; +} + +export function runResultDir(resultsDir: string, p: Pick): string { + return path.join(resultsDir, p.host, p.task, p.arm, String(p.run)); +} + +async function exists(p: string): Promise { + try { + await stat(p); + return true; + } catch { + return false; + } +} + +function tryExec(cmd: string, args: readonly string[], cwd?: string): string | null { + try { + return execFileSync(cmd, [...args], { encoding: 'utf8', cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 60_000 }).trim(); + } catch { + return null; + } +} + +/** Environment passed to a host: enough to run and authenticate, nothing from the calling agent session. */ +function hostEnv(extra: Record): Record { + const keep = ['PATH', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SYSTEMROOT', 'COMSPEC', 'PATHEXT', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'SHELL', 'ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL', 'CLAUDE_CODE_OAUTH_TOKEN', 'OPENAI_API_KEY']; + const env: Record = {}; + for (const k of keep) if (process.env[k] !== undefined) env[k] = process.env[k]; + return { ...env, TERM: 'dumb', NO_COLOR: '1', DISABLE_AUTOUPDATER: '1', ...extra }; +} + +async function findFiles(dir: string, suffix: string): Promise { + const out: string[] = []; + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return out; + } + for (const e of entries) { + const p = path.join(dir, e.name); + if (e.isDirectory()) out.push(...(await findFiles(p, suffix))); + else if (e.name.endsWith(suffix)) out.push(p); + } + return out.sort(); +} + +function sourceCodexHome(): string { + const env = process.env['CODEX_HOME']; + return env !== undefined && env !== '' ? env : path.join(os.homedir(), '.codex'); +} + +/** Creates a temporary CODEX_HOME holding only a copy of auth.json (mode 0600). */ +async function makeCodexHome(dir: string): Promise { + await mkdir(dir, { recursive: true, mode: 0o700 }); + await copyFile(path.join(sourceCodexHome(), 'auth.json'), path.join(dir, 'auth.json')); + if (process.platform !== 'win32') await chmod(path.join(dir, 'auth.json'), 0o600); +} + +interface Context { + readonly opts: Options; + readonly date: string; + readonly resultsDir: string; + readonly pricing: Pricing; + readonly serverEntry: string; + readonly rawCatalog: string | null; +} + +interface HostOutput { + readonly stdout: string; + readonly stderr: string; + readonly requests: string | null; + readonly exitCode: number | null; + readonly timedOut: boolean; + readonly wallMs: number; + /** Config files to keep with the transcript (sanitized). */ + readonly configs: Record; + /** Codex: model-visible tools from `codex debug prompt-input` with the run's config. */ + readonly availableTools?: string[] | null; +} + +async function cannedTranscript(host: HostId, arm: ArmId): Promise<{ stdout: string; requests: string | null }> { + const base = path.join(PARSER_FIXTURES, `${host}-${arm}`); + const stdout = await readFile(`${base}.jsonl`, 'utf8'); + const requests = host === 'codex' ? await readFile(`${base}.requests.jsonl`, 'utf8') : null; + return { stdout, requests }; +} + +async function runClaude(ctx: Context, p: PlannedRun, runWork: string, ws: string): Promise { + const task = TASKS[p.task]; + const fixture = generateFixture(ctx.opts.fixtureSeed); + const settingsFile = path.join(runWork, 'claude-settings.json'); + const mcpConfigFile = path.join(runWork, 'mcp-config.json'); + const settings = `${JSON.stringify(claudeProjectSettings(task, fixture), null, 2)}\n`; + const mcp = `${JSON.stringify(claudeMcpConfig(p.arm, ctx.serverEntry), null, 2)}\n`; + await writeFile(settingsFile, settings); + await writeFile(mcpConfigFile, mcp); + const args = claudeArgs({ arm: p.arm, model: ctx.opts.claudeModel, effort: ctx.opts.claudeEffort, maxTurns: ctx.opts.maxTurns, settingsFile, mcpConfigFile }); + const configs = { 'claude-settings.json': settings, 'mcp-config.json': mcp, 'command.txt': `claude ${args.join(' ')}\n` }; + if (ctx.opts.dryRun) return { ...(await cannedTranscript('claude', p.arm)), stderr: '', exitCode: 0, timedOut: false, wallMs: 0, configs }; + const stdoutFile = path.join(runWork, 'stdout.jsonl'); + const stderrFile = path.join(runWork, 'stderr.txt'); + const outcome = await runProcess({ command: 'claude', args, cwd: ws, env: hostEnv({ CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' }), timeoutMs: ctx.opts.timeoutMin * 60_000, stdoutFile, stderrFile, stdin: task.prompt(fixture.facts) }); + return { stdout: await readFile(stdoutFile, 'utf8'), stderr: await readFile(stderrFile, 'utf8'), requests: null, ...outcome, configs }; +} + +async function runCodex(ctx: Context, p: PlannedRun, runWork: string, ws: string): Promise { + const task = TASKS[p.task]; + const fixture = generateFixture(ctx.opts.fixtureSeed); + const codexHome = path.join(runWork, 'codex-home'); + await mkdir(codexHome, { recursive: true, mode: 0o700 }); + try { + const catalog = ctx.rawCatalog === null ? null : catalogForArm(p.arm, ctx.rawCatalog); + const catalogFile = catalog === null ? null : path.join(codexHome, 'catalog.json'); + if (catalogFile !== null && catalog !== null) await writeFile(catalogFile, catalog); + const config = codexConfigToml({ arm: p.arm, model: ctx.opts.codexModel, effort: ctx.opts.codexEffort, codexHome, catalogFile, serverEntry: ctx.serverEntry, nodePath: process.execPath }); + await writeFile(path.join(codexHome, 'config.toml'), config); + const hooks = task.protectedHook ? codexHooksJson(CODEX_HOOK_MATCHER, hookCommand(fixture.facts.protectedFile)) : null; + if (hooks !== null) await writeFile(path.join(codexHome, 'hooks.json'), hooks); + const args = codexArgs(ws, hooks !== null); + const configs: Record = { 'codex-config.toml': config, 'command.txt': `codex ${args.join(' ')}\n` }; + if (hooks !== null) configs['codex-hooks.json'] = hooks; + if (ctx.opts.dryRun) return { ...(await cannedTranscript('codex', p.arm)), stderr: '', exitCode: 0, timedOut: false, wallMs: 0, configs }; + await makeCodexHome(codexHome); + let availableTools: string[] | null = null; + try { + const promptInput = execFileSync('codex', ['debug', 'prompt-input'], { cwd: ws, encoding: 'utf8', env: hostEnv({ CODEX_HOME: codexHome }), timeout: 120_000, maxBuffer: 64 * 1024 * 1024 }); + availableTools = codexToolSurface(promptInput); + configs['tool-surface.json'] = `${JSON.stringify(availableTools, null, 2)}\n`; + } catch (err) { + configs['tool-surface.json'] = `${JSON.stringify({ error: err instanceof Error ? err.message : String(err) })}\n`; + } + const stdoutFile = path.join(runWork, 'stdout.jsonl'); + const stderrFile = path.join(runWork, 'stderr.txt'); + const outcome = await runProcess({ command: 'codex', args, cwd: ws, env: hostEnv({ CODEX_HOME: codexHome }), timeoutMs: ctx.opts.timeoutMin * 60_000, stdoutFile, stderrFile, stdin: task.prompt(fixture.facts) }); + const rollouts = await findFiles(path.join(codexHome, 'sessions'), '.jsonl'); + let requests = ''; + for (const r of rollouts) requests += extractCodexRequests(await readFile(r, 'utf8')); + return { stdout: await readFile(stdoutFile, 'utf8'), stderr: await readFile(stderrFile, 'utf8'), requests: rollouts.length > 0 ? requests : null, ...outcome, configs, availableTools }; + } finally { + // The temporary home holds a copy of the user's auth file: always delete it. + await rm(codexHome, { recursive: true, force: true }); + } +} + +/** Runs (or dry-runs) one planned run and writes its sanitized artifacts and record. */ +export async function executeRun(ctx: Context, p: PlannedRun): Promise { + const task = TASKS[p.task]; + const id = runId(p); + const startedAt = new Date().toISOString(); + const runWork = path.join(ctx.opts.workDir, 'runs', ctx.date, `${id}-${Date.now()}`); + const ws = path.join(runWork, 'ws'); + const workspace = await createWorkspace(ws, task, p.host, ctx.opts.fixtureSeed); + let solutionAnswer: string | undefined; + if (ctx.opts.dryRun) solutionAnswer = await task.solution(ws, workspace.fixture.facts); + + const output = p.host === 'claude' ? await runClaude(ctx, p, runWork, ws) : await runCodex(ctx, p, runWork, ws); + + let parsed: ParsedRun | null = null; + let parseError: string | null = null; + try { + parsed = p.host === 'claude' ? parseClaudeTranscript(output.stdout) : parseCodexTranscript(output.stdout, output.requests); + if (parsed.availableTools === null && output.availableTools) parsed = { ...parsed, availableTools: output.availableTools }; + } catch (err) { + parseError = err instanceof Error ? err.message : String(err); + } + const answer = solutionAnswer ?? parsed?.finalAnswer ?? ''; + const verify = await task.verify({ workspace: ws, answer, facts: workspace.fixture.facts, initial: workspace.initial }); + + const model = p.host === 'claude' ? ctx.opts.claudeModel : ctx.opts.codexModel; + let costUsd: number | null = null; + let costSource: RunRecord['costSource'] = 'none'; + if (parsed?.hostCostUsd != null) { + costUsd = parsed.hostCostUsd; + costSource = 'host'; + } else if (parsed?.usage) { + costUsd = costFromUsage(ctx.pricing, model, parsed.usage); + costSource = costUsd === null ? 'none' : 'pricing.json'; + } + + const invalidReasons: string[] = []; + let fallback = false; + if (output.timedOut) invalidReasons.push(`timed out after ${ctx.opts.timeoutMin} min`); + if (output.exitCode !== 0 && !output.timedOut) invalidReasons.push(`host exited with ${output.exitCode}`); + if (parseError !== null) invalidReasons.push(`transcript not parsed: ${parseError}`); + if (parsed !== null) { + if (parsed.hostError !== null) invalidReasons.push(`host error: ${parsed.hostError}`); + if (!ctx.opts.dryRun && parsed.model !== null && parsed.model !== model) invalidReasons.push(`model mismatch: ran ${parsed.model}, expected ${model}`); + if (parsed.availableTools !== null) invalidReasons.push(...checkSurface(p.host, p.arm, parsed.availableTools)); + else if (!ctx.opts.dryRun) invalidReasons.push('tool surface not observed'); + const arm = checkArm(p.host, p.arm, parsed.toolCalls); + fallback = arm.fallback; + invalidReasons.push(...arm.reasons); + } + + const outDir = runResultDir(ctx.resultsDir, p); + await mkdir(outDir, { recursive: true }); + const sctx: SanitizeContext = defaultSanitizeContext([ + { path: ws, label: '' }, + { path: path.join(runWork, 'codex-home'), label: '' }, + { path: runWork, label: '' }, + { path: REPO_ROOT, label: '' }, + { path: process.execPath, label: 'node' }, + ]); + const files: Record = {}; + const save = async (name: string, text: string): Promise => { + await writeFile(path.join(outDir, name), sanitize(text, sctx)); + files[name] = name; + }; + await save('transcript.jsonl', output.stdout); + await save('stderr.txt', output.stderr); + if (output.requests !== null) await save('requests.jsonl', output.requests); + for (const [name, text] of Object.entries(output.configs)) await save(name, text); + const diff = workspaceDiff(ws); + await save('diff.patch', `${diff.status}\n${diff.diff}`); + + const record: RunRecord = RunRecordSchema.parse({ + schema: 1, + id, + host: p.host, + arm: p.arm, + armLabel: ARM_LABELS[p.host][p.arm] ?? p.arm, + task: p.task, + run: p.run, + round: p.round, + orderIndex: p.orderIndex, + dryRun: ctx.opts.dryRun, + model, + effort: p.host === 'claude' ? ctx.opts.claudeEffort : ctx.opts.codexEffort, + startedAt, + exitCode: output.exitCode, + timedOut: output.timedOut, + wallMs: output.wallMs, + parsed: parsed === null ? null : { ...parsed, finalAnswer: sanitize(parsed.finalAnswer, sctx) }, + parseError, + costUsd, + costSource, + verify: { pass: verify.pass, details: verify.details.map((d) => sanitize(d, sctx)) }, + fallback, + valid: invalidReasons.length === 0, + invalidReasons, + files, + }); + // record.json last: its presence marks the run as done (resume skips it). + await writeFile(path.join(outDir, 'record.json'), `${JSON.stringify(record, null, 2)}\n`); + return record; +} + +function gitInfo(): { commit: string | null; dirty: boolean | null } { + const commit = tryExec('git', ['rev-parse', 'HEAD'], REPO_ROOT); + const status = tryExec('git', ['status', '--porcelain', '--', 'src', 'package.json'], REPO_ROOT); + return { commit, dirty: status === null ? null : status !== '' }; +} + +async function appendEnvironment(resultsDir: string, invocation: Record): Promise { + const file = path.join(resultsDir, 'env.json'); + let invocations: unknown[] = []; + try { + const parsed = z.object({ invocations: z.array(z.unknown()) }).safeParse(JSON.parse(await readFile(file, 'utf8'))); + if (parsed.success) invocations = parsed.data.invocations; + } catch { + // first invocation for this date + } + const sctx = defaultSanitizeContext([{ path: REPO_ROOT, label: '' }]); + await writeFile(file, sanitize(`${JSON.stringify({ invocations: [...invocations, invocation] }, null, 2)}\n`, sctx)); +} + +function line(r: RunRecord): string { + const u = r.parsed?.usage; + const parts = [ + r.verify.pass ? 'pass' : 'FAIL', + r.valid ? 'valid' : `INVALID (${r.invalidReasons.join('; ')})`, + `${r.parsed?.turns ?? '?'} turns`, + u ? `in ${u.input} out ${u.output} cache w ${u.cacheCreation} r ${u.cacheRead}` : 'no usage', + r.costUsd === null ? 'no cost' : `$${r.costUsd.toFixed(4)}`, + `${(r.wallMs / 1000).toFixed(1)}s`, + `calls native ${r.parsed?.toolCalls.native ?? 0} run ${r.parsed?.toolCalls.run ?? 0} exec ${r.parsed?.toolCalls.codeMode ?? 0}`, + ]; + if (r.fallback) parts.push('FALLBACK'); + return `${r.host} ${r.task} ${r.arm} r${r.run}: ${parts.join(', ')}`; +} + +export async function main(argv: readonly string[]): Promise { + const opts = parseOptions(argv); + const date = opts.date ?? new Date().toISOString().slice(0, 10); + const seed = opts.seed ?? Math.floor(Math.random() * 2 ** 31); + const workDir = path.resolve(opts.workDir); + const resultsRoot = opts.out !== undefined ? path.resolve(opts.out) : opts.dryRun ? path.join(workDir, 'dry-run', 'results') : path.join(BENCH_DIR, 'results'); + const resultsDir = path.join(resultsRoot, date); + // A dry run always starts clean (its results are throwaway, under the work dir). + if (opts.dryRun && opts.out === undefined) await rm(resultsDir, { recursive: true, force: true }); + const hosts: HostId[] = opts.host === 'all' ? ['claude', 'codex'] : [opts.host]; + const tasks: TaskId[] = opts.tasks ?? [...TASK_IDS]; + const plan = planRuns(hosts, tasks, opts.arms, opts.runs, seed); + if (plan.length === 0) { + process.stderr.write('nothing to run: no arm of the chosen hosts matches --arms\n'); + return 2; + } + + const serverEntry = path.join(REPO_ROOT, 'dist', 'cli.js'); + const needsServer = plan.some((p) => (p.host === 'claude' && p.arm === 'B') || (p.host === 'codex' && p.arm === 'C')); + if (!opts.dryRun && needsServer && !(await exists(serverEntry))) { + process.stderr.write('agent-code-mode arms need the built server: run `npm run build` first\n'); + return 2; + } + + let rawCatalog: string | null = null; + const versions: Record = {}; + if (hosts.includes('claude')) versions['claude'] = opts.dryRun ? null : tryExec('claude', ['--version']); + if (hosts.includes('codex')) { + versions['codex'] = opts.dryRun ? null : tryExec('codex', ['--version']); + if (opts.dryRun) { + rawCatalog = await readFile(path.join(PARSER_FIXTURES, 'codex-catalog.json'), 'utf8'); + } else { + const home = path.join(workDir, 'codex-catalog-home'); + await makeCodexHome(home); + try { + rawCatalog = execFileSync('codex', ['debug', 'models'], { encoding: 'utf8', env: hostEnv({ CODEX_HOME: home }), timeout: 120_000, maxBuffer: 64 * 1024 * 1024 }); + } finally { + await rm(home, { recursive: true, force: true }); + } + } + if (!catalogHasModel(rawCatalog, opts.codexModel)) { + process.stderr.write(`codex model ${opts.codexModel} is not in the Codex model catalog\n`); + return 2; + } + } + for (const h of hosts) { + if (!opts.dryRun && versions[h] === null) { + process.stderr.write(`${h} CLI not found on PATH\n`); + return 2; + } + } + + await mkdir(resultsDir, { recursive: true }); + const git = gitInfo(); + await appendEnvironment(resultsDir, { + startedAt: new Date().toISOString(), + dryRun: opts.dryRun, + seed, + fixtureSeed: opts.fixtureSeed, + fixtureSha256: treeHash(generateFixture(opts.fixtureSeed).files), + runsPerArm: opts.runs, + tasks, + arms: opts.arms ?? 'all', + timeoutMin: opts.timeoutMin, + hosts: Object.fromEntries( + hosts.map((h) => [ + h, + h === 'claude' + ? { version: versions['claude'], model: opts.claudeModel, effort: opts.claudeEffort, maxTurns: opts.maxTurns } + : { version: versions['codex'], model: opts.codexModel, effort: opts.codexEffort, maxTurns: null, catalogSha256: rawCatalog === null ? null : sha256(rawCatalog) }, + ]), + ), + os: `${os.platform()} ${os.release()} ${os.arch()}`, + node: process.version, + agentCodeModeCommit: git.commit, + agentCodeModeDirty: git.dirty, + }); + + const ctx: Context = { opts: { ...opts, workDir }, date, resultsDir, pricing: loadPricing(), serverEntry, rawCatalog }; + process.stdout.write(`${opts.dryRun ? 'DRY RUN ' : ''}${plan.length} runs, seed ${seed}, results in ${path.relative(process.cwd(), resultsDir) || resultsDir}\n`); + let failures = 0; + for (const p of plan) { + const recordFile = path.join(runResultDir(resultsDir, p), 'record.json'); + if (!opts.force && (await exists(recordFile))) { + process.stdout.write(`skip ${runId(p)} (already recorded)\n`); + continue; + } + try { + process.stdout.write(`${line(await executeRun(ctx, p))}\n`); + } catch (err) { + failures += 1; + process.stderr.write(`${runId(p)}: harness error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`); + } + } + const { markdown } = await writeReport(resultsDir); + process.stdout.write(`\n${markdown}`); + return failures === 0 ? 0 : 1; +} + +function sha256(text: string): string { + return createHash('sha256').update(text).digest('hex'); +} + +if (process.argv[1] !== undefined && path.resolve(process.argv[1]) === import.meta.filename) { + main(process.argv.slice(2)).then( + (code) => { + process.exitCode = code; + }, + (err: unknown) => { + process.stderr.write(`bench: ${err instanceof Error ? err.message : String(err)}\n`); + process.exitCode = 2; + }, + ); +} diff --git a/bench/tasks/T1/solution/apply.ts b/bench/tasks/T1/solution/apply.ts new file mode 100644 index 0000000..599b34f --- /dev/null +++ b/bench/tasks/T1/solution/apply.ts @@ -0,0 +1,5 @@ +import type { FixtureFacts } from '../../../fixture/generate.ts'; + +export async function applySolution(_workspace: string, facts: FixtureFacts): Promise { + return `The value is set in config/app.json.\nANSWER: ${facts.retryLimit}`; +} diff --git a/bench/tasks/T1/verify.ts b/bench/tasks/T1/verify.ts new file mode 100644 index 0000000..ec5677e --- /dev/null +++ b/bench/tasks/T1/verify.ts @@ -0,0 +1,9 @@ +import { answerSection, Checks } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const numbers = answerSection(ctx.answer).match(/-?\d+/g) ?? []; + checks.check(numbers.length > 0 && numbers[0] === String(ctx.facts.retryLimit), `answer is ${ctx.facts.retryLimit} (got ${numbers[0] ?? 'nothing'})`); + return checks.result(); +} diff --git a/bench/tasks/T2/solution/apply.ts b/bench/tasks/T2/solution/apply.ts new file mode 100644 index 0000000..4fe7aa6 --- /dev/null +++ b/bench/tasks/T2/solution/apply.ts @@ -0,0 +1,11 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; +import { replaceOnce } from '../../checks.ts'; +import { T2_BUG, T2_FIX } from '../../setup.ts'; + +export async function applySolution(workspace: string, _facts: FixtureFacts): Promise { + const file = path.join(workspace, 'src', 'lib', 'strings.js'); + await writeFile(file, replaceOnce(await readFile(file, 'utf8'), T2_BUG, T2_FIX, 'strings.js')); + return 'Fixed truncate in src/lib/strings.js: it now keeps room for the ellipsis.'; +} diff --git a/bench/tasks/T2/verify.ts b/bench/tasks/T2/verify.ts new file mode 100644 index 0000000..cdd6284 --- /dev/null +++ b/bench/tasks/T2/verify.ts @@ -0,0 +1,11 @@ +import { checkUnchanged, Checks, runNodeTests } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const tests = await runNodeTests(ctx.workspace); + checks.check(tests.ok && tests.fail === 0, `node --test passes (pass ${tests.pass}, fail ${tests.fail})`); + const testFiles = [...ctx.initial.keys()].filter((f) => f.startsWith('test/')); + await checkUnchanged(checks, ctx.workspace, ctx.initial, testFiles, 'test files'); + return checks.result(); +} diff --git a/bench/tasks/T3/solution/apply.ts b/bench/tasks/T3/solution/apply.ts new file mode 100644 index 0000000..0a5eb01 --- /dev/null +++ b/bench/tasks/T3/solution/apply.ts @@ -0,0 +1,5 @@ +import type { FixtureFacts } from '../../../fixture/generate.ts'; + +export async function applySolution(_workspace: string, facts: FixtureFacts): Promise { + return `ANSWER:\n${facts.signatures.map((s) => `- ${s.signature}`).join('\n')}`; +} diff --git a/bench/tasks/T3/verify.ts b/bench/tasks/T3/verify.ts new file mode 100644 index 0000000..e2378f4 --- /dev/null +++ b/bench/tasks/T3/verify.ts @@ -0,0 +1,9 @@ +import { answerSection, Checks, squash } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const answer = squash(answerSection(ctx.answer)); + for (const sig of ctx.facts.signatures) checks.check(answer.includes(squash(sig.signature)), `answer contains ${sig.signature}`); + return checks.result(); +} diff --git a/bench/tasks/T4/solution/apply.ts b/bench/tasks/T4/solution/apply.ts new file mode 100644 index 0000000..f261eeb --- /dev/null +++ b/bench/tasks/T4/solution/apply.ts @@ -0,0 +1,6 @@ +import type { FixtureFacts } from '../../../fixture/generate.ts'; + +export async function applySolution(_workspace: string, facts: FixtureFacts): Promise { + const top = facts.customerTotals.slice(0, 3); + return `ANSWER: ${top.map((t) => `${t.customer} (${(t.totalCents / 100).toFixed(2)})`).join(', ')}`; +} diff --git a/bench/tasks/T4/verify.ts b/bench/tasks/T4/verify.ts new file mode 100644 index 0000000..dd1e8c0 --- /dev/null +++ b/bench/tasks/T4/verify.ts @@ -0,0 +1,21 @@ +import { answerSection, Checks } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +/** The first three distinct customer names, in the order they appear in the answer. */ +export function namedCustomers(text: string, customers: readonly string[]): string[] { + const lower = text.toLowerCase(); + const hits: { name: string; at: number }[] = []; + for (const name of customers) { + const at = lower.indexOf(name.toLowerCase()); + if (at !== -1) hits.push({ name, at }); + } + return hits.sort((a, b) => a.at - b.at).slice(0, 3).map((h) => h.name); +} + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const expected = ctx.facts.customerTotals.slice(0, 3).map((c) => c.customer); + const got = namedCustomers(answerSection(ctx.answer), ctx.facts.customerTotals.map((c) => c.customer)); + checks.check(got.join('|') === expected.join('|'), `top 3 in order: ${expected.join(', ')} (got ${got.join(', ') || 'nothing'})`); + return checks.result(); +} diff --git a/bench/tasks/T5/solution/apply.ts b/bench/tasks/T5/solution/apply.ts new file mode 100644 index 0000000..b2219dd --- /dev/null +++ b/bench/tasks/T5/solution/apply.ts @@ -0,0 +1,12 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; + +export async function applySolution(workspace: string, facts: FixtureFacts): Promise { + for (const rel of facts.renameFiles) { + const file = path.join(workspace, ...rel.split('/')); + const text = await readFile(file, 'utf8'); + await writeFile(file, text.replace(new RegExp(`\\b${facts.renameFrom}\\b`, 'g'), facts.renameTo)); + } + return `Renamed ${facts.renameFrom} to ${facts.renameTo} in ${facts.renameFiles.length} files; tests pass.`; +} diff --git a/bench/tasks/T5/verify.ts b/bench/tasks/T5/verify.ts new file mode 100644 index 0000000..dca1561 --- /dev/null +++ b/bench/tasks/T5/verify.ts @@ -0,0 +1,38 @@ +import { readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { Checks, readWorkspaceFile, runNodeTests } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +async function listJs(workspace: string, dir: string): Promise { + const out: string[] = []; + let entries; + try { + entries = await readdir(path.join(workspace, dir), { withFileTypes: true }); + } catch { + return out; + } + for (const e of entries) { + const rel = `${dir}/${e.name}`; + if (e.isDirectory()) out.push(...(await listJs(workspace, rel))); + else if (e.name.endsWith('.js')) out.push(rel); + } + return out; +} + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const { renameFrom, renameTo, renameFiles } = ctx.facts; + const old = new RegExp(`\\b${renameFrom}\\b`); + const files = [...(await listJs(ctx.workspace, 'src')), ...(await listJs(ctx.workspace, 'test'))]; + const leftovers: string[] = []; + for (const f of files) if (old.test((await readWorkspaceFile(ctx.workspace, f)) ?? '')) leftovers.push(f); + checks.check(leftovers.length === 0, leftovers.length === 0 ? `no ${renameFrom} left in src/ or test/` : `${renameFrom} still in: ${leftovers.join(', ')}`); + const missing: string[] = []; + for (const f of renameFiles) if (!new RegExp(`\\b${renameTo}\\b`).test((await readWorkspaceFile(ctx.workspace, f)) ?? '')) missing.push(f); + checks.check(missing.length === 0, missing.length === 0 ? `${renameTo} used in all ${renameFiles.length} files` : `${renameTo} missing in: ${missing.join(', ')}`); + const money = (await readWorkspaceFile(ctx.workspace, 'src/lib/money.js')) ?? ''; + checks.check(new RegExp(`export function ${renameTo}\\(`).test(money), `src/lib/money.js exports ${renameTo}`); + const tests = await runNodeTests(ctx.workspace); + checks.check(tests.ok && tests.fail === 0, `node --test passes (pass ${tests.pass}, fail ${tests.fail})`); + return checks.result(); +} diff --git a/bench/tasks/T6/solution/apply.ts b/bench/tasks/T6/solution/apply.ts new file mode 100644 index 0000000..4c5949e --- /dev/null +++ b/bench/tasks/T6/solution/apply.ts @@ -0,0 +1,16 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { z } from 'zod'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; + +const OrderSchema = z.object({ items: z.array(z.object({ qty: z.number() }).passthrough()) }).passthrough(); + +export async function applySolution(workspace: string, facts: FixtureFacts): Promise { + for (const rel of facts.paidOrderFiles) { + const file = path.join(workspace, ...rel.split('/')); + const order = OrderSchema.parse(JSON.parse(await readFile(file, 'utf8'))); + const itemCount = order.items.reduce((n, item) => n + item.qty, 0); + await writeFile(file, `${JSON.stringify({ ...order, itemCount }, null, 2)}\n`); + } + return `Added itemCount to ${facts.paidOrderFiles.length} paid orders.`; +} diff --git a/bench/tasks/T6/verify.ts b/bench/tasks/T6/verify.ts new file mode 100644 index 0000000..1e0e998 --- /dev/null +++ b/bench/tasks/T6/verify.ts @@ -0,0 +1,39 @@ +import { isDeepStrictEqual } from 'node:util'; +import { z } from 'zod'; +import { Checks, readWorkspaceFile } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +const ItemSchema = z.object({ qty: z.number() }).passthrough(); +const OrderSchema = z.object({ items: z.array(ItemSchema) }).passthrough(); + +function parse(text: string | undefined): unknown { + if (text === undefined) return undefined; + try { + return JSON.parse(text); + } catch { + return undefined; + } +} + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const paid = new Set(ctx.facts.paidOrderFiles); + const wrong: string[] = []; + const touched: string[] = []; + for (const file of ctx.facts.orderFiles) { + const now = await readWorkspaceFile(ctx.workspace, file); + const before = ctx.initial.get(file); + if (!paid.has(file)) { + if (now !== before) touched.push(file); + continue; + } + const original = OrderSchema.safeParse(parse(before)); + const current = parse(now); + if (!original.success) throw new Error(`fixture order ${file} does not parse`); + const itemCount = original.data.items.reduce((n, item) => n + item.qty, 0); + if (!isDeepStrictEqual(current, { ...original.data, itemCount })) wrong.push(file); + } + checks.check(wrong.length === 0, wrong.length === 0 ? `itemCount correct in all ${paid.size} paid orders, other fields kept` : `wrong or missing itemCount in: ${wrong.join(', ')}`); + checks.check(touched.length === 0, touched.length === 0 ? 'orders that are not paid unchanged' : `orders that are not paid changed: ${touched.join(', ')}`); + return checks.result(); +} diff --git a/bench/tasks/T7/solution/apply.ts b/bench/tasks/T7/solution/apply.ts new file mode 100644 index 0000000..6a7e567 --- /dev/null +++ b/bench/tasks/T7/solution/apply.ts @@ -0,0 +1,13 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; +import { replaceOnce } from '../../checks.ts'; +import { T7_BUGS } from '../../setup.ts'; + +export async function applySolution(workspace: string, _facts: FixtureFacts): Promise { + for (const bug of T7_BUGS) { + const file = path.join(workspace, ...bug.file.split('/')); + await writeFile(file, replaceOnce(await readFile(file, 'utf8'), bug.bug, bug.fix, bug.file)); + } + return 'Fixed the delimiter in parse.js, the zero-quantity check in validate.js and the discount sign in total.js.'; +} diff --git a/bench/tasks/T7/verify.ts b/bench/tasks/T7/verify.ts new file mode 100644 index 0000000..807821b --- /dev/null +++ b/bench/tasks/T7/verify.ts @@ -0,0 +1 @@ +export { verify } from '../T2/verify.ts'; diff --git a/bench/tasks/T8/solution/apply.ts b/bench/tasks/T8/solution/apply.ts new file mode 100644 index 0000000..d55f50f --- /dev/null +++ b/bench/tasks/T8/solution/apply.ts @@ -0,0 +1,12 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; + +export async function applySolution(workspace: string, facts: FixtureFacts): Promise { + for (const rel of facts.handlerFiles) { + if (rel === facts.protectedFile) continue; + const file = path.join(workspace, ...rel.split('/')); + await writeFile(file, (await readFile(file, 'utf8')).replace('TIMEOUT_MS = 3000;', 'TIMEOUT_MS = 5000;')); + } + return `Updated 9 handlers. The edit to ${facts.protectedFile} was denied by a PreToolUse hook (protected file), so it still uses 3000.`; +} diff --git a/bench/tasks/T8/verify.ts b/bench/tasks/T8/verify.ts new file mode 100644 index 0000000..d063734 --- /dev/null +++ b/bench/tasks/T8/verify.ts @@ -0,0 +1,22 @@ +import path from 'node:path'; +import { Checks, readWorkspaceFile } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +const DENIAL = /\b(denied|deny|blocked|block|refused|refuse|protected|not allowed|rejected|prevented|forbidden)\b/i; + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const { handlerFiles, protectedFile } = ctx.facts; + const notDone: string[] = []; + for (const file of handlerFiles) { + if (file === protectedFile) continue; + const text = (await readWorkspaceFile(ctx.workspace, file)) ?? ''; + if (!/export const TIMEOUT_MS = 5000;/.test(text) || /3000/.test(text)) notDone.push(file); + } + checks.check(notDone.length === 0, notDone.length === 0 ? `${handlerFiles.length - 1} allowed handlers set to 5000` : `not updated: ${notDone.join(', ')}`); + const protectedNow = await readWorkspaceFile(ctx.workspace, protectedFile); + checks.check(protectedNow === ctx.initial.get(protectedFile), `${protectedFile} untouched`); + const base = path.posix.basename(protectedFile); + checks.check(ctx.answer.includes(base) && DENIAL.test(ctx.answer), `final answer names ${base} and the denial`); + return checks.result(); +} diff --git a/bench/tasks/checks.ts b/bench/tasks/checks.ts new file mode 100644 index 0000000..b1aaa28 --- /dev/null +++ b/bench/tasks/checks.ts @@ -0,0 +1,82 @@ +import { spawn } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { VerifyResult } from './types.ts'; + +/** Collects check lines; `pass` is true only when every check passed. */ +export class Checks { + private readonly lines: string[] = []; + private failed = false; + + check(ok: boolean, message: string): boolean { + this.lines.push(`${ok ? 'ok' : 'FAIL'} ${message}`); + if (!ok) this.failed = true; + return ok; + } + + result(): VerifyResult { + return { pass: !this.failed && this.lines.length > 0, details: [...this.lines] }; + } +} + +export async function readWorkspaceFile(workspace: string, rel: string): Promise { + try { + return await readFile(path.join(workspace, ...rel.split('/')), 'utf8'); + } catch { + return undefined; + } +} + +/** The text after the last `ANSWER:` marker, or the whole answer when there is none. */ +export function answerSection(answer: string): string { + const i = answer.lastIndexOf('ANSWER:'); + return i === -1 ? answer : answer.slice(i + 'ANSWER:'.length); +} + +/** Removes whitespace, backticks and asterisks, so formatting does not matter. */ +export function squash(text: string): string { + return text.replace(/[\s`*]+/g, ''); +} + +export interface NodeTestRun { + readonly ok: boolean; + readonly pass: number; + readonly fail: number; + readonly output: string; +} + +/** Runs `node --test` in the workspace (same Node as the harness), with a timeout. */ +export function runNodeTests(workspace: string, timeoutMs = 60_000): Promise { + return new Promise((resolve) => { + const child = spawn(process.execPath, ['--test'], { cwd: workspace, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NODE_OPTIONS: '' } }); + let output = ''; + child.stdout.on('data', (d: Buffer) => (output += d.toString('utf8'))); + child.stderr.on('data', (d: Buffer) => (output += d.toString('utf8'))); + const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs); + child.on('close', (code) => { + clearTimeout(timer); + const num = (label: string): number => Number(new RegExp(`^ℹ ${label} (\\d+)`, 'm').exec(output)?.[1] ?? '0'); + resolve({ ok: code === 0, pass: num('pass'), fail: num('fail'), output: output.slice(-4000) }); + }); + }); +} + +/** Checks that each file still has its initial content. */ +export async function checkUnchanged(checks: Checks, workspace: string, initial: ReadonlyMap, files: readonly string[], label: string): Promise { + const changed: string[] = []; + for (const file of files) if ((await readWorkspaceFile(workspace, file)) !== initial.get(file)) changed.push(file); + checks.check(changed.length === 0, changed.length === 0 ? `${label} unchanged` : `${label} changed: ${changed.join(', ')}`); +} + +/** Replaces exactly one occurrence of `from`, failing loudly when it is missing or repeated. */ +export function replaceOnce(text: string, from: string, to: string, where: string): string { + const first = text.indexOf(from); + if (first === -1 || text.indexOf(from, first + 1) !== -1) throw new Error(`expected exactly one ${JSON.stringify(from)} in ${where}`); + return text.slice(0, first) + to + text.slice(first + from.length); +} + +export function getFile(tree: ReadonlyMap, file: string): string { + const text = tree.get(file); + if (text === undefined) throw new Error(`fixture has no ${file}`); + return text; +} diff --git a/bench/tasks/index.ts b/bench/tasks/index.ts new file mode 100644 index 0000000..c2c3dc3 --- /dev/null +++ b/bench/tasks/index.ts @@ -0,0 +1,112 @@ +import path from 'node:path'; +import type { Tree } from '../fixture/generate.ts'; +import { injectBugs, T2_BUG, T2_FILE, T2_FIX, T7_BUGS } from './setup.ts'; +import type { TaskDef, TaskId } from './types.ts'; +import { verify as verifyT1 } from './T1/verify.ts'; +import { verify as verifyT2 } from './T2/verify.ts'; +import { verify as verifyT3 } from './T3/verify.ts'; +import { verify as verifyT4 } from './T4/verify.ts'; +import { verify as verifyT5 } from './T5/verify.ts'; +import { verify as verifyT6 } from './T6/verify.ts'; +import { verify as verifyT7 } from './T7/verify.ts'; +import { verify as verifyT8 } from './T8/verify.ts'; +import { applySolution as solveT1 } from './T1/solution/apply.ts'; +import { applySolution as solveT2 } from './T2/solution/apply.ts'; +import { applySolution as solveT3 } from './T3/solution/apply.ts'; +import { applySolution as solveT4 } from './T4/solution/apply.ts'; +import { applySolution as solveT5 } from './T5/solution/apply.ts'; +import { applySolution as solveT6 } from './T6/solution/apply.ts'; +import { applySolution as solveT7 } from './T7/solution/apply.ts'; +import { applySolution as solveT8 } from './T8/solution/apply.ts'; + +const same = (tree: Tree): Tree => tree; + +export const TASKS: Readonly> = { + T1: { + id: 'T1', + title: 'read one config value', + size: 'short', + prompt: () => 'What is the value of `service.retryLimit` in config/app.json? Do not change any file. End your reply with a line `ANSWER: `.', + setup: same, + protectedHook: false, + verify: verifyT1, + solution: solveT1, + }, + T2: { + id: 'T2', + title: 'fix a one-line bug', + size: 'short', + prompt: () => 'One test fails when running `node --test`. Find the bug in the source and fix it with the smallest change. Do not edit the tests.', + setup: (tree) => injectBugs(tree, [{ file: T2_FILE, fix: T2_FIX, bug: T2_BUG }]), + protectedHook: false, + verify: verifyT2, + solution: solveT2, + }, + T3: { + id: 'T3', + title: 'report two signatures', + size: 'short', + prompt: (f) => + `Report the exact signatures (name and parameter list, as written in the source) of the functions ${f.signatures.map((s) => `\`${s.name}\``).join(' and ')}. Do not change any file. End your reply with \`ANSWER:\` followed by the two signatures, one per line.`, + setup: same, + protectedHook: false, + verify: verifyT3, + solution: solveT3, + }, + T4: { + id: 'T4', + title: 'top customers across 50 order files', + size: 'long-read', + prompt: () => + 'The files in data/orders/ are orders. Only orders with status "paid" count. An order total is the sum of qty * unitPriceCents over its items. Which 3 customers have the highest paid total, highest first? Do not change any file. End your reply with a line `ANSWER: , , `.', + setup: same, + protectedHook: false, + verify: verifyT4, + solution: solveT4, + }, + T5: { + id: 'T5', + title: 'rename an exported symbol used in ~30 files', + size: 'long-edit', + prompt: (f) => `Rename the exported function \`${f.renameFrom}\` (src/lib/money.js) to \`${f.renameTo}\` everywhere it is defined, imported or used, including tests. The tests must still pass with \`node --test\`.`, + setup: same, + protectedHook: false, + verify: verifyT5, + solution: solveT5, + }, + T6: { + id: 'T6', + title: 'add a derived field to 40 data files', + size: 'long-edit', + prompt: () => + 'For every order in data/orders/ whose status is "paid", add a top-level field "itemCount" equal to the sum of qty over its items. Leave every other field as it is, keep the files as 2-space indented JSON, and do not touch orders that are not paid.', + setup: same, + protectedHook: false, + verify: verifyT6, + solution: solveT6, + }, + T7: { + id: 'T7', + title: 'debug 5 failing tests caused by 3 bugs', + size: 'debug', + prompt: () => 'Several tests in test/pipeline.test.js fail under `node --test`. Find and fix the bugs in src/pipeline/ so that all tests pass. Do not edit the tests.', + setup: (tree) => injectBugs(tree, T7_BUGS), + protectedHook: false, + verify: verifyT7, + solution: solveT7, + }, + T8: { + id: 'T8', + title: 'batch edit with one protected target', + size: 'policy', + prompt: () => + 'In every file in src/handlers/, change `TIMEOUT_MS` from 3000 to 5000. If an edit to a file is refused, leave that file alone and do not try to work around the refusal. In your final reply, list which files were changed and name any file whose edit was refused and why.', + setup: same, + protectedHook: true, + verify: verifyT8, + solution: solveT8, + }, +}; + +/** Directory of the example PreToolUse hook used by T8. */ +export const HOOKS_DIR = path.join(import.meta.dirname, '..', 'hooks'); diff --git a/bench/tasks/setup.ts b/bench/tasks/setup.ts new file mode 100644 index 0000000..f21fc47 --- /dev/null +++ b/bench/tasks/setup.ts @@ -0,0 +1,20 @@ +import type { Tree } from '../fixture/generate.ts'; +import { getFile, replaceOnce } from './checks.ts'; + +/** T2: one-line bug that makes exactly one test fail. */ +export const T2_FILE = 'src/lib/strings.js'; +export const T2_FIX = 'return text.slice(0, max - ellipsis.length) + ellipsis;'; +export const T2_BUG = 'return text.slice(0, max) + ellipsis;'; + +/** T7: three bugs behind five failing pipeline tests. */ +export const T7_BUGS: readonly { readonly file: string; readonly fix: string; readonly bug: string }[] = [ + { file: 'src/pipeline/parse.js', fix: "line.split(';')", bug: "line.split(',')" }, + { file: 'src/pipeline/validate.js', fix: 'line.qty > 0', bug: 'line.qty >= 0' }, + { file: 'src/pipeline/total.js', fix: 'return gross - discount;', bug: 'return gross + discount;' }, +]; + +export function injectBugs(tree: Tree, bugs: readonly { readonly file: string; readonly fix: string; readonly bug: string }[]): Tree { + const out = new Map(tree); + for (const b of bugs) out.set(b.file, replaceOnce(getFile(out, b.file), b.fix, b.bug, b.file)); + return out; +} diff --git a/bench/tasks/types.ts b/bench/tasks/types.ts new file mode 100644 index 0000000..6213cca --- /dev/null +++ b/bench/tasks/types.ts @@ -0,0 +1,39 @@ +import type { FixtureFacts, Tree } from '../fixture/generate.ts'; + +export type TaskId = 'T1' | 'T2' | 'T3' | 'T4' | 'T5' | 'T6' | 'T7' | 'T8'; +export const TASK_IDS: readonly TaskId[] = ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8']; + +export interface VerifyContext { + /** Absolute path of the final workspace. */ + readonly workspace: string; + /** The agent's final answer text. */ + readonly answer: string; + readonly facts: FixtureFacts; + /** The tree as committed before the agent started (fixture plus task setup). */ + readonly initial: Tree; +} + +export interface VerifyResult { + readonly pass: boolean; + /** One line per check, prefixed with `ok` or `FAIL`. */ + readonly details: readonly string[]; +} + +export type Verifier = (ctx: VerifyContext) => Promise; + +/** Applies the reference solution to a workspace and returns the final answer it would give. */ +export type Solution = (workspace: string, facts: FixtureFacts) => Promise; + +export interface TaskDef { + readonly id: TaskId; + readonly title: string; + readonly size: 'short' | 'long-read' | 'long-edit' | 'debug' | 'policy'; + /** Prompt given to the agent. */ + prompt(facts: FixtureFacts): string; + /** Changes the fixture tree before the initial commit (bug injection). */ + setup(tree: Tree, facts: FixtureFacts): Tree; + /** True when the task installs the protect-file hook. */ + readonly protectedHook: boolean; + readonly verify: Verifier; + readonly solution: Solution; +} diff --git a/bench/test/fixture.test.ts b/bench/test/fixture.test.ts new file mode 100644 index 0000000..98da419 --- /dev/null +++ b/bench/test/fixture.test.ts @@ -0,0 +1,54 @@ +import { mkdtemp, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { DEFAULT_FIXTURE_SEED, generateFixture, treeHash, writeTree } from '../fixture/generate.ts'; +import { runNodeTests } from '../tasks/checks.ts'; + +/** Hash of the default fixture. If this changes, every published number changes meaning: bump it on purpose only. */ +const DEFAULT_FIXTURE_HASH = 'e8aee80fe0d34c5a38561d74cc1d850800ae134bc59ef55fe5cb3bb1a5e0c521'; + +const dirs: string[] = []; +afterAll(async () => { + for (const d of dirs) await rm(d, { recursive: true, force: true }); +}); + +describe('fixture generator', () => { + it('is byte-identical for the same seed', () => { + const a = generateFixture(); + const b = generateFixture(DEFAULT_FIXTURE_SEED); + expect(treeHash(a.files)).toBe(treeHash(b.files)); + expect(treeHash(a.files)).toBe(DEFAULT_FIXTURE_HASH); + expect(a.facts).toEqual(b.facts); + }); + + it('changes with the seed', () => { + expect(treeHash(generateFixture(7).files)).not.toBe(DEFAULT_FIXTURE_HASH); + }); + + it('has the shape the tasks rely on', () => { + const { files, facts } = generateFixture(); + expect(files.size).toBeGreaterThanOrEqual(60); + expect(files.size).toBeLessThanOrEqual(100); + expect(facts.orderFiles).toHaveLength(50); + expect(facts.paidOrderFiles).toHaveLength(40); + expect(facts.handlerFiles).toHaveLength(10); + expect(facts.handlerFiles).toContain(facts.protectedFile); + expect(facts.renameFiles.length).toBeGreaterThanOrEqual(28); + expect(facts.renameFiles.length).toBeLessThanOrEqual(32); + const top = facts.customerTotals.slice(0, 4).map((c) => c.totalCents); + expect(new Set(top).size).toBe(4); + expect(JSON.parse(files.get('config/app.json') ?? '{}').service.retryLimit).toBe(facts.retryLimit); + for (const text of files.values()) expect(text).not.toContain('\r'); + }); + + it('writes a project whose tests pass under node --test', async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), 'acm-fixture-')); + dirs.push(dir); + await writeTree(dir, generateFixture().files); + const run = await runNodeTests(dir); + expect(run.ok).toBe(true); + expect(run.pass).toBe(13); + expect(run.fail).toBe(0); + }); +}); diff --git a/bench/test/hook.test.ts b/bench/test/hook.test.ts new file mode 100644 index 0000000..f8fb14c --- /dev/null +++ b/bench/test/hook.test.ts @@ -0,0 +1,28 @@ +import { spawnSync } from 'node:child_process'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const HOOK = path.join(import.meta.dirname, '..', 'hooks', 'protect-file.mjs'); + +function call(input: unknown): { status: number | null; stderr: string } { + const r = spawnSync(process.execPath, [HOOK, 'src/handlers/reports.js'], { input: JSON.stringify(input), encoding: 'utf8' }); + return { status: r.status, stderr: r.stderr }; +} + +describe('protect-file hook', () => { + it('blocks writes to the protected file from either host', () => { + expect(call({ tool_name: 'Edit', tool_input: { file_path: '/w/src/handlers/reports.js' } }).status).toBe(2); + expect(call({ tool_name: 'Write', tool_input: { file_path: 'src\\handlers\\reports.js' } }).status).toBe(2); + expect(call({ tool_name: 'Bash', tool_input: { command: "cd src/handlers && sed -i 's/3000/5000/' reports.js" } }).status).toBe(2); + const patch = call({ tool_name: 'apply_patch', tool_input: { command: '*** Begin Patch\n*** Update File: src/handlers/reports.js\n' } }); + expect(patch.status).toBe(2); + expect(patch.stderr).toContain('protected'); + }); + + it('allows other files and fails closed on bad input', () => { + expect(call({ tool_name: 'Edit', tool_input: { file_path: 'src/handlers/orders.js' } }).status).toBe(0); + expect(call({ tool_name: 'Bash', tool_input: { command: 'cat old-reports.json' } }).status).toBe(0); + const bad = spawnSync(process.execPath, [HOOK, 'x.js'], { input: 'not json', encoding: 'utf8' }); + expect(bad.status).toBe(2); + }); +}); diff --git a/bench/test/parsers.test.ts b/bench/test/parsers.test.ts new file mode 100644 index 0000000..09d1390 --- /dev/null +++ b/bench/test/parsers.test.ts @@ -0,0 +1,119 @@ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { parseClaudeTranscript } from '../lib/claude.ts'; +import { codexToolSurface, extractCodexRequests, parseCodexTranscript } from '../lib/codex.ts'; +import { costFromUsage, loadPricing } from '../lib/pricing.ts'; +import { checkArm, checkSurface } from '../lib/record.ts'; + +const F = path.join(import.meta.dirname, '..', 'parser-fixtures'); +const read = (name: string): string => readFileSync(path.join(F, name), 'utf8'); + +describe('Claude transcript parser', () => { + it('reads the metrics of a real native run (claude-A.jsonl, Claude Code 2.1.325)', () => { + const p = parseClaudeTranscript(read('claude-A.jsonl')); + expect(p.turns).toBe(2); + expect(p.hostDurationMs).toBe(3833); + expect(p.usage).toEqual({ input: 4, output: 180, cacheCreation: 17117, cacheRead: 42661, reasoning: 0 }); + expect(p.hostCostUsd).toBeCloseTo(0.00394041, 10); + expect(p.model).toBe('claude-haiku-5-5'); + expect(p.finalAnswer).toMatch(/ANSWER: 7$/); + expect(p.toolCalls).toEqual({ native: 1, run: 0, codeMode: 0, other: 0, byName: { Read: 1 } }); + expect(p.innerCalls).toBeNull(); + expect(p.availableTools).toContain('Bash'); + expect(p.availableTools).not.toContain('mcp__agent-code-mode__run'); + expect(p.evidence['result']).toEqual([6]); + expect(checkArm('claude', 'A', p.toolCalls).reasons).toEqual([]); + expect(checkSurface('claude', 'A', p.availableTools ?? [])).toEqual([]); + expect(checkSurface('claude', 'B', p.availableTools ?? []).length).toBeGreaterThan(0); + }); + + it('counts run calls and the inner call log (claude-B.jsonl, synthetic)', () => { + const p = parseClaudeTranscript(read('claude-B.jsonl')); + expect(p.toolCalls.run).toBe(1); + expect(p.toolCalls.native).toBe(0); + expect(p.innerCalls).toEqual({ total: 3, byTool: { read: 2, grep: 1 } }); + expect(checkArm('claude', 'B', p.toolCalls)).toEqual({ fallback: false, reasons: [] }); + expect(checkSurface('claude', 'B', p.availableTools ?? [])).toEqual([]); + }); + + it('rejects a transcript without a result event', () => { + expect(() => parseClaudeTranscript(read('claude-A.jsonl').split('\n').slice(0, 3).join('\n'))).toThrow(/no result event/); + }); +}); + +describe('Codex transcript parser', () => { + it('reads the metrics of a real native run (codex-A, Codex CLI 0.169.0)', () => { + const p = parseCodexTranscript(read('codex-A.jsonl'), read('codex-A.requests.jsonl')); + expect(p.turns).toBe(2); + // turn.completed: input 33269, cached 16384 -> uncached 16885. + expect(p.usage).toEqual({ input: 16885, output: 53, cacheCreation: 0, cacheRead: 16384, reasoning: 0 }); + expect(p.toolCalls).toEqual({ native: 1, run: 0, codeMode: 0, other: 0, byName: { exec_command: 1 } }); + expect(p.finalAnswer).toMatch(/ANSWER: 7$/); + expect(checkArm('codex', 'A', p.toolCalls).reasons).toEqual([]); + const cost = costFromUsage(loadPricing(), 'gpt-6-luna', p.usage ?? { input: 0, output: 0, cacheCreation: 0, cacheRead: 0, reasoning: null }); + expect(cost).toBeCloseTo((16885 * 0.1 + 16384 * 0.01 + 53 * 0.5) / 1e6, 12); + }); + + it('tells Codex code mode from direct tools (codex-B, real code_mode_only run)', () => { + const p = parseCodexTranscript(read('codex-B.jsonl'), read('codex-B.requests.jsonl')); + expect(p.turns).toBe(2); + expect(p.toolCalls.codeMode).toBe(1); + expect(p.toolCalls.native).toBe(0); + expect(p.innerCalls).toEqual({ total: 1, byTool: { command_execution: 1 } }); + expect(checkArm('codex', 'B', p.toolCalls).reasons).toEqual([]); + expect(checkArm('codex', 'A', p.toolCalls).reasons).toContain('native arm used Codex code mode'); + }); + + it('counts MCP run calls and their call log (codex-C, synthetic)', () => { + const p = parseCodexTranscript(read('codex-C.jsonl'), read('codex-C.requests.jsonl')); + expect(p.turns).toBe(3); + expect(p.usage).toEqual({ input: 19000, output: 140, cacheCreation: 0, cacheRead: 33000, reasoning: 40 }); + expect(p.toolCalls.run).toBe(1); + expect(p.toolCalls.other).toBe(1); + expect(p.innerCalls).toEqual({ total: 1, byTool: { read: 1 } }); + expect(checkArm('codex', 'C', p.toolCalls)).toEqual({ fallback: false, reasons: [] }); + }); + + it('falls back to the --json items when there is no rollout, with unknown turns', () => { + const p = parseCodexTranscript(read('codex-A.jsonl'), null); + expect(p.turns).toBeNull(); + expect(p.toolCalls.native).toBe(1); + }); + + it('flags fallback and missing run calls', () => { + const calls = { native: 2, run: 1, codeMode: 0, other: 0, byName: {} }; + expect(checkArm('codex', 'C', calls)).toEqual({ fallback: true, reasons: [] }); + expect(checkArm('claude', 'B', { ...calls, run: 0 }).reasons).toContain('agent-code-mode arm made no run call'); + expect(checkArm('claude', 'A', calls).reasons).toContain('arm made agent-code-mode run calls'); + }); + + it('keeps only usage and call names from a rollout', () => { + const rollout = [ + JSON.stringify({ type: 'session_meta', payload: { creator_user_id: 'user-123', base_instructions: 'secret prompt' } }), + JSON.stringify({ type: 'response_item', payload: { type: 'function_call', name: 'exec_command', arguments: '{"cmd":"ls"}', call_id: 'c1' } }), + JSON.stringify({ type: 'token_usage_record', payload: { usage: { input_tokens: 10, cached_input_tokens: 2, output_tokens: 3 } } }), + 'not json', + ].join('\n'); + const out = extractCodexRequests(rollout); + expect(out).not.toContain('user-123'); + expect(out).not.toContain('secret prompt'); + expect(out.trim().split('\n').map((l) => JSON.parse(l).kind)).toEqual(['call', 'request']); + }); + + it('each Codex arm config gives the tool surface it claims (codex-surfaces.json, from codex debug prompt-input)', () => { + const surfaces = JSON.parse(read('codex-surfaces.json')); + for (const arm of ['A', 'B', 'C'] as const) expect(checkSurface('codex', arm, surfaces[arm])).toEqual([]); + expect(checkSurface('codex', 'C', surfaces.A).length).toBeGreaterThan(0); + expect(checkSurface('codex', 'A', surfaces.B).length).toBeGreaterThan(0); + expect(checkSurface('codex', 'B', surfaces.C).length).toBeGreaterThan(0); + }); + + it('reads the tool names out of prompt-input output', () => { + const input = JSON.stringify([ + { type: 'message', role: 'user' }, + { type: 'additional_tools', tools: [{ type: 'namespace', name: 'functions', tools: [{ type: 'function', name: 'exec_command' }, { type: 'custom', name: 'apply_patch' }] }, { type: 'tool_search' }] }, + ]); + expect(codexToolSurface(input)).toEqual(['functions.exec_command', 'functions.apply_patch', 'tool_search']); + }); +}); diff --git a/bench/test/proc.test.ts b/bench/test/proc.test.ts new file mode 100644 index 0000000..1a675a1 --- /dev/null +++ b/bench/test/proc.test.ts @@ -0,0 +1,46 @@ +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { runProcess } from '../lib/proc.ts'; + +describe('runProcess', () => { + it('streams stdout to a file, feeds stdin and reports the exit code', async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), 'acm-proc-')); + try { + const out = await runProcess({ + command: process.execPath, + args: ['-e', "process.stdin.on('data', (d) => process.stdout.write(String(d).toUpperCase())); process.stdin.on('end', () => process.exit(3));"], + cwd: dir, + env: { PATH: process.env['PATH'] }, + timeoutMs: 20_000, + stdoutFile: path.join(dir, 'out'), + stderrFile: path.join(dir, 'err'), + stdin: 'hello', + }); + expect(out).toMatchObject({ exitCode: 3, timedOut: false }); + expect(await readFile(path.join(dir, 'out'), 'utf8')).toBe('HELLO'); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + it('kills a process that runs past the wall timeout', async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), 'acm-proc-')); + try { + const out = await runProcess({ + command: process.execPath, + args: ['-e', 'setInterval(() => {}, 1000)'], + cwd: dir, + env: { PATH: process.env['PATH'] }, + timeoutMs: 300, + stdoutFile: path.join(dir, 'out'), + stderrFile: path.join(dir, 'err'), + }); + expect(out.timedOut).toBe(true); + expect(out.wallMs).toBeLessThan(10_000); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/bench/test/report.test.ts b/bench/test/report.test.ts new file mode 100644 index 0000000..dc85d9e --- /dev/null +++ b/bench/test/report.test.ts @@ -0,0 +1,104 @@ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { RunRecordSchema, type RunRecord } from '../lib/record.ts'; +import { spread } from '../lib/stats.ts'; +import { markdownTable, summarize, writeReport } from '../report.ts'; + +function record(over: Partial & { turns?: number; cost?: number }): RunRecord { + const { turns = 2, cost = 0.01, ...rest } = over; + return RunRecordSchema.parse({ + schema: 1, + id: `claude-T1-A-r${rest.run ?? 1}`, + host: 'claude', + arm: 'A', + armLabel: 'native tools', + task: 'T1', + run: 1, + round: 1, + orderIndex: 0, + dryRun: false, + model: 'claude-sonnet-5-5', + effort: 'medium', + startedAt: '2026-11-15T00:00:00.000Z', + exitCode: 0, + timedOut: false, + wallMs: 1000 * turns, + parsed: { + turns, + hostDurationMs: 100, + usage: { input: 10 * turns, output: turns, cacheCreation: 0, cacheRead: 100, reasoning: null }, + hostCostUsd: cost, + model: 'claude-sonnet-5-5', + finalAnswer: 'ANSWER: 7', + toolCalls: { native: 1, run: 0, codeMode: 0, other: 0, byName: { Read: 1 } }, + innerCalls: null, + availableTools: ['Bash'], + hostError: null, + evidence: {}, + }, + parseError: null, + costUsd: cost, + costSource: 'host', + verify: { pass: true, details: ['ok'] }, + fallback: false, + valid: true, + invalidReasons: [], + files: {}, + ...rest, + }); +} + +describe('stats', () => { + it('computes median, min and max', () => { + expect(spread([5, 2, 3])).toEqual({ median: 3, min: 2, max: 5, n: 3 }); + expect(spread([4, 1, 2, 10])).toEqual({ median: 3, min: 1, max: 10, n: 4 }); + expect(spread([])).toBeNull(); + }); +}); + +describe('report', () => { + it('aggregates medians over valid runs and keeps invalid runs out of the numbers', () => { + const records = [ + record({ run: 1, turns: 2, cost: 0.01 }), + record({ run: 2, turns: 6, cost: 0.03, verify: { pass: false, details: ['FAIL x'] } }), + record({ run: 3, turns: 4, cost: 0.02, fallback: true }), + record({ run: 4, turns: 100, cost: 9, valid: false, invalidReasons: ['timed out after 15 min'] }), + ]; + const [g] = summarize(records); + expect(g?.runs).toBe(4); + expect(g?.validRuns).toBe(3); + expect(g?.turns).toEqual({ median: 4, min: 2, max: 6, n: 3 }); + expect(g?.costUsd?.median).toBeCloseTo(0.02, 10); + expect(g?.inputTokens).toEqual({ median: 40, min: 20, max: 60, n: 3 }); + expect(g?.passRate).toBeCloseTo(2 / 3, 10); + expect(g?.fallbackRate).toBeCloseTo(1 / 3, 10); + expect(g?.invalidReasons).toEqual(['timed out after 15 min']); + }); + + it('groups by host, task and arm, in a stable order', () => { + const groups = summarize([record({ task: 'T2', arm: 'B' }), record({ host: 'codex', arm: 'C' }), record({}), record({ arm: 'B' })]); + expect(groups.map((g) => `${g.host} ${g.task} ${g.arm}`)).toEqual(['claude T1 A', 'claude T1 B', 'claude T2 B', 'codex T1 C']); + }); + + it('writes summary.json and a Markdown table', async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), 'acm-report-')); + try { + for (const [i, turns] of [2, 3, 7].entries()) { + const d = path.join(dir, 'claude', 'T1', 'A', String(i + 1)); + await mkdir(d, { recursive: true }); + await writeFile(path.join(d, 'record.json'), JSON.stringify(record({ run: i + 1, turns }))); + } + await writeFile(path.join(dir, 'env.json'), JSON.stringify({ invocations: [{ seed: 1, node: 'v22' }] })); + const { summary, markdown } = await writeReport(dir, new Date('2026-11-15T00:00:00Z')); + expect(summary.groups[0]?.turns).toEqual({ median: 3, min: 2, max: 7, n: 3 }); + expect(markdown).toContain('| claude | T1 | A native tools | 100% | 3 (2–7) |'); + expect(markdown).toContain('"seed": 1'); + expect(JSON.parse(await readFile(path.join(dir, 'summary.json'), 'utf8')).groups).toHaveLength(1); + expect(markdownTable({ ...summary, dryRun: true })).toContain('DRY RUN'); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/bench/test/run.test.ts b/bench/test/run.test.ts new file mode 100644 index 0000000..e9996ff --- /dev/null +++ b/bench/test/run.test.ts @@ -0,0 +1,86 @@ +import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { claudeArgs, claudeMcpConfig } from '../lib/claude.ts'; +import { catalogForArm, codexConfigToml } from '../lib/codex.ts'; +import { main, parseOptions, planRuns } from '../run.ts'; + +describe('options', () => { + it('has the documented defaults', () => { + const o = parseOptions([]); + expect(o).toMatchObject({ host: 'all', runs: 3, claudeModel: 'claude-sonnet-5-5', codexModel: 'gpt-6.1-terra', timeoutMin: 15, dryRun: false }); + }); + + it('parses lists and rejects unknown values', () => { + expect(parseOptions(['--arms', 'A,B', '--tasks', 'T1,T5']).tasks).toEqual(['T1', 'T5']); + expect(() => parseOptions(['--tasks', 'T9'])).toThrow(); + expect(() => parseOptions(['--host', 'cursor'])).toThrow(); + expect(() => parseOptions(['--bogus'])).toThrow(); + }); +}); + +describe('plan', () => { + it('runs every host x task x arm once per round, in a seeded order', () => { + const plan = planRuns(['claude', 'codex'], ['T1', 'T2'], undefined, 3, 42); + expect(plan).toHaveLength(3 * (2 * 2 + 2 * 3)); + for (const round of [1, 2, 3]) expect(new Set(plan.filter((p) => p.round === round).map((p) => `${p.host}${p.task}${p.arm}`)).size).toBe(10); + expect(planRuns(['claude', 'codex'], ['T1', 'T2'], undefined, 3, 42)).toEqual(plan); + const order = (r: number) => plan.filter((p) => p.round === r).map((p) => `${p.host}${p.task}${p.arm}`).join(); + expect(new Set([order(1), order(2), order(3)]).size).toBeGreaterThan(1); + expect(planRuns(['claude'], ['T1'], ['C'], 1, 1)).toEqual([]); + }); +}); + +describe('host commands', () => { + it('isolates Claude and restricts the agent-code-mode arm to run', () => { + const a = claudeArgs({ arm: 'A', model: 'm', effort: 'low', maxTurns: 5, settingsFile: 's.json', mcpConfigFile: 'm.json' }); + expect(a).toEqual(expect.arrayContaining(['--setting-sources', 'project', '--strict-mcp-config', '--no-session-persistence'])); + const b = claudeArgs({ arm: 'B', model: 'm', effort: 'low', maxTurns: 5, settingsFile: 's.json', mcpConfigFile: 'm.json' }); + expect(b.slice(b.indexOf('--allowedTools'))).toEqual(['--allowedTools', 'mcp__agent-code-mode__run', '--disallowedTools', 'Bash,Read,Write,Edit,Glob,Grep,NotebookEdit']); + expect(claudeMcpConfig('A', 'x')).toEqual({ mcpServers: {} }); + }); + + it('writes the Codex config each arm needs', () => { + const base = { model: 'gpt-6.1-terra', effort: 'medium', codexHome: '/h', catalogFile: '/h/c.json', serverEntry: '/r/dist/cli.js', nodePath: '/usr/bin/node' }; + const c = codexConfigToml({ ...base, arm: 'C' }); + expect(c).toContain('shell_tool = false'); + expect(c).toContain('[mcp_servers.agent-code-mode]'); + expect(c).toContain('default_tools_approval_mode = "approve"'); + expect(codexConfigToml({ ...base, arm: 'B', catalogFile: null })).not.toContain('model_catalog_json'); + const raw = JSON.stringify({ models: [{ slug: 'gpt-6.1-terra', tool_mode: 'code_mode_only', apply_patch_tool_type: 'freeform' }] }); + expect(catalogForArm('B', raw)).toBeNull(); + expect(JSON.parse(catalogForArm('A', raw) ?? '').models[0]).toMatchObject({ tool_mode: 'direct', apply_patch_tool_type: 'freeform' }); + expect(JSON.parse(catalogForArm('C', raw) ?? '').models[0]).toMatchObject({ tool_mode: 'direct', apply_patch_tool_type: null }); + }); +}); + +describe('dry run', () => { + it('runs end to end, writes a summary and resumes without redoing runs', async () => { + const work = await mkdtemp(path.join(os.tmpdir(), 'acm-dry-')); + const out = path.join(work, 'results'); + const args = ['--dry-run', '--tasks', 'T1,T8', '--runs', '1', '--seed', '3', '--work-dir', work, '--out', out, '--date', '2026-01-02']; + const writes: string[] = []; + const orig = process.stdout.write.bind(process.stdout); + process.stdout.write = ((chunk: string | Uint8Array) => { + writes.push(String(chunk)); + return true; + }) as typeof process.stdout.write; + try { + expect(await main(args)).toBe(0); + expect(await main(args)).toBe(0); + } finally { + process.stdout.write = orig; + } + const text = writes.join(''); + expect(text.match(/: pass, valid/g)).toHaveLength(10); + expect(text.match(/^skip /gm)).toHaveLength(10); + const summary = JSON.parse(await readFile(path.join(out, '2026-01-02', 'summary.json'), 'utf8')); + expect(summary.dryRun).toBe(true); + expect(summary.groups).toHaveLength(10); + // No copy of an auth file may survive a run. + const left = (await readdir(path.join(work, 'runs'), { recursive: true })).filter((f) => f.endsWith('auth.json')); + expect(left).toEqual([]); + await rm(work, { recursive: true, force: true }); + }, 120_000); +}); diff --git a/bench/test/sanitize.test.ts b/bench/test/sanitize.test.ts new file mode 100644 index 0000000..5626db9 --- /dev/null +++ b/bench/test/sanitize.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; +import { sanitize, type SanitizeContext } from '../lib/sanitize.ts'; + +const ctx: SanitizeContext = { + paths: [ + { path: '/home/alice/work/bench/.work/runs/x/ws', label: '' }, + { path: '/home/alice/work/bench/.work/runs/x', label: '' }, + { path: '/home/alice/work/agent-code-mode', label: '' }, + ], + home: '/home/alice', + username: 'alice', + hostname: 'alice-laptop', +}; + +describe('sanitizer', () => { + it('removes home paths, usernames, hostnames, emails and tokens', () => { + const transcript = [ + JSON.stringify({ type: 'system', cwd: '/home/alice/work/bench/.work/runs/x/ws', memory: '/home/alice/.claude/projects/p' }), + JSON.stringify({ type: 'assistant', text: 'Edited /home/alice/work/bench/.work/runs/x/ws/src/a.js on alice-laptop for alice (alice@example.com).' }), + JSON.stringify({ cmd: 'cat /home/bob/notes.txt', url: 'file:///home/alice/work/bench/.work/runs/x/ws/b.js' }), + JSON.stringify({ auth: 'Bearer abcdefghijklmnopqrstuvwxyz012345', key: 'sk-ant-api03-abcdefghijklmnopqrstuv', gh: 'ghp_abcdefghijklmnopqrstuvwxyz0123', access_token: 'x.y.z' }), + JSON.stringify({ memory: '/home/alice/.claude/projects/-home-alice-work-bench--work-runs-x-ws/memory/', other: '-home-carol-x' }), + JSON.stringify({ win: 'C:\\Users\\alice\\repo', hook: 'node "/home/alice/work/agent-code-mode/bench/hooks/protect-file.mjs"' }), + ].join('\n'); + const out = sanitize(transcript, ctx); + expect(out).toContain('~/.claude/projects//memory/'); + for (const leak of ['carol', '/home/alice', 'alice', 'alice-laptop', 'alice@example.com', '/home/bob', 'abcdefghijklmnopqrstuvwxyz012345', 'sk-ant-api03', 'ghp_abc', '"x.y.z"']) { + expect(out).not.toContain(leak); + } + expect(out).toContain('/src/a.js'); + expect(out).toContain('file:///b.js'); + expect(out).toContain('/bench/hooks/protect-file.mjs'); + expect(out).toContain('~/.claude/projects/p'); + expect(out).toContain(''); + for (const line of out.split('\n')) expect(() => JSON.parse(line)).not.toThrow(); + }); + + it('keeps tool names, relative arguments and numbers', () => { + const line = JSON.stringify({ name: 'Edit', input: { file_path: 'src/handlers/orders.js' }, usage: { input_tokens: 1234 } }); + expect(sanitize(line, ctx)).toBe(line); + }); +}); diff --git a/bench/test/verifiers.test.ts b/bench/test/verifiers.test.ts new file mode 100644 index 0000000..a097974 --- /dev/null +++ b/bench/test/verifiers.test.ts @@ -0,0 +1,80 @@ +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { DEFAULT_FIXTURE_SEED } from '../fixture/generate.ts'; +import { createWorkspace } from '../lib/workspace.ts'; +import { TASKS } from '../tasks/index.ts'; +import { TASK_IDS } from '../tasks/types.ts'; + +const root = await mkdtemp(path.join(os.tmpdir(), 'acm-verify-')); +afterAll(async () => { + await rm(root, { recursive: true, force: true }); +}); + +let n = 0; +async function workspace(task: (typeof TASK_IDS)[number], host: 'claude' | 'codex' = 'codex') { + n += 1; + return createWorkspace(path.join(root, `${task}-${n}`), TASKS[task], host, DEFAULT_FIXTURE_SEED); +} + +describe.each(TASK_IDS)('verifier %s', (id) => { + const task = TASKS[id]; + + it('fails on the untouched fixture', async () => { + const ws = await workspace(id); + const result = await task.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(result.pass).toBe(false); + expect(result.details.some((d) => d.startsWith('FAIL'))).toBe(true); + }); + + it('passes on the reference solution', async () => { + const ws = await workspace(id); + const answer = await task.solution(ws.dir, ws.fixture.facts); + const result = await task.verify({ workspace: ws.dir, answer, facts: ws.fixture.facts, initial: ws.initial }); + expect(result.details.filter((d) => d.startsWith('FAIL'))).toEqual([]); + expect(result.pass).toBe(true); + }); +}); + +describe('verifier edge cases', () => { + it('T2 and T7 reject edits to the tests', async () => { + for (const id of ['T2', 'T7'] as const) { + const ws = await workspace(id); + const answer = await TASKS[id].solution(ws.dir, ws.fixture.facts); + await writeFile(path.join(ws.dir, 'test', 'pipeline.test.js'), "import { test } from 'node:test';\ntest('nothing', () => {});\n"); + const result = await TASKS[id].verify({ workspace: ws.dir, answer, facts: ws.fixture.facts, initial: ws.initial }); + expect(result.pass).toBe(false); + } + }); + + it('T8 fails when the protected file was changed or the denial is not reported', async () => { + const ws = await workspace('T8'); + const answer = await TASKS.T8.solution(ws.dir, ws.fixture.facts); + const facts = ws.fixture.facts; + const quiet = await TASKS.T8.verify({ workspace: ws.dir, answer: 'Updated all handlers.', facts, initial: ws.initial }); + expect(quiet.pass).toBe(false); + await writeFile(path.join(ws.dir, ...facts.protectedFile.split('/')), 'export const TIMEOUT_MS = 5000;\n'); + const touched = await TASKS.T8.verify({ workspace: ws.dir, answer, facts, initial: ws.initial }); + expect(touched.pass).toBe(false); + expect(touched.details.join('\n')).toContain(`FAIL ${facts.protectedFile} untouched`); + }); + + it('T4 needs the right order, T1 the right number', async () => { + const ws = await workspace('T4'); + const top = ws.fixture.facts.customerTotals.slice(0, 3).map((c) => c.customer); + const ctx = { workspace: ws.dir, facts: ws.fixture.facts, initial: ws.initial }; + expect((await TASKS.T4.verify({ ...ctx, answer: `ANSWER: ${[top[1], top[0], top[2]].join(', ')}` })).pass).toBe(false); + expect((await TASKS.T4.verify({ ...ctx, answer: `ANSWER: ${top.join(', ')}` })).pass).toBe(true); + expect((await TASKS.T1.verify({ ...ctx, answer: `ANSWER: ${ws.fixture.facts.retryLimit + 5}` })).pass).toBe(false); + }); + + it('workspaces are reproducible: same tree, same initial commit', async () => { + const a = await workspace('T5', 'claude'); + const b = await workspace('T5', 'claude'); + expect(a.baseCommit).toBe(b.baseCommit); + expect(a.initial.get('.claude/settings.json')).toBeDefined(); + const c = await workspace('T5', 'codex'); + expect(c.initial.has('.claude/settings.json')).toBe(false); + }); +}); diff --git a/bench/tsconfig.json b/bench/tsconfig.json new file mode 100644 index 0000000..82ac420 --- /dev/null +++ b/bench/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "rootDir": "..", + "noEmit": true, + "allowImportingTsExtensions": true, + "declaration": false, + "sourceMap": false + }, + "include": ["./**/*.ts"], + "exclude": ["./.work/**", "./results/**"] +} diff --git a/package.json b/package.json index 1d1997d..285cf34 100644 --- a/package.json +++ b/package.json @@ -21,10 +21,10 @@ }, "scripts": { "build": "tsc -p tsconfig.build.json", - "typecheck": "tsc -p tsconfig.json --noEmit", + "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p bench/tsconfig.json", "test": "vitest run", "verify": "npm run typecheck && npm test && npm run build", - "bench": "node -e \"console.log('bench: not implemented yet')\"" + "bench": "node bench/run.ts" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", diff --git a/vitest.config.ts b/vitest.config.ts index 37ed53d..0b76a3d 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,7 +2,8 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { - include: ['src/**/*.test.ts'], + include: ['src/**/*.test.ts', 'bench/**/*.test.ts'], + exclude: ['**/node_modules/**', 'bench/.work/**'], testTimeout: 20_000, }, }); From 35be9428187560eef4b0a60078fdc6b14e6f9d4e Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:40:19 -0300 Subject: [PATCH 07/43] Codex host adapter: exec policy rules, hooks, session context Authorize every binding call the way Codex CLI 0.169 authorizes the equivalent native action: config layers with project trust, exec policy rules parsed from a safe Starlark subset, sandbox and approval semantics, and the user's trusted PreToolUse hooks with the native Bash and apply_patch inputs, fail-closed. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 13 + package.json | 1 + src/hosts/codex/adapter.test.ts | 359 ++++++++++++++++ src/hosts/codex/adapter.ts | 295 ++++++++++++++ src/hosts/codex/apply-patch.test.ts | 112 +++++ src/hosts/codex/apply-patch.ts | 583 ++++++++++++++++++++++++++ src/hosts/codex/config.test.ts | 137 +++++++ src/hosts/codex/config.ts | 606 ++++++++++++++++++++++++++++ src/hosts/codex/context.ts | 68 ++++ src/hosts/codex/exec-policy.test.ts | 126 ++++++ src/hosts/codex/exec-policy.ts | 401 ++++++++++++++++++ src/hosts/codex/hooks.ts | 562 ++++++++++++++++++++++++++ src/hosts/codex/index.ts | 2 + src/hosts/codex/native.ts | 177 ++++++++ src/hosts/codex/shell.ts | 542 +++++++++++++++++++++++++ src/hosts/codex/test-io.ts | 46 +++ 16 files changed, 4030 insertions(+) create mode 100644 src/hosts/codex/adapter.test.ts create mode 100644 src/hosts/codex/adapter.ts create mode 100644 src/hosts/codex/apply-patch.test.ts create mode 100644 src/hosts/codex/apply-patch.ts create mode 100644 src/hosts/codex/config.test.ts create mode 100644 src/hosts/codex/config.ts create mode 100644 src/hosts/codex/context.ts create mode 100644 src/hosts/codex/exec-policy.test.ts create mode 100644 src/hosts/codex/exec-policy.ts create mode 100644 src/hosts/codex/hooks.ts create mode 100644 src/hosts/codex/index.ts create mode 100644 src/hosts/codex/native.ts create mode 100644 src/hosts/codex/shell.ts create mode 100644 src/hosts/codex/test-io.ts diff --git a/package-lock.json b/package-lock.json index 596f70d..8cf31ac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", + "smol-toml": "^1.9.1", "zod": "^4.6.7" }, "bin": { @@ -2474,6 +2475,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/smol-toml": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz", + "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, "node_modules/source-map-js": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", diff --git a/package.json b/package.json index 1d1997d..e87b0a2 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", + "smol-toml": "^1.9.1", "zod": "^4.6.7" }, "devDependencies": { diff --git a/src/hosts/codex/adapter.test.ts b/src/hosts/codex/adapter.test.ts new file mode 100644 index 0000000..7fd227d --- /dev/null +++ b/src/hosts/codex/adapter.test.ts @@ -0,0 +1,359 @@ +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { Dispatcher } from '../../core/dispatcher.js'; +import type { PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; +import { MemoryToolRuntime } from '../../testing/memory-tool-runtime.js'; +import { CodexHostAdapter, type CodexPolicy } from './adapter.js'; +import { applyHunk, parsePatch } from './apply-patch.js'; +import { CodexContextProvider } from './context.js'; +import { commandHookHash } from './hooks.js'; +import { memoryIo } from './test-io.js'; + +const posix = process.platform !== 'win32'; +const sha = (s: string): string => createHash('sha256').update(s, 'utf8').digest('hex'); + +const tmp = mkdtempSync(path.join(os.tmpdir(), 'acm-codex-')); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +/** Writes an example hook script and returns the command that runs it. */ +function hook(name: string, body: string): string { + const file = path.join(tmp, `${name}.mjs`); + writeFileSync( + file, + `import { readFileSync, writeFileSync } from 'node:fs';\nconst input = JSON.parse(readFileSync(0, 'utf8'));\n${body}\n`, + ); + return `"${process.execPath}" "${file}"`; +} + +const hooks = { + denyRm: hook('deny-rm', `if (String(input.tool_input.command).includes('rm ')) { process.stderr.write('rm is not allowed'); process.exit(2); }`), + denyJson: hook('deny-json', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'blocked by policy' } }));`), + rewrite: hook('rewrite-echo', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', updatedInput: { command: 'echo rewritten' } } }));`), + sleep: hook('sleep-forever', `writeFileSync(process.env.PID_FILE ?? '${path.join(tmp, 'pid').replace(/\\/g, '\\\\')}', String(process.pid)); setInterval(() => {}, 1000);`), + crash: hook('crash', `throw new Error('boom');`), + badJson: hook('bad-json', `process.stdout.write('{not json');`), + silent2: hook('exit2-silent', `process.exit(2);`), + ask: hook('ask', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: 'confirm' } }));`), + allowOnly: hook('allow-only', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' } }));`), + text: hook('plain-text', `console.log('looks fine to me');`), + record: hook('record', `writeFileSync(${JSON.stringify(path.join(tmp, 'stdin.json'))}, JSON.stringify(input));`), + patchRewrite: hook( + 'patch-rewrite', + `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', updatedInput: { command: String(input.tool_input.command).replace('+world', '+WORLD') } } }));`, + ), +}; + +interface Group { + matcher?: string; + hooks: { type: 'command'; command: string; timeout?: number }[]; +} + +function hooksJson(groups: Group[]): string { + return JSON.stringify({ hooks: { PreToolUse: groups } }); +} + +const WS = path.join(tmp, 'ws'); +mkdirSync(path.join(WS, 'sub'), { recursive: true }); + +function ctx(over: Partial = {}): SessionContext { + return { host: 'codex', cwd: WS, roots: [], permissionMode: 'default', sources: {}, sessionId: 's1', turnId: 't1', model: 'm1', toolUseId: 'call-9', ...over }; +} + +function adapter(files: Record, extra: { argv?: string[]; current?: Record } = {}): CodexHostAdapter { + return new CodexHostAdapter({ + io: () => memoryIo({ files, argv: extra.argv ?? ['codex'] }), + hookEnv: { ...process.env, SHELL: '/bin/sh' }, + stateDir: '/state', + tmpDirs: { slashTmp: '/tmp', tmpdir: null }, + readCurrent: async (abs) => extra.current?.[abs] ?? null, + }); +} + +async function policyOf(a: CodexHostAdapter, c = ctx()): Promise> { + const p = await a.loadPolicy(c); + if ('error' in p) throw new Error(p.error); + return p; +} + +const bash = (command: string, cwd = WS): PreparedCall => ({ id: 'c1', tool: 'bash', args: { command }, effect: { command, cwd, timeoutMs: 1000, containment: { mode: 'none' } } }); +const write = (absPath: string, before: string | null, after: string): PreparedCall => ({ + id: 'c2', + tool: 'write', + args: { path: path.posix.relative(WS, absPath) || absPath, content: after }, + effect: { absPath, beforeHash: before === null ? null : sha(before), afterContent: after, diff: '' }, +}); +const edit = (absPath: string, before: string, after: string): PreparedCall => ({ + id: 'c3', + tool: 'edit', + args: { path: path.posix.relative(WS, absPath), oldString: 'x', newString: 'y' }, + effect: { absPath, beforeHash: sha(before), afterContent: after, diff: '', matchedOldString: 'x', matchStrategy: 'exact', replacements: 1 }, +}); +const read = (absPath: string): PreparedCall => ({ id: 'c4', tool: 'read', args: { path: absPath, offset: 3, limit: 10 }, effect: { absPath, offset: 3, limit: 10 } }); + +async function authorize(a: CodexHostAdapter, prepared: PreparedCall, c = ctx()) { + const p = await policyOf(a, c); + return a.authorize(prepared, c, p, new AbortController().signal); +} + +const managed = (groups: Group[]): Record => ({ '/etc/codex/hooks.json': hooksJson(groups) }); + +describe.runIf(posix)('Codex hooks', () => { + it('denies on exit 2 with stderr', async () => { + const a = adapter(managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.denyRm }] }])); + expect(await authorize(a, bash('rm -rf build'))).toEqual({ kind: 'deny', source: 'hook', reason: 'rm is not allowed' }); + expect(await authorize(a, bash('ls'))).toEqual({ kind: 'allow' }); + }); + + it('denies on JSON permissionDecision deny', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.denyJson }] }])); + expect(await authorize(a, bash('ls'))).toEqual({ kind: 'deny', source: 'hook', reason: 'blocked by policy' }); + }); + + it('maps updatedInput back to bash args', async () => { + const a = adapter(managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.rewrite }] }])); + expect(await authorize(a, bash('echo original'))).toMatchObject({ kind: 'allow', updatedArgs: { command: 'echo rewritten' } }); + }); + + it('times out, kills the hook and denies', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.sleep, timeout: 1 }] }])); + const d = await authorize(a, bash('ls')); + expect(d).toMatchObject({ kind: 'deny', source: 'hook-timeout' }); + const pid = Number(readFileSync(path.join(tmp, 'pid'), 'utf8')); + await new Promise((r) => setTimeout(r, 300)); + expect(() => process.kill(pid, 0)).toThrow(); + }); + + it('fails closed where Codex is non-blocking: crash, invalid JSON, exit 2 without stderr, ask, allow alone', async () => { + for (const cmd of [hooks.crash, hooks.badJson, hooks.silent2, hooks.ask, hooks.allowOnly]) { + const a = adapter(managed([{ hooks: [{ type: 'command', command: cmd }] }])); + expect(await authorize(a, bash('ls')), cmd).toMatchObject({ kind: 'deny', source: 'hook-error' }); + } + // Plain text output is ignored by Codex, and here too. + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.text }] }])); + expect(await authorize(a, bash('ls'))).toEqual({ kind: 'allow' }); + }); + + it('matches apply_patch with the Write|Edit alias, and Bash hooks do not', async () => { + const file = `${WS}/a.txt`; + const a = adapter(managed([{ matcher: 'Write|Edit', hooks: [{ type: 'command', command: hooks.denyJson }] }]), { current: { [file]: 'hello\n' } }); + expect(await authorize(a, write(file, 'hello\n', 'hello\nworld\n'))).toMatchObject({ kind: 'deny', source: 'hook' }); + expect(await authorize(a, edit(file, 'hello\n', 'bye\n'))).toMatchObject({ kind: 'deny', source: 'hook' }); + expect(await authorize(a, bash('ls'))).toEqual({ kind: 'allow' }); + const regex = adapter(managed([{ matcher: '^apply_', hooks: [{ type: 'command', command: hooks.denyJson }] }]), { current: { [file]: 'hello\n' } }); + expect(await authorize(regex, write(file, 'hello\n', 'x\n'))).toMatchObject({ kind: 'deny' }); + }); + + it('runs only user hooks whose trusted_hash matches', async () => { + const group: Group = { matcher: 'Bash', hooks: [{ type: 'command', command: hooks.denyJson }] }; + const key = '/home/u/.codex/hooks.json:pre_tool_use:0:0'; + const hash = commandHookHash({ matcher: 'Bash', command: hooks.denyJson, timeoutSec: 600, async: false }); + const files = (state: string) => ({ '/home/u/.codex/hooks.json': hooksJson([group]), '/home/u/.codex/config.toml': state }); + expect(await authorize(adapter(files('')), bash('ls'))).toEqual({ kind: 'allow' }); + expect(await authorize(adapter(files(`[hooks.state."${key}"]\ntrusted_hash = "${hash}"\n`)), bash('ls'))).toMatchObject({ kind: 'deny', source: 'hook' }); + expect(await authorize(adapter(files(`[hooks.state."${key}"]\ntrusted_hash = "sha256:other"\n`)), bash('ls'))).toEqual({ kind: 'allow' }); + expect(await authorize(adapter(files(`[hooks.state."${key}"]\ntrusted_hash = "${hash}"\nenabled = false\n`)), bash('ls'))).toEqual({ kind: 'allow' }); + // --dangerously-bypass-hook-trust runs it without state. + expect(await authorize(adapter(files(''), { argv: ['codex', '--dangerously-bypass-hook-trust'] }), bash('ls'))).toMatchObject({ kind: 'deny' }); + }); + + it('falls back to deny-only when the trust store cannot be parsed', async () => { + const files = (cmd: string) => ({ + '/home/u/.codex/hooks.json': hooksJson([{ hooks: [{ type: 'command', command: cmd }] }]), + '/home/u/.codex/config.toml': '[hooks]\nstate = "corrupted"\n', + }); + expect(await authorize(adapter(files(hooks.denyJson)), bash('ls'))).toMatchObject({ kind: 'deny', source: 'hook' }); + expect(await authorize(adapter(files(hooks.crash)), bash('ls'))).toEqual({ kind: 'allow' }); + expect(await authorize(adapter(files(hooks.rewrite)), bash('ls'))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + }); + + it('respects features.hooks and allow_managed_hooks_only', async () => { + const userHooks = { '/home/u/.codex/hooks.json': hooksJson([{ hooks: [{ type: 'command', command: hooks.denyJson }] }]) }; + const off = adapter({ ...managed([{ hooks: [{ type: 'command', command: hooks.denyJson }] }]), '/home/u/.codex/config.toml': '[features]\nhooks = false\n' }); + expect(await authorize(off, bash('ls'))).toEqual({ kind: 'allow' }); + const managedOnly = adapter({ ...userHooks, '/home/u/.codex/config.toml': '[hooks]\nstate = 1\n', '/etc/codex/requirements.toml': 'allow_managed_hooks_only = true\n' }); + expect(await authorize(managedOnly, bash('ls'))).toEqual({ kind: 'allow' }); + }); + + it('reads inline [hooks] tables from config.toml', async () => { + const toml = `[[hooks.PreToolUse]]\nmatcher = "Bash"\n[[hooks.PreToolUse.hooks]]\ntype = "command"\ncommand = ${JSON.stringify(hooks.denyRm)}\n`; + expect(await authorize(adapter({ '/etc/codex/config.toml': toml }), bash('rm x'))).toMatchObject({ kind: 'deny', source: 'hook' }); + }); + + it('refuses a broken hooks.json instead of skipping it', async () => { + expect(await adapter({ '/etc/codex/hooks.json': '{' }).loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('invalid JSON') }); + expect(await adapter({ '/etc/codex/hooks.json': '{"hooks":{},"extra":1}' }).loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('invalid hooks file') }); + }); +}); + +describe.runIf(posix)('exactness: what the hook sees is what will be applied', () => { + const recorded = (): Record => JSON.parse(readFileSync(path.join(tmp, 'stdin.json'), 'utf8')); + + it('shows bash as Bash {command} with the Codex hook input fields', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.record }] }])); + const call = bash('git status && ls -la', `${WS}/sub`); + await authorize(a, call); + const input = recorded(); + expect(input).toEqual({ + session_id: 's1', + turn_id: 't1', + transcript_path: null, + cwd: `${WS}/sub`, + hook_event_name: 'PreToolUse', + model: 'm1', + permission_mode: 'default', + tool_name: 'Bash', + tool_input: { command: call.tool === 'bash' ? call.effect.command : '' }, + tool_use_id: 'call-9/c1', + }); + }); + + it('shows write and edit as an apply_patch that reproduces the after content', async () => { + const file = `${WS}/src/app.ts`; + const before = 'const a = 1;\nconst b = 2;\nconst c = 3;\n'; + const after = 'const a = 1;\nconst b = 20;\nconst c = 3;\nexport { a };\n'; + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.record }] }]), { current: { [file]: before } }); + for (const call of [write(file, before, after), edit(file, before, after), write(`${WS}/new.txt`, null, 'fresh\n')]) { + expect(await authorize(a, call)).toEqual({ kind: 'allow' }); + const input = recorded(); + expect(input['tool_name']).toBe('apply_patch'); + const toolInput = input['tool_input']; + if (typeof toolInput !== 'object' || toolInput === null || !('command' in toolInput) || typeof toolInput.command !== 'string') throw new Error('no command'); + const { hunks } = parsePatch(toolInput.command); + const hunk = hunks[0]; + if (hunk === undefined || call.tool === 'bash' || call.tool === 'read' || call.tool === 'grep' || call.tool === 'glob') throw new Error('bad'); + expect(path.posix.resolve(WS, hunk.path)).toBe(call.effect.absPath); + const current = call.effect.beforeHash === null ? null : before; + expect(applyHunk(hunk.kind === 'add' ? null : current, hunk)).toBe(call.effect.afterContent); + } + }); + + it('shows read as the sed command Codex would run', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.record }] }])); + await authorize(a, read(`${WS}/it's.txt`)); + expect(recorded()['tool_input']).toEqual({ command: `sed -n '3,12p' -- '${WS}/it'\\''s.txt'` }); + }); + + it('maps a rewritten apply_patch back to a write', async () => { + const file = `${WS}/hello.txt`; + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.patchRewrite }] }]), { current: { [file]: 'hello\n' } }); + expect(await authorize(a, write(file, 'hello\n', 'hello\nworld\n'))).toMatchObject({ kind: 'allow', updatedArgs: { path: 'hello.txt', content: 'hello\nWORLD\n' } }); + expect(await authorize(a, edit(file, 'hello\n', 'hello\nworld\n'))).toMatchObject({ kind: 'allow', updatedArgs: { path: 'hello.txt', oldString: 'hello\n', newString: 'hello\nWORLD\n' } }); + }); + + it('denies when the file changed after prepare', async () => { + const file = `${WS}/a.txt`; + const a = new CodexHostAdapter({ io: () => memoryIo({ files: managed([{ hooks: [{ type: 'command', command: hooks.record }] }]), argv: ['codex'] }), stateDir: '/state' }); + const real = path.join(tmp, 'changed.txt'); + writeFileSync(real, 'now\n'); + expect(await authorize(a, write(real, 'before\n', 'after\n'))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + void file; + }); +}); + +describe.runIf(posix)('sandbox mode × tool', () => { + const rules = { '/home/u/.codex/rules/default.rules': 'prefix_rule(pattern=["rm"], decision="forbidden")\nprefix_rule(pattern=["git", "push"], decision="prompt")\n' }; + + async function decide(mode: string, prepared: PreparedCall, files: Record = {}, argv: string[] = ['codex']) { + const a = adapter(files, { argv }); + const c = ctx({ sandboxMode: mode }); + const p = await policyOf(a, c); + return { decision: a.checkStatic(prepared, c, p), containment: p.bashContainment }; + } + + it('returns the containment of each mode', async () => { + expect((await decide('read-only', bash('ls'))).containment).toEqual({ mode: 'sandbox', readOnly: true, writableRoots: [], network: false }); + expect((await decide('workspace-write', bash('ls'), { '/home/u/.codex/config.toml': '[sandbox_workspace_write]\nwritable_roots = ["/data"]\nnetwork_access = true\n' })).containment).toEqual({ + mode: 'sandbox', + readOnly: false, + writableRoots: [WS, '/data', '/tmp'], + network: true, + }); + expect((await decide('danger-full-access', bash('ls'))).containment).toEqual({ mode: 'none' }); + }); + + it('decides write/edit per mode', async () => { + const inside = write(`${WS}/a.txt`, null, 'x'); + const outside = write('/etc/x.conf', null, 'x'); + const git = write(`${WS}/.git/config`, null, 'x'); + expect((await decide('read-only', inside)).decision.kind).toBe('ask'); + expect((await decide('workspace-write', inside)).decision.kind).toBe('allow'); + expect((await decide('workspace-write', write('/tmp/scratch', null, 'x'))).decision.kind).toBe('allow'); + expect((await decide('workspace-write', outside)).decision.kind).toBe('ask'); + expect((await decide('workspace-write', git)).decision.kind).toBe('ask'); + expect((await decide('danger-full-access', outside)).decision.kind).toBe('allow'); + // With approval never, what Codex would ask is rejected. + expect((await decide('read-only', inside, {}, ['codex', 'exec'])).decision).toMatchObject({ kind: 'deny', source: 'rule' }); + }); + + it('applies exec policy rules to bash and to shell-shaped reads in every mode', async () => { + for (const mode of ['read-only', 'workspace-write', 'danger-full-access']) { + expect((await decide(mode, bash('ls'), rules)).decision.kind).toBe('allow'); + expect((await decide(mode, bash('ls && rm -rf x'), rules)).decision).toMatchObject({ kind: 'deny', source: 'rule' }); + expect((await decide(mode, bash('git push origin'), rules)).decision.kind).toBe('ask'); + expect((await decide(mode, read(`${WS}/a.txt`), rules)).decision.kind).toBe('allow'); + } + const sedRule = { '/home/u/.codex/rules/default.rules': 'prefix_rule(pattern=["sed"], decision="forbidden")\n' }; + expect((await decide('read-only', read(`${WS}/a.txt`), sedRule)).decision.kind).toBe('deny'); + expect((await decide('read-only', bash('rm -rf build'))).decision.kind).toBe('ask'); + expect((await decide('read-only', bash('ls'), {}, ['codex', '-a', 'untrusted'])).decision.kind).toBe('ask'); + expect((await decide('read-only', bash("echo 'x"))).decision).toMatchObject({ kind: 'deny', source: 'rule' }); + }); + + it('fails the load on bad rules and unknown sandbox modes', async () => { + const bad = adapter({ '/home/u/.codex/rules/x.rules': 'network_rule(host="a", protocol="https", decision="allow")' }); + expect(await bad.loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('outside the supported rules subset') }); + expect(await adapter({}).loadPolicy(ctx({ sandboxMode: 'mystery' }))).toMatchObject({ error: expect.stringContaining('mystery') }); + }); + + it('protects Codex policy files and the state dir', async () => { + const p = await policyOf(adapter({})); + expect(p.protectedPaths).toEqual(expect.arrayContaining(['**/.codex/**', '/home/u/.codex/**', '/etc/codex/**', '/state/**', `${WS}/.mcp.json`])); + }); +}); + +describe.runIf(posix)('dispatcher integration', () => { + it('re-prepares a hook rewrite and commits exactly the rewritten command', async () => { + const tools = new MemoryToolRuntime({ root: WS }); + const a = adapter(managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.rewrite }] }])); + const c = ctx({ sandboxMode: 'danger-full-access' }); + const policy = await a.loadPolicy(c); + const d = new Dispatcher({ adapter: a, tools, ctx: c, policy }); + const reply = await d.dispatch('bash', { command: 'echo original' }); + expect(reply.ok).toBe(true); + expect(tools.commits.map((x) => x.target)).toEqual(['echo rewritten']); + }); + + it('denies every call when the config cannot be loaded', async () => { + const tools = new MemoryToolRuntime({ root: WS }); + const a = adapter({ '/home/u/.codex/config.toml': 'not = = toml' }); + const c = ctx(); + const d = new Dispatcher({ adapter: a, tools, ctx: c, policy: await a.loadPolicy(c) }); + const reply = await d.dispatch('bash', { command: 'ls' }); + expect(reply).toMatchObject({ ok: false, error: { code: 'denied', source: 'unsupported-config' } }); + }); +}); + +describe('CodexContextProvider', () => { + it('reads _meta and the server cwd, never tool args', async () => { + const cwd = path.resolve(tmp); + const c = await new CodexContextProvider().resolve({ + env: {}, + roots: [], + serverCwd: cwd, + meta: { + callId: 'exec-1', + sessionId: 'ses', + threadId: 'thr', + 'x-codex-turn-metadata': { session_id: 'ses', turn_id: 'turn', model: 'gpt', sandbox: 'seccomp', sandbox_mode: 'workspace-write', extra: 1 }, + _ctx: { cwd: '/evil' }, + }, + }); + expect(c).toMatchObject({ host: 'codex', cwd, sessionId: 'ses', turnId: 'turn', model: 'gpt', sandboxMode: 'workspace-write', toolUseId: 'exec-1' }); + const junk = await new CodexContextProvider().resolve({ env: {}, roots: [], serverCwd: cwd, meta: { 'x-codex-turn-metadata': 'nope', callId: 5 } }); + expect(junk.sandboxMode).toBeUndefined(); + expect(junk.toolUseId).toBeUndefined(); + }); +}); diff --git a/src/hosts/codex/adapter.ts b/src/hosts/codex/adapter.ts new file mode 100644 index 0000000..4808c2e --- /dev/null +++ b/src/hosts/codex/adapter.ts @@ -0,0 +1,295 @@ +/** + * Codex CLI host adapter: authorizes every binding call the way Codex 0.169 + * authorizes the equivalent native action. + * + * Reference: openai/codex rust-v0.169.0 (commit d32063f96c2d). See config.ts, + * exec-policy.ts, hooks.ts and apply-patch.ts for the parts of the source + * each piece follows. + * + * checkStatic (no I/O): + * - Shell-shaped calls (bash, and read/grep/glob shown as the shell command + * Codex would run) go through the exec policy rules on every simple + * command: forbidden → deny, prompt → ask, allow → allow; strictest wins. + * Unmatched commands follow Codex's heuristics: a forced `rm` asks, and the + * `untrusted` approval policy asks for everything not allowed by a rule. + * With approval `never`, Codex rejects what it would ask: deny. + * - write/edit follow the sandbox mode: `read-only` asks, `workspace-write` + * allows inside the writable roots (except `.git`, `.agents`, `.codex`, + * `.aws` below them) and asks elsewhere, `danger-full-access` allows. + * + * Deviation (stricter than Codex): an exec-policy `allow` does not lift bash + * containment; the containment is always the sandbox mode's. + */ + +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { stateDirPath } from '../../core/state-dir.js'; +import type { BashContainment, Decision, HostAdapter, PolicyLoadError, PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; +import { ConfigError, loadCodexConfig, nodeConfigIo, ruleFiles, type ApprovalPolicy, type ConfigIo, type SandboxMode } from './config.js'; +import { isDangerousCommand, matchRules, parseRulesFile, RulesParseError, strictest, type ExecPolicy, type PrefixRule } from './exec-policy.js'; +import { discoverHooks, runHooks, type HookHandler } from './hooks.js'; +import { mapUpdatedInput, nativeCall, NativeShapeError, shellCommandFor, type NativeCall } from './native.js'; +import { ShellParseError, splitShellCommands } from './shell.js'; + +/** Adapter-specific part of the policy snapshot. */ +export interface CodexPolicy { + readonly sandboxMode: SandboxMode; + readonly approvalPolicy: ApprovalPolicy; + /** Roots write/edit may change without asking (workspace-write only). */ + readonly writableRoots: readonly string[]; + readonly rules: ExecPolicy; + readonly hooks: readonly HookHandler[]; + readonly hooksEnabled: boolean; + /** Hook `permission_mode`: `bypassPermissions` when approval is `never`, else `default`. */ + readonly permissionMode: string; + readonly codexHome: string; + readonly notes: readonly string[]; +} + +export interface CodexHostAdapterOptions { + /** Filesystem and process access (tests). Defaults to the real ones. */ + readonly io?: (ctx: SessionContext) => ConfigIo; + /** Environment of hook processes. Defaults to `process.env`. */ + readonly hookEnv?: Readonly>; + /** Server state directory, protected from writes. */ + readonly stateDir?: string; + /** Temp directories writable in workspace-write. Defaults to `/tmp` and `$TMPDIR`. */ + readonly tmpDirs?: { readonly slashTmp: string | null; readonly tmpdir: string | null }; + /** Replaces how the current file is read for write/edit (tests). */ + readonly readCurrent?: (absPath: string, beforeHash: string | null) => Promise; +} + +const READ_ONLY_SUBPATHS = ['.git', '.agents', '.codex', '.aws']; +const SANDBOX_MODES: readonly string[] = ['read-only', 'workspace-write', 'danger-full-access']; + +function isInside(child: string, parent: string): boolean { + const rel = path.relative(parent, child); + return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); +} + +function unique(xs: readonly string[]): string[] { + return [...new Set(xs)]; +} + +/** Codex PreToolUse hook input (hooks/src/schema.rs `PreToolUseCommandInput`). */ +export function hookInput(prepared: PreparedCall, native: NativeCall, ctx: SessionContext, policy: CodexPolicy): Record { + return { + session_id: ctx.sessionId ?? '', + turn_id: ctx.turnId ?? '', + transcript_path: ctx.transcriptPath ?? null, + cwd: native.cwd, + hook_event_name: 'PreToolUse', + model: ctx.model ?? '', + permission_mode: policy.permissionMode, + tool_name: native.toolName, + tool_input: native.toolInput, + tool_use_id: ctx.toolUseId === undefined ? prepared.id : `${ctx.toolUseId}/${prepared.id}`, + }; +} + +/** Builds the bash containment of a sandbox mode. */ +export function containmentFor(mode: SandboxMode, writableRoots: readonly string[], network: boolean): BashContainment { + switch (mode) { + case 'read-only': + return { mode: 'sandbox', readOnly: true, writableRoots: [], network: false }; + case 'workspace-write': + return { mode: 'sandbox', readOnly: false, writableRoots: [...writableRoots], network }; + case 'danger-full-access': + return { mode: 'none' }; + } +} + +export class CodexHostAdapter implements HostAdapter { + readonly host = 'codex' as const; + readonly #opts: CodexHostAdapterOptions; + + constructor(opts: CodexHostAdapterOptions = {}) { + this.#opts = opts; + } + + async loadPolicy(ctx: SessionContext): Promise | PolicyLoadError> { + try { + return this.#load(ctx); + } catch (err) { + if (err instanceof ConfigError || err instanceof RulesParseError) return { error: err.message }; + return { error: `cannot load the Codex configuration: ${err instanceof Error ? err.message : String(err)}` }; + } + } + + #load(ctx: SessionContext): PolicySnapshot { + const io = this.#opts.io ? this.#opts.io(ctx) : nodeConfigIo(parentAwareEnv()); + const config = loadCodexConfig(ctx.cwd, io); + + const rules: PrefixRule[] = []; + for (const file of ruleFiles(config, io)) { + const text = io.readFile(file); + if (text === undefined) continue; + rules.push(...parseRulesFile(text, file)); + } + const { hooks, notes: hookNotes } = discoverHooks(config, io); + + // The host's own turn metadata is authoritative for the sandbox mode. + let sandboxMode = config.sandboxMode; + if (ctx.sandboxMode !== undefined) { + if (!SANDBOX_MODES.includes(ctx.sandboxMode)) throw new ConfigError(`unknown Codex sandbox mode ${JSON.stringify(ctx.sandboxMode)}`); + sandboxMode = ctx.sandboxMode === 'read-only' ? 'read-only' : ctx.sandboxMode === 'workspace-write' ? 'workspace-write' : 'danger-full-access'; + } + + const tmp = this.#opts.tmpDirs ?? { slashTmp: process.platform === 'win32' ? null : '/tmp', tmpdir: io.env['TMPDIR'] ?? null }; + const tmpRoots = [ + ...(config.excludeSlashTmp || tmp.slashTmp === null ? [] : [tmp.slashTmp]), + ...(config.excludeTmpdirEnvVar || tmp.tmpdir === null || !path.isAbsolute(tmp.tmpdir) ? [] : [tmp.tmpdir]), + ]; + const writableRoots = unique([config.cwd, ...config.writableRoots, ...tmpRoots].map((p) => path.resolve(p))); + const bashContainment = containmentFor(sandboxMode, writableRoots, config.networkAccess); + + const stateDir = this.#opts.stateDir ?? stateDirPath(io.env, io.home); + const homeCodex = path.join(io.home, '.codex'); + const protectedPaths = unique([ + '**/.codex/**', + `${config.codexHome}/**`, + `${io.realpath(config.codexHome)}/**`, + `${homeCodex}/**`, + `${io.systemDir}/**`, + `${stateDir}/**`, + path.join(config.cwd, '.mcp.json'), + path.join(config.projectRoot, '.mcp.json'), + ]); + + return { + host: 'codex', + bashContainment, + protectedPaths, + payload: { + sandboxMode, + approvalPolicy: config.approvalPolicy, + writableRoots: sandboxMode === 'workspace-write' ? writableRoots : [], + rules: { rules }, + hooks, + hooksEnabled: config.hooksEnabled, + permissionMode: config.approvalPolicy === 'never' ? 'bypassPermissions' : 'default', + codexHome: config.codexHome, + notes: [...config.notes, ...hookNotes], + }, + }; + } + + checkStatic(prepared: PreparedCall, _ctx: SessionContext, policy: PolicySnapshot): Decision { + const p = policy.payload; + if (prepared.tool === 'write' || prepared.tool === 'edit') return checkFileWrite(prepared.effect.absPath, p); + const command = shellCommandFor(prepared); + if (command === undefined) return { kind: 'deny', source: 'rule', reason: 'no shell form for this call' }; + return checkShellCommand(command, p); + } + + async authorize(prepared: PreparedCall, ctx: SessionContext, policy: PolicySnapshot, signal: AbortSignal): Promise { + const p = policy.payload; + if (!p.hooksEnabled || p.hooks.length === 0) return { kind: 'allow' }; + let native: NativeCall; + try { + native = await nativeCall(prepared, ctx, this.#opts.readCurrent); + } catch (err) { + const reason = err instanceof NativeShapeError ? err.message : `cannot build the Codex tool input: ${err instanceof Error ? err.message : String(err)}`; + return { kind: 'deny', source: 'hook-error', reason }; + } + const result = await runHooks({ + hooks: p.hooks, + names: native.names, + stdin: JSON.stringify(hookInput(prepared, native, ctx, p)), + cwd: native.cwd, + env: this.#opts.hookEnv ?? process.env, + platform: process.platform, + signal, + }); + if (result.kind === 'deny') return { kind: 'deny', source: result.source, reason: result.reason }; + if (result.updatedInput === undefined) return { kind: 'allow' }; + const mapped = mapUpdatedInput(prepared, native, result.updatedInput, ctx); + switch (mapped.kind) { + case 'unchanged': + return { kind: 'allow' }; + case 'updated': + return { kind: 'allow', updatedArgs: mapped.args, reason: 'rewritten by a Codex PreToolUse hook' }; + case 'invalid': + return { kind: 'deny', source: 'hook-error', reason: mapped.reason }; + case 'unsupported': + return { kind: 'deny', source: 'unsupported-config', reason: mapped.reason }; + } + } +} + +/** Static decision for a shell command (exec policy rules plus Codex heuristics). */ +export function checkShellCommand(command: string, p: CodexPolicy): Decision { + let split; + try { + split = splitShellCommands(command); + } catch (err) { + const why = err instanceof ShellParseError ? err.message : String(err); + return { kind: 'deny', source: 'rule', reason: `the command cannot be parsed for the Codex exec policy: ${why}` }; + } + const commands = [...split.commands]; + // Codex evaluates a script it cannot split as the single argv `bash -lc