From fe45eaf40eb693356b7995c8ac81177b94186b5e Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:58:42 -0300 Subject: [PATCH 01/13] Compact run results, exact read() text, relative result paths Prototype from the 2026-11-16 cost analysis: the run response reports call counts and keeps every denied or failed call, clips large diffs, and returns paths relative to the working directory; read() returns the file text exactly; the binding docs move from server instructions to the tool description. verbose: true returns the full call log and diff. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- bench/lib/claude.ts | 18 ++---- bench/lib/codex.ts | 16 ++---- bench/lib/run-result.ts | 42 ++++++++++++++ bench/test/parsers.test.ts | 10 ++++ src/core/contracts.test.ts | 8 +-- src/core/dispatcher.ts | 15 ++++- src/core/output.test.ts | 80 +++++++++++++++++++++++++- src/core/output.ts | 85 ++++++++++++++++++++++++---- src/core/schemas.ts | 5 ++ src/core/types.ts | 12 ++-- src/hosts/claude/adapter.test.ts | 14 ++++- src/hosts/claude/adapter.ts | 11 +++- src/hosts/claude/regressions.test.ts | 9 +-- src/server/mcp.test.ts | 26 ++++++++- src/server/mcp.ts | 28 ++++++--- src/server/runtime.test.ts | 2 +- src/testing/memory-tool-runtime.ts | 3 +- src/tools/runtime.test.ts | 17 +++++- src/tools/runtime.ts | 5 +- test/attack/harness.ts | 5 +- test/attack/hooks.test.ts | 2 +- test/attack/paths.test.ts | 2 +- 23 files changed, 345 insertions(+), 74 deletions(-) create mode 100644 bench/lib/run-result.ts diff --git a/README.md b/README.md index cb348b3..d563902 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ return { files: hits.matches.length, exitCode: test.exitCode }; | `grep({pattern, path?, glob?, ignoreCase?, maxResults?})` | `{matches: [{file, line, text}], truncated, filtered}` | | `glob({pattern, path?, maxResults?})` | `{files, truncated, filtered}` | -`console.log/info/warn/error` go to `logs`. A denied call rejects with an `Error` named `PermissionDenied` (with `source` and `reason`); other failures reject with `ToolError` (with `code`). `run` takes `{code, transaction?, timeoutMs?}`. With `transaction: true`, file changes are rolled back if the script throws, times out, is cancelled or any call is denied; if the server process dies mid-run, the next start restores them from its journal (inside the roots of that run only). The result holds the return value, logs, a call log, the changed files and a combined diff. +`console.log/info/warn/error` go to `logs`. A denied call rejects with an `Error` named `PermissionDenied` (with `source` and `reason`); other failures reject with `ToolError` (with `code`). `read` returns the exact text of the lines, final newline included, and paths in results are relative to the working directory when inside it. `run` takes `{code, transaction?, timeoutMs?, verbose?}`. With `transaction: true`, file changes are rolled back if the script throws, times out, is cancelled or any call is denied; if the server process dies mid-run, the next start restores them from its journal (inside the roots of that run only). The result holds the return value, logs, the number of calls by tool with every denied or failed call, the changed files and a combined diff; a diff above 1,500 characters is cut and the whole result saved to a file. `verbose: true` returns the log of every call and the whole diff. Edits that do not match exactly fall back through tolerant rungs (line endings, copied line numbers, trailing whitespace, indentation, typographic punctuation). `matchStrategy` says which rung matched. @@ -110,7 +110,7 @@ Output is capped below the hosts' MCP limits (about 30,000 characters, less for ## Compared with the built-in code modes -- **Claude Code's official Code Mode** applies the same per-call rules and hooks, but only in interactive sessions. agent-code-mode also works in `claude -p`, the Agent SDK and Codex, and every call shows up in a call log you get back. +- **Claude Code's official Code Mode** applies the same per-call rules and hooks, but only in interactive sessions. agent-code-mode also works in `claude -p`, the Agent SDK and Codex, and every denied or failed call shows up in the result you get back (every call with `verbose: true`). - **Codex's own code mode.** Codex 0.169 models already run in Codex's code mode by default (its `exec` tool calls nested tools). agent-code-mode gives Codex the same binding surface as Claude, with transactions, the call log and your hooks applied to file reads and edits made inside the script. ## Benchmark diff --git a/bench/lib/claude.ts b/bench/lib/claude.ts index 0dbe773..a4429aa 100644 --- a/bench/lib/claude.ts +++ b/bench/lib/claude.ts @@ -1,5 +1,6 @@ import { z } from 'zod'; import type { ArmId, ParsedRun, ToolCalls } from './record.ts'; +import { runInnerCalls } from './run-result.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']; @@ -99,11 +100,6 @@ export function claudeIsolationIssues(ctx: { agents: readonly string[]; plugins: return reasons; } -/** 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(), summary: z.string().optional(), reason: z.string().optional() }).passthrough()), -}).passthrough(); - function textOf(content: unknown): string { if (typeof content === 'string') return content; if (Array.isArray(content)) { @@ -190,14 +186,12 @@ export function parseClaudeTranscript(text: string): ParsedRun { // A result can be replayed in the stream (e.g. on resume); count each tool_use_id once. if (tr.success && runToolUses.has(tr.data.tool_use_id) && !seenToolResult.has(tr.data.tool_use_id)) { seenToolResult.add(tr.data.tool_use_id); - const parsed = RunResultText.safeParse(parseJson(textOf(tr.data.content))); - if (parsed.success) { + const innerCalls = runInnerCalls(textOf(tr.data.content)); + if (innerCalls !== null) { innerSeen = true; - for (const call of parsed.data.calls) { - innerTotal += 1; - inner[call.tool] = (inner[call.tool] ?? 0) + 1; - if (call.decision === 'denied') denials.push(`${call.tool} ${call.summary ?? ''}: ${call.reason ?? 'denied'}`.slice(0, 500)); - } + innerTotal += innerCalls.total; + for (const [tool, n] of Object.entries(innerCalls.byTool)) inner[tool] = (inner[tool] ?? 0) + n; + denials.push(...innerCalls.denials); evidence['innerCalls']?.push(i + 1); } } diff --git a/bench/lib/codex.ts b/bench/lib/codex.ts index 6583577..5613990 100644 --- a/bench/lib/codex.ts +++ b/bench/lib/codex.ts @@ -1,5 +1,6 @@ import { z } from 'zod'; import type { ArmId, ParsedRun, ToolCalls } from './record.ts'; +import { runInnerCalls } from './run-result.ts'; /** * Codex CLI 0.169 facts the arms depend on (checked with `codex debug prompt-input`, no model calls): @@ -190,9 +191,6 @@ const Failure = z.object({ type: z.enum(['turn.failed', 'error']), error: z.obje 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 DenialLine = z.object({ kind: z.literal('denial'), text: z.string() }); -const RunResultText = z.object({ - calls: z.array(z.object({ tool: z.string(), decision: z.string().optional(), summary: z.string().optional(), reason: z.string().optional() }).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' { @@ -275,14 +273,12 @@ export function parseCodexTranscript(json: string, requests: string | null): Par 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) { + const innerCalls = runInnerCalls(text); + if (innerCalls !== null) { runInnerSeen = true; - for (const c of log.data.calls) { - runInnerTotal += 1; - runInner[c.tool] = (runInner[c.tool] ?? 0) + 1; - if (c.decision === 'denied') runDenials.push(`${c.tool} ${c.summary ?? ''}: ${c.reason ?? 'denied'}`.slice(0, 500)); - } + runInnerTotal += innerCalls.total; + for (const [tool, n] of Object.entries(innerCalls.byTool)) runInner[tool] = (runInner[tool] ?? 0) + n; + runDenials.push(...innerCalls.denials); } } } else if (type === 'command_execution' || type === 'file_change') { diff --git a/bench/lib/run-result.ts b/bench/lib/run-result.ts new file mode 100644 index 0000000..4de0d3f --- /dev/null +++ b/bench/lib/run-result.ts @@ -0,0 +1,42 @@ +import { z } from 'zod'; + +/** + * The agent-code-mode `run` response as the server returns it (only the fields the bench reads). + * `calls` is the full log (verbose, and every result before the compact view existed) or the + * compact summary: counts by tool plus the denied calls. + */ +const Call = z.object({ tool: z.string(), decision: z.string().optional(), summary: z.string().optional(), reason: z.string().optional() }).passthrough(); +const RunResultText = z.object({ + calls: z.union([ + z.array(Call), + z.object({ total: z.number().int().nonnegative(), byTool: z.record(z.string(), z.number().int().nonnegative()), denied: z.array(z.union([Call, z.string()])).optional() }).passthrough(), + ]), +}).passthrough(); + +export interface RunInnerCalls { + readonly total: number; + readonly byTool: Readonly>; + /** One line per denied inner call. */ + readonly denials: readonly string[]; +} + +const denialLine = (c: z.infer): string => `${c.tool} ${c.summary ?? ''}: ${c.reason ?? 'denied'}`.slice(0, 500); + +/** Inner calls of one `run` response text; null when the text is not a run result. */ +export function runInnerCalls(text: string): RunInnerCalls | null { + let json: unknown; + try { + json = JSON.parse(text); + } catch { + return null; + } + const parsed = RunResultText.safeParse(json); + if (!parsed.success) return null; + const calls = parsed.data.calls; + if (Array.isArray(calls)) { + const byTool: Record = {}; + for (const c of calls) byTool[c.tool] = (byTool[c.tool] ?? 0) + 1; + return { total: calls.length, byTool, denials: calls.filter((c) => c.decision === 'denied').map(denialLine) }; + } + return { total: calls.total, byTool: calls.byTool, denials: (calls.denied ?? []).flatMap((c) => (typeof c === 'string' ? [] : [denialLine(c)])) }; +} diff --git a/bench/test/parsers.test.ts b/bench/test/parsers.test.ts index afed50f..4e8c298 100644 --- a/bench/test/parsers.test.ts +++ b/bench/test/parsers.test.ts @@ -5,6 +5,7 @@ import { claudeIsolationIssues, parseClaudeTranscript } from '../lib/claude.ts'; import { classifyCodexTool, codexToolSurface, extractCodexRequests, parseCodexTranscript } from '../lib/codex.ts'; import { costFromUsage, loadPricing } from '../lib/pricing.ts'; import { checkArm, checkSurface } from '../lib/record.ts'; +import { runInnerCalls } from '../lib/run-result.ts'; const F = path.join(import.meta.dirname, '..', 'parser-fixtures'); const read = (name: string): string => readFileSync(path.join(F, name), 'utf8'); @@ -49,6 +50,15 @@ describe('Claude transcript parser', () => { expect(p.innerCalls).toEqual({ total: 3, byTool: { read: 2, grep: 1 } }); }); + it('reads the compact run response: call counts and the denied calls', () => { + const compact = { ok: true, result: 1, calls: { total: 5, byTool: { read: 3, bash: 2 }, denied: [{ id: 'c2', tool: 'bash', summary: 'bash rm x', reason: 'rule: no rm' }, '…[1 more]'] } }; + expect(runInnerCalls(JSON.stringify(compact))).toEqual({ total: 5, byTool: { read: 3, bash: 2 }, denials: ['bash bash rm x: rule: no rm'] }); + const full = { ok: true, calls: [{ id: 'c1', tool: 'read', summary: 'read a', decision: 'allowed' }, { id: 'c2', tool: 'bash', summary: 'bash rm x', decision: 'denied', reason: 'rule: no rm' }] }; + expect(runInnerCalls(JSON.stringify(full))).toEqual({ total: 2, byTool: { read: 1, bash: 1 }, denials: ['bash bash rm x: rule: no rm'] }); + expect(runInnerCalls('not json')).toBeNull(); + expect(runInnerCalls('{"ok":true}')).toBeNull(); + }); + it('collects denied calls from hook errors and the run call log', () => { const lines = [ { type: 'assistant', message: { content: [{ type: 'tool_use', id: 'e1', name: 'Edit', input: {} }] } }, diff --git a/src/core/contracts.test.ts b/src/core/contracts.test.ts index a61c699..02daf30 100644 --- a/src/core/contracts.test.ts +++ b/src/core/contracts.test.ts @@ -116,10 +116,10 @@ describe('PolicySnapshot.readFilter and additionalRoots', () => { }; const d = dispatcherFor(ctx, policy); const grep = value(await d.dispatch('grep', { pattern: 'token' })); - expect(grep.matches.map((m) => path.relative(ws, m.file))).toEqual([path.join('src', 'a.ts')]); + expect(grep.matches.map((m) => m.file)).toEqual(['src/a.ts']); expect(grep.filtered).toBe(2); const glob = value(await d.dispatch('glob', { pattern: '**/*' })); - expect(glob.files.map((f) => path.relative(ws, f))).toEqual([path.join('src', 'a.ts')]); + expect(glob.files).toEqual(['src/a.ts']); expect(glob.filtered).toBe(2); }); @@ -142,7 +142,7 @@ describe('PolicySnapshot.readFilter and additionalRoots', () => { expect(denied.ok ? undefined : denied.error.code).toBe('outside-workspace'); const withRoot: PolicySnapshot = { ...without, additionalRoots: [extra] }; const d = dispatcherFor(ctx, withRoot); - expect(value<{ content: string }>(await d.dispatch('read', { path: path.join(extra, 'x.txt') })).content).toBe('x'); + expect(value<{ content: string }>(await d.dispatch('read', { path: path.join(extra, 'x.txt') })).content).toBe('x\n'); const stillOut = await d.dispatch('read', { path: path.join(base, 'outside.txt') }); expect(stillOut.ok ? undefined : stillOut.error.code).toBe('outside-workspace'); }); @@ -196,7 +196,7 @@ describe('Claude policy wiring', () => { expect(policy.readFilter?.(path.join(project, 'private', 'p.txt'))).toBe(false); expect(policy.readFilter?.(path.join(project, 'src', 'ok.txt'))).toBe(true); const grep = value(await d.dispatch('grep', { pattern: 'key' })); - expect(grep.matches.map((m) => path.relative(project, m.file))).toEqual([path.join('src', 'ok.txt')]); + expect(grep.matches.map((m) => m.file)).toEqual(['src/ok.txt']); expect(grep.filtered).toBe(2); }); diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts index 7d52199..ded4986 100644 --- a/src/core/dispatcher.ts +++ b/src/core/dispatcher.ts @@ -434,7 +434,7 @@ export class Dispatcher

{ } this.#calls[slot] = { id: prepared.id, tool: prepared.tool, summary, decision: 'allowed', durationMs: this.#elapsed(started) }; - return { ok: true, value: result }; + return { ok: true, value: scriptResult(result, this.#opts.ctx.cwd) }; } #toolFailure(err: unknown): Failure { @@ -566,6 +566,19 @@ export function displayPath(absPath: string, cwd: string): string { return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : absPath; } +/** + * The result as the script sees it: paths inside `cwd` are relative to it + * (they resolve back to the same file when passed to a binding), so a result + * the script returns does not repeat the workspace path in every entry. + * Hooks and the diff keep the tool runtime's absolute paths. + */ +export function scriptResult(result: ToolResult, cwd: string): ToolResult { + if ('matches' in result) return { ...result, matches: result.matches.map((m) => ({ ...m, file: displayPath(m.file, cwd) })) }; + if ('files' in result) return { ...result, files: result.files.map((f) => displayPath(f, cwd)) }; + if ('path' in result) return { ...result, path: displayPath(result.path, cwd) }; + return result; +} + /** Short description of a call for the call log. */ export function summarize(call: ToolCall, cwd: string): string { const p = (value: string): string => displayPath(path.resolve(cwd, value), cwd); diff --git a/src/core/output.test.ts b/src/core/output.test.ts index 409c2af..03bf5db 100644 --- a/src/core/output.test.ts +++ b/src/core/output.test.ts @@ -2,9 +2,9 @@ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; -import { ERROR_CAP_CHARS, SUCCESS_CAP_CHARS, formatRunResult, truncateStructurally } from './output.js'; +import { CHANGED_FILES_SHOWN, DIFF_INLINE_CHARS, DIFF_SAMPLE_CHARS, ERROR_CAP_CHARS, FAILED_CALLS_SHOWN, SUCCESS_CAP_CHARS, compactRunResult, formatRunResult, truncateStructurally } from './output.js'; import { stateDirPath } from './state-dir.js'; -import type { RunResult } from './types.js'; +import type { CallLogEntry, RunResult } from './types.js'; const base: RunResult = { ok: true, result: null, logs: [], calls: [], changedFiles: [], diff: '', warnings: [] }; const dirs: string[] = []; @@ -17,7 +17,83 @@ afterEach(async () => { await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true }))); }); +const allowed = (i: number, tool = 'read'): CallLogEntry => ({ id: `c${i}`, tool, summary: `${tool} f${i}.txt`, decision: 'allowed', durationMs: 2 }); + +describe('compactRunResult', () => { + it('turns the call log into counts and keeps denied and failed calls in full, without durations', () => { + const calls: CallLogEntry[] = [ + allowed(1), + allowed(2, 'write'), + { id: 'c3', tool: 'bash', summary: 'bash rm x', decision: 'denied', reason: 'rule: rm is not allowed', durationMs: 9 }, + { id: 'c4', tool: 'read', summary: 'read gone.txt', decision: 'error', reason: 'gone.txt does not exist', durationMs: 1 }, + allowed(5), + ]; + expect(compactRunResult({ ...base, calls }).view['calls']).toEqual({ + total: 5, + byTool: { read: 3, write: 1, bash: 1 }, + denied: [{ id: 'c3', tool: 'bash', summary: 'bash rm x', reason: 'rule: rm is not allowed' }], + errors: [{ id: 'c4', tool: 'read', summary: 'read gone.txt', reason: 'gone.txt does not exist' }], + }); + }); + + it('does not grow with the number of allowed calls and caps the list of failed ones', () => { + const few = JSON.stringify(compactRunResult({ ...base, calls: Array.from({ length: 3 }, (_, i) => allowed(i)) }).view); + const many = JSON.stringify(compactRunResult({ ...base, calls: Array.from({ length: 3_000 }, (_, i) => allowed(i)) }).view); + expect(many.length).toBeLessThan(few.length + 10); + const denied = Array.from({ length: FAILED_CALLS_SHOWN + 7 }, (_, i): CallLogEntry => ({ ...allowed(i, 'bash'), decision: 'denied', reason: 'no' })); + const shown = (compactRunResult({ ...base, calls: denied }).view['calls'] as { denied: unknown[] }).denied; + expect(shown).toHaveLength(FAILED_CALLS_SHOWN + 1); + expect(shown.at(-1)).toBe('…[7 more]'); + }); + + it('leaves out empty fields and keeps the result, error, logs, warnings and rollback report', () => { + expect(Object.keys(compactRunResult({ ...base, result: 1 }).view).sort()).toEqual(['calls', 'ok', 'result']); + const rolledBack = { restored: ['a.txt'], skipped: [] }; + const failed: RunResult = { ...base, ok: false, error: { kind: 'denied', name: 'PermissionDenied', message: 'm' }, logs: ['l'], warnings: ['w'], rolledBack }; + expect(compactRunResult(failed).view).toEqual({ ok: false, result: null, error: failed.error, logs: ['l'], calls: { total: 0, byTool: {} }, warnings: ['w'], rolledBack }); + }); + + it('returns a small diff whole and cuts a large one at a line end', () => { + const small = 'x'.repeat(DIFF_INLINE_CHARS - 1) + '\n'; + expect(compactRunResult({ ...base, diff: small })).toMatchObject({ diffClipped: false, view: { diff: small } }); + const line = '+0123456789\n'; + const large = line.repeat(Math.ceil((DIFF_INLINE_CHARS + 1) / line.length)); + const { view, diffClipped } = compactRunResult({ ...base, diff: large }); + const shown = String(view['diff']); + expect(diffClipped).toBe(true); + const kept = shown.slice(0, shown.indexOf('…[')); + expect(kept.length).toBeLessThanOrEqual(DIFF_SAMPLE_CHARS); + expect(kept.endsWith(line)).toBe(true); + expect(large.startsWith(kept)).toBe(true); + expect(shown).toContain(`…[${large.length - kept.length} more chars; overflowPath has the whole result]`); + }); + + it('caps a long list of changed files', () => { + const changedFiles = Array.from({ length: CHANGED_FILES_SHOWN + 5 }, (_, i) => `f${i}.txt`); + const shown = compactRunResult({ ...base, changedFiles }).view['changedFiles'] as string[]; + expect(shown).toEqual([...changedFiles.slice(0, CHANGED_FILES_SHOWN), '…[5 more]']); + }); +}); + describe('formatRunResult', () => { + it('returns the whole result when verbose', async () => { + const result: RunResult = { ...base, calls: [allowed(1), allowed(2)], diff: 'd'.repeat(DIFF_INLINE_CHARS + 1) }; + const out = await formatRunResult(result, { stateDir: await tmp(), verbose: true }); + expect(JSON.parse(out.content[0]?.text ?? '')).toEqual(result); + }); + + it('saves the whole result when the compact view cut the diff, and points to the file', async () => { + const stateDir = await tmp(); + const result: RunResult = { ...base, result: 'done', calls: [allowed(1, 'write')], changedFiles: ['a.txt'], diff: '+line\n'.repeat(2_000) }; + const out = await formatRunResult(result, { stateDir }); + const shown = JSON.parse(out.content[0]?.text ?? '') as { diff: string; overflowPath: string; truncated?: boolean }; + expect(shown.truncated).toBeUndefined(); + expect(shown.diff.length).toBeLessThan(DIFF_SAMPLE_CHARS + 90); + expect(shown.diff).toContain('overflowPath'); + expect(JSON.parse(await readFile(shown.overflowPath, 'utf8'))).toEqual(result); + }); + + it('returns compact JSON and isError', async () => { const ok = await formatRunResult({ ...base, result: { a: 1 } }, { stateDir: await tmp() }); expect(ok.isError).toBe(false); diff --git a/src/core/output.ts b/src/core/output.ts index cc8a69d..ab31f33 100644 --- a/src/core/output.ts +++ b/src/core/output.ts @@ -3,7 +3,7 @@ import { writeFile } from 'node:fs/promises'; import path from 'node:path'; import { errorMessage } from './errors.js'; import { ensureStateDir } from './state-dir.js'; -import type { RunResult } from './types.js'; +import type { CallLogEntry, RunResult } from './types.js'; /** Largest text of a successful result. */ export const SUCCESS_CAP_CHARS = 30_000; @@ -16,9 +16,20 @@ export interface McpToolResponse { isError: boolean; } +/** A combined diff up to this size is returned whole. */ +export const DIFF_INLINE_CHARS = 1_500; +/** How much of a larger diff is returned; the whole result goes to a file. */ +export const DIFF_SAMPLE_CHARS = 600; +/** Changed files listed before the rest is counted. */ +export const CHANGED_FILES_SHOWN = 10; +/** Denied or failed calls listed in full before the rest is counted. */ +export const FAILED_CALLS_SHOWN = 20; + export interface FormatOptions { /** Directory for overflow files. Created 0700 when needed. */ readonly stateDir: string; + /** Return every call and the whole diff instead of the compact view. */ + readonly verbose?: boolean; readonly successCap?: number; readonly errorCap?: number; } @@ -102,24 +113,78 @@ async function writeOverflow(stateDir: string, text: string): Promise { return file; } +function clipList(items: readonly T[], shown: number): (T | string)[] { + return items.length <= shown ? [...items] : [...items.slice(0, shown), `…[${items.length - shown} more]`]; +} + +/** The call log as counts; only calls that were denied or failed keep their entry (without the duration). */ +export function summarizeCalls(calls: readonly CallLogEntry[]): Record { + const byTool: Record = {}; + for (const c of calls) byTool[c.tool] = (byTool[c.tool] ?? 0) + 1; + const failed = (decision: CallLogEntry['decision']): unknown[] => + clipList( + calls.filter((c) => c.decision === decision).map(({ id, tool, summary, reason }) => ({ id, tool, summary, ...(reason === undefined ? {} : { reason }) })), + FAILED_CALLS_SHOWN, + ); + const denied = failed('denied'); + const errors = failed('error'); + return { total: calls.length, byTool, ...(denied.length > 0 ? { denied } : {}), ...(errors.length > 0 ? { errors } : {}) }; +} + +/** + * The default view of a `RunResult`: what the model needs to go on, without + * the parts that grow with the number of calls. The call log becomes counts + * plus the denied and failed calls, a large diff is cut to its first lines + * (`diffClipped`), a long list of changed files is cut, empty fields are left out. + */ +export function compactRunResult(result: RunResult): { readonly view: Record; readonly diffClipped: boolean } { + const { logs, calls, changedFiles, diff, warnings, ...rest } = result; + const diffClipped = diff.length > DIFF_INLINE_CHARS; + let shownDiff = diff; + if (diffClipped) { + const head = diff.slice(0, DIFF_SAMPLE_CHARS); + const lineEnd = head.lastIndexOf('\n'); + shownDiff = `${lineEnd > 0 ? head.slice(0, lineEnd + 1) : head}…[${diff.length - (lineEnd > 0 ? lineEnd + 1 : head.length)} more chars; overflowPath has the whole result]`; + } + const view = { + ...rest, + ...(logs.length > 0 ? { logs } : {}), + calls: summarizeCalls(calls), + ...(changedFiles.length > 0 ? { changedFiles: clipList(changedFiles, CHANGED_FILES_SHOWN) } : {}), + ...(shownDiff !== '' ? { diff: shownDiff } : {}), + ...(warnings.length > 0 ? { warnings } : {}), + }; + return { view, diffClipped }; +} + /** - * Formats a `RunResult` as an MCP tool response: compact JSON text, `isError` - * when the run failed. Results above the cap are written whole to an - * overflow file (mode 0600) and replaced by a structurally truncated preview - * carrying `overflowPath`. + * Formats a `RunResult` as an MCP tool response: JSON text, `isError` when + * the run failed. The text is the compact view (`compactRunResult`) unless + * `verbose`. When the view cut the diff, or the text is above the cap, the + * whole result is written to an overflow file (mode 0600) and the response + * carries `overflowPath`; above the cap the text is a structurally truncated + * preview. */ export async function formatRunResult(result: RunResult, opts: FormatOptions): Promise { const isError = !result.ok; const cap = isError ? (opts.errorCap ?? ERROR_CAP_CHARS) : (opts.successCap ?? SUCCESS_CAP_CHARS); - const full = safeStringify(result); - if (full.length <= cap) return { content: [{ type: 'text', text: full }], isError }; + const compact = opts.verbose === true ? undefined : compactRunResult(result); + const shown: unknown = compact ? compact.view : result; + const text = safeStringify(shown); + const fits = text.length <= cap; + if (fits && compact?.diffClipped !== true) return { content: [{ type: 'text', text }], isError }; + const full = safeStringify(result); let extra: Record; try { const overflowPath = await writeOverflow(opts.stateDir, full); - extra = { overflowPath, note: `Result was ${full.length} chars; the full JSON is in the file at overflowPath (open it with the host's file reading tool).` }; + extra = fits + ? { overflowPath } + : { overflowPath, note: `Result was ${full.length} chars; the full JSON is in the file at overflowPath (open it with the host's file reading tool).` }; } catch (err) { - extra = { note: `Result was ${full.length} chars and could not be saved: ${errorMessage(err)}` }; + extra = { note: `${fits ? 'The diff is cut' : `Result was ${full.length} chars`} and the whole result could not be saved: ${errorMessage(err)}` }; } - return { content: [{ type: 'text', text: truncateStructurally(result, cap, extra) }], isError }; + const noted = fits ? safeStringify({ ...compact?.view, ...extra }) : undefined; + if (noted !== undefined && noted.length <= cap) return { content: [{ type: 'text', text: noted }], isError }; + return { content: [{ type: 'text', text: truncateStructurally(shown, cap, extra) }], isError }; } diff --git a/src/core/schemas.ts b/src/core/schemas.ts index 248d5cf..cf2728d 100644 --- a/src/core/schemas.ts +++ b/src/core/schemas.ts @@ -144,6 +144,7 @@ export const RunArgsSchema = z.object({ code: z.string().min(1, 'must not be empty').max(MAX_CODE_CHARS), transaction: z.boolean().optional(), timeoutMs: z.number().int().min(1).optional(), + verbose: z.boolean().optional(), }); export type RunArgs = z.infer; @@ -161,6 +162,10 @@ export const RUN_INPUT_JSON_SCHEMA: { description: 'Body of an async JavaScript function. Use await with the bindings bash, read, write, edit, grep, glob; the return value is the result.', }, + verbose: { + type: 'boolean', + description: 'Return the log of every call and the whole diff instead of the compact summary.', + }, transaction: { type: 'boolean', description: 'Roll back file writes and edits if the script fails, times out or any call is denied. bash effects are never rolled back.', diff --git a/src/core/types.ts b/src/core/types.ts index 0eb823f..4dfb1a0 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -134,9 +134,9 @@ export interface BashResult { /** Result of `read`. */ export interface ReadResult { - /** Absolute real path that was read. */ + /** Real path that was read; the script sees it relative to the session cwd when inside it. */ readonly path: string; - /** The returned lines, joined with `\n`. */ + /** Exact text of the returned lines: each keeps its newline, except a last line the file leaves unterminated. */ readonly content: string; /** 1-based line number of the first returned line. */ readonly startLine: number; @@ -148,7 +148,7 @@ export interface ReadResult { /** Result of `write`. */ export interface WriteResult { - /** Absolute real path that was written. */ + /** Real path that was written; the script sees it relative to the session cwd when inside it. */ readonly path: string; /** True when the file did not exist before. */ readonly created: boolean; @@ -168,7 +168,7 @@ export type MatchStrategy = 'exact' | 'line-endings' | 'line-numbers' | 'trailin /** Result of `edit`. */ export interface EditResult { - /** Absolute real path that was edited. */ + /** Real path that was edited; the script sees it relative to the session cwd when inside it. */ readonly path: string; /** Number of occurrences replaced. */ readonly replacements: number; @@ -179,7 +179,7 @@ export interface EditResult { /** One `grep` match. */ export interface GrepMatch { - /** Absolute real path of the file. */ + /** Real path of the file; the script sees it relative to the session cwd when inside it. */ readonly file: string; /** 1-based line number. */ readonly line: number; @@ -198,7 +198,7 @@ export interface GrepResult { /** Result of `glob`. */ export interface GlobResult { - /** Absolute real paths. */ + /** Real paths; the script sees them relative to the session cwd when inside it. */ readonly files: readonly string[]; /** True when more files existed than were returned. */ readonly truncated: boolean; diff --git a/src/hosts/claude/adapter.test.ts b/src/hosts/claude/adapter.test.ts index 2d03783..cbae8a6 100644 --- a/src/hosts/claude/adapter.test.ts +++ b/src/hosts/claude/adapter.test.ts @@ -7,7 +7,7 @@ import { afterAll, describe, expect, it } from 'vitest'; import { Dispatcher } from '../../core/dispatcher.js'; import type { Decision, PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; import { MemoryToolRuntime, makeContext } from '../../testing/index.js'; -import { ClaudeHostAdapter, type ClaudePolicy } from './adapter.js'; +import { ClaudeHostAdapter, type ClaudePolicy, RUNTIME_FILES_HINT } from './adapter.js'; const posix = process.platform !== 'win32'; const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures'); @@ -175,6 +175,18 @@ describe('Bash rules', () => { expect(check(s, bash('npm run build > out.log', s.project))).toBe('allow'); }); + it('says why an allow-all Bash rule did not approve a command that names files at run time', async () => { + const s = await setup({ user: { permissions: { allow: ['Bash'] } } }); + expect(check(s, bash('wc -l src/a.ts', s.project))).toBe('allow'); + for (const command of ['wc -l src/*', 'head -c 9 src/$(ls src | head -1)']) { + const decision = s.adapter.checkStatic(bash(command, s.project), s.ctx, s.policy); + expect(decision).toMatchObject({ kind: 'ask', reason: `Bash needs approval in default mode: ${RUNTIME_FILES_HINT}` }); + } + // Without files named at run time the reason stays as it was. + const none = await setup({}); + expect(none.adapter.checkStatic(bash('wc -l src/a.ts', none.project), none.ctx, none.policy)).toEqual({ kind: 'ask', reason: 'Bash needs approval in default mode' }); + }); + it('checks redirect and file-reader targets against Read/Edit rules', async () => { const s = await setup({ user: { permissions: { deny: ['Read(./.env)', 'Edit(./locked/**)'] } }, mode: 'bypassPermissions' }); expect(check(s, bash('cat .env', s.project))).toBe('deny'); diff --git a/src/hosts/claude/adapter.ts b/src/hosts/claude/adapter.ts index 36c1dfd..9ca9a46 100644 --- a/src/hosts/claude/adapter.ts +++ b/src/hosts/claude/adapter.ts @@ -241,6 +241,10 @@ function allowedByRule(view: CallView, rules: readonly Rule[], policy: ClaudePol }); } +/** Why no allow rule approved a bash command that names files by glob, variable or substitution. */ +export const RUNTIME_FILES_HINT = + 'the command names files only known at run time (a glob, variable or substitution), which no allow rule covers; name each file literally, or find and read files with glob(), read() and grep()'; + /** What the permission mode does with a call that no rule decided. */ function modeDecision(view: CallView, policy: ClaudePolicy): Decision { const { prepared } = view; @@ -601,7 +605,12 @@ export class ClaudeHostAdapter implements HostAdapter { const critical = criticalRemoval(view, policy); if (critical !== undefined) return askOrDeny(`${critical}; no rule or mode approves it`); if (allowedByRule(view, policy.rules.allow, policy)) return { kind: 'allow' }; - return modeDecision(view, policy); + const decision = modeDecision(view, policy); + // Same decision, with the cause the script can act on: allow rules never cover files named at run time. + if (decision.kind !== 'allow' && view.bashFiles.some((f) => f.path === undefined)) { + return { ...decision, reason: `${decision.reason}: ${RUNTIME_FILES_HINT}` }; + } + return decision; } /** diff --git a/src/hosts/claude/regressions.test.ts b/src/hosts/claude/regressions.test.ts index d642307..af35f87 100644 --- a/src/hosts/claude/regressions.test.ts +++ b/src/hosts/claude/regressions.test.ts @@ -158,12 +158,13 @@ describe('recursive grep and glob', () => { const grep = await dispatcher.dispatch('grep', { pattern: 'SECRET', path: '.' }); const glob = await dispatcher.dispatch('glob', { pattern: '**/*', path: '.' }); if (!grep.ok || !glob.ok) throw new Error('search failed'); - const keep = (file: string): boolean => !s.policy.payload.isReadDenied(file); + // The script sees paths relative to the session cwd. + const keep = (file: string): boolean => !s.policy.payload.isReadDenied(path.resolve(s.project, file)); const grepFiles = ('matches' in grep.value ? (grep.value as GrepResult).matches : []).map((m) => m.file); const globFiles = 'files' in glob.value ? (glob.value as GlobResult).files : []; - expect(grepFiles).toContain(path.join(s.project, '.env')); // unfiltered, the secret leaks - expect(grepFiles.filter(keep)).toEqual([path.join(s.project, 'a.txt')]); - expect(globFiles.filter(keep)).not.toContain(path.join(s.project, '.env')); + expect(grepFiles).toContain('.env'); // unfiltered, the secret leaks + expect(grepFiles.filter(keep)).toEqual(['a.txt']); + expect(globFiles.filter(keep)).not.toContain('.env'); expect(s.policy.payload.isReadDenied(path.join(s.project, 'sub', '.env'))).toBe(false); }); }); diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 36a0d5a..515a066 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -67,7 +67,7 @@ function textOf(result: unknown): string { } describe('MCP server', () => { - it('lists the run tool with annotations, _meta and instructions', async () => { + it('lists the run tool with annotations and _meta, and documents the bindings in its description (no server instructions)', async () => { const { client } = await connect(); const { tools } = await client.listTools(); expect(tools).toHaveLength(1); @@ -77,7 +77,10 @@ describe('MCP server', () => { _meta: { 'anthropic/alwaysLoad': true }, inputSchema: { type: 'object', required: ['code'] }, }); - expect(client.getInstructions()).toContain('bash({command'); + expect(tools[0]?.description).toContain('bash({command'); + expect(tools[0]?.inputSchema.properties).toHaveProperty('verbose'); + // Claude Code writes server instructions to the prompt cache again in every session. + expect(client.getInstructions()).toBeUndefined(); }); it('runs a script end to end: FakeSandbox → Dispatcher → StaticHostAdapter → MemoryToolRuntime, with one denied call', async () => { @@ -87,7 +90,7 @@ describe('MCP server', () => { { tool: 'bash', args: { command: 'rm -rf /' } }, { tool: 'read', args: { path: 'notes.txt' } }, ]); - const result = await client.callTool({ name: 'run', arguments: { code } }); + const result = await client.callTool({ name: 'run', arguments: { code, verbose: true } }); expect(result.isError).toBe(false); const body = JSON.parse(textOf(result)) as { ok: boolean; @@ -112,6 +115,23 @@ describe('MCP server', () => { expect(tools.commits.some((c) => c.tool === 'bash')).toBe(false); }); + it('returns the compact view by default: call counts, the denied call in full, no empty fields', async () => { + const { client } = await connect(); + const code = JSON.stringify([ + { tool: 'read', args: { path: 'notes.txt' } }, + { tool: 'bash', args: { command: 'rm -rf /' } }, + { tool: 'read', args: { path: 'notes.txt' } }, + ]); + const result = await client.callTool({ name: 'run', arguments: { code } }); + const body = JSON.parse(textOf(result)) as Record; + expect(body['calls']).toEqual({ + total: 3, + byTool: { read: 2, bash: 1 }, + denied: [{ id: 'c2', tool: 'bash', summary: 'bash rm -rf /', reason: 'rule: rm is not allowed' }], + }); + expect(Object.keys(body).sort()).toEqual(['calls', 'ok', 'result']); + }); + it('rolls back a transaction when a call is denied and reports isError', async () => { const { client, tools } = await connect(); const code = JSON.stringify([ diff --git a/src/server/mcp.ts b/src/server/mcp.ts index c957452..e3fca87 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { CallToolRequestSchema, ListToolsRequestSchema, type Tool } from '@modelcontextprotocol/sdk/types.js'; import { errorMessage } from '../core/errors.js'; -import { formatRunResult, type McpToolResponse } from '../core/output.js'; +import { DIFF_INLINE_CHARS, formatRunResult, type McpToolResponse } from '../core/output.js'; import { runScript, toRunRequest } from '../core/run.js'; import { RUN_INPUT_JSON_SCHEMA, parseRunArgs } from '../core/schemas.js'; import { stateDirPath } from '../core/state-dir.js'; @@ -15,8 +15,15 @@ import { createRuntime, type Runtime, type RuntimeFactory } from './runtime.js'; export const SERVER_NAME = 'agent-code-mode'; -export const SERVER_INSTRUCTIONS = `Prefer the run tool when a step needs several tool calls: batch many reads, searches, edits and commands into one script instead of calling tools one by one. -The script is the body of an async JavaScript function; return a value to get it back. Globals (all async, all subject to your normal permission rules and hooks): +/** + * Everything the model needs to write a script. It lives in the tool + * description, not in the server `instructions`: Claude Code puts server + * instructions in the per-session environment message, where they are written + * to the prompt cache again in every session, while tool definitions sit in + * the prefix that sessions share. + */ +export const RUN_DESCRIPTION = `Run a JavaScript script that calls the host's tools. Prefer it when a step needs several tool calls: batch many reads, searches, edits and commands into one script instead of calling tools one by one. A script can look, decide and change things in the same call, so finish the step in one script when you can (each extra call is another model round trip), and return only what you need: filter and aggregate in the script. +The script is the body of an async function; return a value to get it back. Globals (all async, each call subject to the host permission rules and hooks): bash({command, cwd?, timeoutMs?}) -> {exitCode, signal, stdout, stderr, truncated, timedOut} read({path, offset?, limit?}) -> {path, content, startLine, totalLines, truncated} write({path, content}) -> {path, created, diff} @@ -24,13 +31,16 @@ The script is the body of an async JavaScript function; return a value to get it grep({pattern, path?, glob?, ignoreCase?, maxResults?}) -> {matches: [{file, line, text}], truncated, filtered} glob({pattern, path?, maxResults?}) -> {files, truncated, filtered} console.log/info/warn/error -A denied call rejects with an Error named PermissionDenied; other failures reject with ToolError. Pass transaction: true to roll back file changes if the script fails or a call is denied (bash effects are never rolled back).`; +read's content is the exact text of the file, final newline included. Paths in results are relative to the working directory. +A denied call rejects with an Error named PermissionDenied; other failures reject with ToolError. +In bash, name every file literally: a glob (src/*), a variable or $(...) as a file argument gets the whole command denied when nobody can approve it. Find, read and loop over files with glob, read, grep and JavaScript instead. +Pass transaction: true to roll back file changes if the script fails or a call is denied (bash effects are never rolled back). +Returns JSON: {ok, result | error, logs, calls: {total, byTool, denied, errors}, changedFiles, diff, warnings}; empty fields are left out, and a long list of changed files and a diff above ${DIFF_INLINE_CHARS} chars are cut (verbose: true returns every call and the whole diff).`; export const RUN_TOOL: Tool = { name: 'run', title: 'Run a code-mode script', - description: - 'Run a JavaScript script that calls bash, read, write, edit, grep and glob. Every call goes through the host permission rules and hooks. Returns the script result, logs, a call log, changed files and the diff.', + description: RUN_DESCRIPTION, inputSchema: RUN_INPUT_JSON_SCHEMA, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, _meta: { 'anthropic/alwaysLoad': true }, @@ -117,7 +127,7 @@ export function createMcpServer(opts: McpServerOptions): Server { return runtime; }; - const server = new Server({ name: SERVER_NAME, version: opts.version }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }); + const server = new Server({ name: SERVER_NAME, version: opts.version }, { capabilities: { tools: {} } }); const listRoots = async (): Promise => { if (!server.getClientCapabilities()?.roots) return []; @@ -132,10 +142,12 @@ export function createMcpServer(opts: McpServerOptions): Server { server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [RUN_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { - const respond = (result: RunResult): Promise => formatRunResult(result, { stateDir }); + let verbose = false; + const respond = (result: RunResult): Promise => formatRunResult(result, { stateDir, verbose }); if (request.params.name !== RUN_TOOL.name) return respond(errorResult(`unknown tool ${JSON.stringify(request.params.name)}`)); const args = parseRunArgs(request.params.arguments); if (!args.ok) return respond(errorResult(`invalid run arguments: ${args.message}`)); + verbose = args.value.verbose ?? false; try { const meta: unknown = request.params._meta; const host = detectHost({ flag: opts.host, env, meta }); diff --git a/src/server/runtime.test.ts b/src/server/runtime.test.ts index 43a3704..9677521 100644 --- a/src/server/runtime.test.ts +++ b/src/server/runtime.test.ts @@ -54,7 +54,7 @@ describe('generic host policy', () => { }, ); expect(result.ok).toBe(true); - expect(result.result).toMatchObject({ r: 'hello', b: 'PermissionDenied' }); + expect(result.result).toMatchObject({ r: 'hello\n', b: 'PermissionDenied' }); expect(JSON.stringify(result.result)).toContain(GENERIC_ASK_REASON); expect(result.calls.map((c) => c.decision)).toEqual(['allowed', 'denied', 'denied']); }); diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index a9a1062..6691bdd 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -286,7 +286,8 @@ export class MemoryToolRuntime implements ToolRuntime { const lines = content.split('\n'); const window = lines.slice(offset - 1, offset - 1 + limit); this.commits.push({ id: prepared.id, tool: 'read', target: absPath }); - return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated: offset - 1 + limit < lines.length }; + const more = offset - 1 + window.length < lines.length; + return { path: absPath, content: `${window.join('\n')}${more ? '\n' : ''}`, startLine: offset, totalLines: lines.length, truncated: offset - 1 + limit < lines.length }; } case 'grep': { const { absRoot, pattern, ignoreCase, maxResults, glob } = prepared.effect; diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts index 318be45..2895cab 100644 --- a/src/tools/runtime.test.ts +++ b/src/tools/runtime.test.ts @@ -221,7 +221,7 @@ describe('protected paths', () => { 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('content' in read && read.content).toBe('[core]\n'); expect(readFileSync(path.join(ws, '.git', 'config'), 'utf8')).toBe('[core]\n'); }); @@ -312,9 +312,20 @@ 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 }); + expect(all).toEqual({ path: path.join(ws, 'r.txt'), content: 'l1\nl2\nl3\nl4\n', 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 }); + expect(part).toEqual({ path: path.join(ws, 'r.txt'), content: 'l2\nl3\n', startLine: 2, totalLines: 4, truncated: true }); + }); + + it('returns the exact text, so writing the content back keeps the file byte for byte', async () => { + for (const text of ['a\nb\n', 'a\nb', 'a\n\n', '\n', '']) { + writeFileSync(path.join(ws, 'exact.txt'), text); + const all = await run('read', { path: 'exact.txt' }); + expect('content' in all && all.content).toBe(text); + const first = await run('read', { path: 'exact.txt', limit: 1 }); + const rest = await run('read', { path: 'exact.txt', offset: 2 }); + expect(('content' in first ? first.content : '') + ('content' in rest ? rest.content : '')).toBe(text); + } }); it('caps the bytes returned and refuses binary files', async () => { diff --git a/src/tools/runtime.ts b/src/tools/runtime.ts index 4775607..807abff 100644 --- a/src/tools/runtime.ts +++ b/src/tools/runtime.ts @@ -382,7 +382,10 @@ export class NodeToolRuntime implements ToolRuntime { bytes += size; } if (offset - 1 + window.length < lines.length) truncated = true; - return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated }; + // Exact text of the window: every line keeps its newline, except a last line the file leaves unterminated. + const unterminated = offset - 1 + window.length >= lines.length && !text.endsWith('\n'); + const content = window.length === 0 ? '' : `${window.join('\n')}${unterminated ? '' : '\n'}`; + return { path: absPath, content, startLine: offset, totalLines: lines.length, truncated }; } async #commitWrite( diff --git a/test/attack/harness.ts b/test/attack/harness.ts index a47f52a..b66e4b8 100644 --- a/test/attack/harness.ts +++ b/test/attack/harness.ts @@ -105,7 +105,7 @@ export function snapshot(dir: string): Record { } export interface Server { - /** Calls `run` and returns the parsed result. */ + /** Calls `run` with `verbose: true` and returns the parsed result (full call log and diff). */ run(code: string, opts?: { transaction?: boolean; timeoutMs?: number; signal?: AbortSignal }): Promise; /** Calls `run` and returns the raw text of the response. */ runText(code: string): Promise; @@ -134,7 +134,8 @@ async function serve(runtime: Runtime, lab: Lab, meta: Record, return { async run(code, opts = {}) { const text = await call( - { code, ...(opts.transaction ? { transaction: true } : {}), ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}) }, + // verbose: the attack tests assert on the entry of every call, which the compact view reduces to counts. + { code, verbose: true, ...(opts.transaction ? { transaction: true } : {}), ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}) }, opts.signal, ); return RunOutputSchema.parse(JSON.parse(text)); diff --git a/test/attack/hooks.test.ts b/test/attack/hooks.test.ts index 795ed28..c2eeaff 100644 --- a/test/attack/hooks.test.ts +++ b/test/attack/hooks.test.ts @@ -133,7 +133,7 @@ describe.runIf(posix)('the example deny-rm hook blocks a call made inside run', const back = (await read({ path: 'a.txt' })).content; const rm = await bash({ command: 'rm a.txt' }).then(() => 'ran', (e) => e.name + ': ' + e.message); return { back, rm };`); - expect(out.result).toMatchObject({ back: 'hello', rm: expect.stringMatching(/^PermissionDenied: .*rm is blocked by the example hook/) }); + expect(out.result).toMatchObject({ back: 'hello\n', rm: expect.stringMatching(/^PermissionDenied: .*rm is blocked by the example hook/) }); expect(existsSync(path.join(lab.ws, 'a.txt'))).toBe(true); }); }); diff --git a/test/attack/paths.test.ts b/test/attack/paths.test.ts index 1e40cc3..5f71b9a 100644 --- a/test/attack/paths.test.ts +++ b/test/attack/paths.test.ts @@ -128,7 +128,7 @@ describe('grep and glob never return a file the Read rules deny', () => { expect(out.ok).toBe(true); const text = JSON.stringify(out.result); expect(text).not.toContain('secret'); - expect(out.result).toMatchObject({ matches: [{ file: path.join(lab.ws, 'src', 'app.ts') }], filtered: 2 }); + expect(out.result).toMatchObject({ matches: [{ file: 'src/app.ts' }], filtered: 2 }); }); it('glob over the root drops the denied entries', async () => { From 3f0c1db7f342983a1858c1419d990d670530dd09 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:24:54 -0300 Subject: [PATCH 02/13] Fix compact run results; add readOverflow, grep rows, plain-text results, output cap Denied calls, errors and changed files are always listed whole. A large diff becomes a diffStat of at most 10 files; anything cut from the response (diff or output above the 10k-token cap) is kept in memory for this server session and read back with readOverflow(id), so no state-dir path leaks and nothing accumulates on disk. grep() returns {columns, rows}; a long string result comes as a second plain-text block. Result paths use the canonical cwd, and names such as ..env stay relative. The tool description keeps only the binding signatures. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +- bench/lib/run-result.ts | 44 ++- bench/test/run-result.test.ts | 45 +++ src/core/contracts.test.ts | 15 +- src/core/dispatcher.test.ts | 50 ++- src/core/dispatcher.ts | 21 +- src/core/output.test.ts | 325 ++++++++++++------- src/core/output.ts | 396 ++++++++++++++++-------- src/core/overflow.test.ts | 89 ++++++ src/core/overflow.ts | 134 ++++++++ src/core/run.ts | 13 +- src/core/schemas.ts | 4 +- src/core/types.ts | 27 +- src/hosts/claude/regressions.test.ts | 4 +- src/sandbox/child.ts | 3 + src/sandbox/quickjs-sandbox.test.ts | 6 +- src/server/mcp.test.ts | 11 +- src/server/mcp.ts | 50 +-- src/testing/memory-tool-runtime.test.ts | 44 +++ src/testing/memory-tool-runtime.ts | 9 +- test/attack/harness.ts | 19 +- test/attack/paths.test.ts | 2 +- test/attack/run-limits.test.ts | 47 +++ 23 files changed, 1040 insertions(+), 327 deletions(-) create mode 100644 bench/test/run-result.test.ts create mode 100644 src/core/overflow.test.ts create mode 100644 src/core/overflow.ts create mode 100644 src/testing/memory-tool-runtime.test.ts diff --git a/README.md b/README.md index d563902..522b7eb 100644 --- a/README.md +++ b/README.md @@ -58,11 +58,11 @@ The script is the body of an async function. All bindings are async globals; `re ```js const hits = await grep({ pattern: 'TODO', glob: '*.ts' }); -for (const file of [...new Set(hits.matches.map((m) => m.file))]) { +for (const file of [...new Set(hits.rows.map(([file]) => file))]) { await edit({ path: file, oldString: 'TODO', newString: 'DONE', replaceAll: true }); } const test = await bash({ command: 'npm test --silent' }); -return { files: hits.matches.length, exitCode: test.exitCode }; +return { matches: hits.count, exitCode: test.exitCode }; ``` | Binding | Returns | @@ -71,10 +71,11 @@ return { files: hits.matches.length, exitCode: test.exitCode }; | `read({path, offset?, limit?})` | `{path, content, startLine, totalLines, truncated}` | | `write({path, content})` | `{path, created, diff}` | | `edit({path, oldString, newString, replaceAll?})` | `{path, replacements, matchStrategy, diff}` | -| `grep({pattern, path?, glob?, ignoreCase?, maxResults?})` | `{matches: [{file, line, text}], truncated, filtered}` | +| `grep({pattern, path?, glob?, ignoreCase?, maxResults?})` | `{columns: ['file', 'line', 'text'], rows: [[file, line, text]], count, truncated, filtered}` | | `glob({pattern, path?, maxResults?})` | `{files, truncated, filtered}` | +| `readOverflow(id, offset?, limit?)` | `{text, offset, totalChars, truncated}`: a slice of a result a response cut | -`console.log/info/warn/error` go to `logs`. A denied call rejects with an `Error` named `PermissionDenied` (with `source` and `reason`); other failures reject with `ToolError` (with `code`). `read` returns the exact text of the lines, final newline included, and paths in results are relative to the working directory when inside it. `run` takes `{code, transaction?, timeoutMs?, verbose?}`. With `transaction: true`, file changes are rolled back if the script throws, times out, is cancelled or any call is denied; if the server process dies mid-run, the next start restores them from its journal (inside the roots of that run only). The result holds the return value, logs, the number of calls by tool with every denied or failed call, the changed files and a combined diff; a diff above 1,500 characters is cut and the whole result saved to a file. `verbose: true` returns the log of every call and the whole diff. +`console.log/info/warn/error` go to `logs`. A denied call rejects with an `Error` named `PermissionDenied` (with `source` and `reason`); other failures reject with `ToolError` (with `code`). `read` returns the exact text of the lines, final newline included, and paths in results are relative to the working directory when inside it. `run` takes `{code, transaction?, timeoutMs?, verbose?}`. With `transaction: true`, file changes are rolled back if the script throws, times out, is cancelled or any call is denied; if the server process dies mid-run, the next start restores them from its journal (inside the roots of that run only). The response is a JSON block: `{ok, result | error, logs, calls: {total, byTool, denied, errors}, changedFiles, diff | diffStat, warnings}`, with empty fields left out. Every denied and failed call is listed with its reason, and every changed file is listed. A multi-line string result longer than 200 characters comes as plain text in a second block instead of an escaped JSON string. A diff above 1,500 characters becomes `diffStat` (lines added and removed for up to 10 files, plus the totals). A response stays under about 10,000 tokens (40,000 characters; 9,500 for an error): above that, the result and the logs keep their start and end, long lists keep their first entries, each cut is marked and `truncated: true` is set. Whenever something is left out, the whole result is kept in the server's memory for 30 minutes and the response carries `overflow: {id, chars}`; a later script reads it with `readOverflow(id)`. The id is random, works only in the same server process and nothing is written to disk. `verbose: true` returns the log of every call and the whole diff. Edits that do not match exactly fall back through tolerant rungs (line endings, copied line numbers, trailing whitespace, indentation, typographic punctuation). `matchStrategy` says which rung matched. diff --git a/bench/lib/run-result.ts b/bench/lib/run-result.ts index 4de0d3f..a0374b6 100644 --- a/bench/lib/run-result.ts +++ b/bench/lib/run-result.ts @@ -3,7 +3,8 @@ import { z } from 'zod'; /** * The agent-code-mode `run` response as the server returns it (only the fields the bench reads). * `calls` is the full log (verbose, and every result before the compact view existed) or the - * compact summary: counts by tool plus the denied calls. + * compact summary: counts by tool plus the denied calls. A long multi-line string result comes in + * a second content block after the JSON one; hosts hand the blocks over joined. */ const Call = z.object({ tool: z.string(), decision: z.string().optional(), summary: z.string().optional(), reason: z.string().optional() }).passthrough(); const RunResultText = z.object({ @@ -22,14 +23,45 @@ export interface RunInnerCalls { const denialLine = (c: z.infer): string => `${c.tool} ${c.summary ?? ''}: ${c.reason ?? 'denied'}`.slice(0, 500); -/** Inner calls of one `run` response text; null when the text is not a run result. */ -export function runInnerCalls(text: string): RunInnerCalls | null { - let json: unknown; +/** End index of the JSON object `text` starts with, or -1. */ +function leadingObjectEnd(text: string): number { + if (!text.startsWith('{')) return -1; + let depth = 0; + let inString = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (inString) { + if (ch === '\\') i++; + else if (ch === '"') inString = false; + } else if (ch === '"') inString = true; + else if (ch === '{' || ch === '[') depth++; + else if (ch === '}' || ch === ']') { + depth--; + if (depth === 0) return i + 1; + } + } + return -1; +} + +/** The JSON value of a response's first block: the whole text, or the object it starts with when a text block follows. */ +function firstBlockJson(text: string): unknown { try { - json = JSON.parse(text); + return JSON.parse(text); } catch { - return null; + const end = leadingObjectEnd(text); + if (end === -1) return undefined; + try { + return JSON.parse(text.slice(0, end)); + } catch { + return undefined; + } } +} + +/** Inner calls of one `run` response text (its content blocks joined); null when the text is not a run result. */ +export function runInnerCalls(text: string): RunInnerCalls | null { + const json = firstBlockJson(text); + if (json === undefined) return null; const parsed = RunResultText.safeParse(json); if (!parsed.success) return null; const calls = parsed.data.calls; diff --git a/bench/test/run-result.test.ts b/bench/test/run-result.test.ts new file mode 100644 index 0000000..79263e1 --- /dev/null +++ b/bench/test/run-result.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest'; +import { formatRunResult } from '../../src/core/output.ts'; +import { OverflowStore } from '../../src/core/overflow.ts'; +import type { CallLogEntry, RunResult } from '../../src/core/types.ts'; +import { runInnerCalls } from '../lib/run-result.ts'; + +const base: RunResult = { ok: true, result: null, logs: [], calls: [], changedFiles: [], diff: '', warnings: [] }; +const calls: CallLogEntry[] = [ + { id: 'c1', tool: 'read', summary: 'read a', decision: 'allowed', durationMs: 1 }, + { id: 'c2', tool: 'bash', summary: 'bash rm x', decision: 'denied', reason: 'rule: no rm', durationMs: 1 }, + { id: 'c3', tool: 'grep', summary: 'grep "{"', decision: 'allowed', durationMs: 1 }, +]; +const expected = { total: 3, byTool: { read: 1, bash: 1, grep: 1 }, denials: ['bash bash rm x: rule: no rm'] }; + +/** The response text as the hosts hand it to the bench: every content block, joined. */ +const joined = (result: RunResult, verbose = false): string => + formatRunResult(result, { overflow: new OverflowStore(), verbose }) + .content.map((c) => c.text) + .join(''); + +describe('runInnerCalls on the server response', () => { + it('reads a one-block response, compact and verbose', () => { + expect(runInnerCalls(joined({ ...base, result: { a: '}' }, calls }))).toEqual(expected); + expect(runInnerCalls(joined({ ...base, result: 1, calls }, true))).toEqual(expected); + }); + + it('reads the JSON block when a plain text result follows it', () => { + const text = Array.from({ length: 30 }, (_, i) => `"line" {${i}} \\ ]`).join('\n'); + const response = formatRunResult({ ...base, result: text, calls }); + expect(response.content).toHaveLength(2); + expect(runInnerCalls(joined({ ...base, result: text, calls }))).toEqual(expected); + }); + + it('reads a response cut at the cap', () => { + const result: RunResult = { ...base, result: '{"x":\n'.repeat(40_000), calls }; + expect(runInnerCalls(joined(result))).toEqual(expected); + }); + + it('is null for text that is not a run result', () => { + expect(runInnerCalls('not json')).toBeNull(); + expect(runInnerCalls('{"ok":true}')).toBeNull(); + expect(runInnerCalls('{"calls": {"total": 1, "byTool": {}} plus text')).toBeNull(); + expect(runInnerCalls('{"unclosed": "')).toBeNull(); + }); +}); diff --git a/src/core/contracts.test.ts b/src/core/contracts.test.ts index 02daf30..d5dbc41 100644 --- a/src/core/contracts.test.ts +++ b/src/core/contracts.test.ts @@ -7,7 +7,7 @@ import { makeContext } from '../testing/context.js'; import { StaticHostAdapter } from '../testing/static-host-adapter.js'; import { NodeToolRuntime } from '../tools/runtime.js'; import { Dispatcher } from './dispatcher.js'; -import type { CallReply, GlobResult, GrepResult, PolicySnapshot, PreparedCall, SessionContext, ToolCall } from './types.js'; +import type { CallReply, GlobResult, PolicySnapshot, ScriptGrepResult, PreparedCall, SessionContext, ToolCall } from './types.js'; const posix = process.platform !== 'win32'; @@ -115,8 +115,8 @@ describe('PolicySnapshot.readFilter and additionalRoots', () => { payload: null, }; const d = dispatcherFor(ctx, policy); - const grep = value(await d.dispatch('grep', { pattern: 'token' })); - expect(grep.matches.map((m) => m.file)).toEqual(['src/a.ts']); + const grep = value(await d.dispatch('grep', { pattern: 'token' })); + expect(grep.rows.map(([file]) => file)).toEqual(['src/a.ts']); expect(grep.filtered).toBe(2); const glob = value(await d.dispatch('glob', { pattern: '**/*' })); expect(glob.files).toEqual(['src/a.ts']); @@ -126,8 +126,9 @@ describe('PolicySnapshot.readFilter and additionalRoots', () => { it('reports filtered 0 without a filter', async () => { const { ctx } = workspace(); const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; - const grep = value(await dispatcherFor(ctx, policy).dispatch('grep', { pattern: 'token' })); - expect(grep.matches).toHaveLength(3); + const grep = value(await dispatcherFor(ctx, policy).dispatch('grep', { pattern: 'token' })); + expect(grep.rows).toHaveLength(3); + expect(grep.count).toBe(3); expect(grep.filtered).toBe(0); }); @@ -195,8 +196,8 @@ describe('Claude policy wiring', () => { expect(policy.readFilter?.(path.join(project, '.env'))).toBe(false); expect(policy.readFilter?.(path.join(project, 'private', 'p.txt'))).toBe(false); expect(policy.readFilter?.(path.join(project, 'src', 'ok.txt'))).toBe(true); - const grep = value(await d.dispatch('grep', { pattern: 'key' })); - expect(grep.matches.map((m) => m.file)).toEqual(['src/ok.txt']); + const grep = value(await d.dispatch('grep', { pattern: 'key' })); + expect(grep.rows.map(([file]) => file)).toEqual(['src/ok.txt']); expect(grep.filtered).toBe(2); }); diff --git a/src/core/dispatcher.test.ts b/src/core/dispatcher.test.ts index 985a84f..862f29c 100644 --- a/src/core/dispatcher.test.ts +++ b/src/core/dispatcher.test.ts @@ -1,8 +1,12 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { makeContext } from '../testing/context.js'; import { MemoryToolRuntime } from '../testing/memory-tool-runtime.js'; import { StaticHostAdapter, type StaticHostAdapterOptions } from '../testing/static-host-adapter.js'; -import { Dispatcher } from './dispatcher.js'; +import { NodeToolRuntime } from '../tools/runtime.js'; +import { Dispatcher, displayPath } from './dispatcher.js'; import type { CallReply, PolicyLoadError, PolicySnapshot, Transaction } from './types.js'; async function setup( @@ -352,3 +356,47 @@ describe('Dispatcher', () => { expect(dispatcher.warnings[0]).toContain('post failed'); }); }); + +describe('script-facing paths', () => { + it('D4: a name starting with .. inside the cwd stays relative; .. and outside paths stay absolute', () => { + expect(displayPath('/ws/..env', '/ws')).toBe('..env'); + expect(displayPath('/ws/..cache/a.ts', '/ws')).toBe('..cache/a.ts'); + expect(displayPath('/ws/src/a.ts', '/ws')).toBe('src/a.ts'); + expect(displayPath('/', '/ws')).toBe('/'); + expect(displayPath('/other/a.ts', '/ws')).toBe('/other/a.ts'); + expect(displayPath('/ws', '/ws')).toBe('/ws'); + }); + + it.runIf(process.platform !== 'win32')('D4: with the cwd reached through a symlink, results are relative to the real cwd', async () => { + const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-d4-'))); + try { + const real = path.join(base, 'real-ws'); + mkdirSync(path.join(real, 'src'), { recursive: true }); + writeFileSync(path.join(real, 'src', 'a.ts'), 'const X = 1;\n'); + writeFileSync(path.join(real, '..env'), 'X\n'); + const link = path.join(base, 'link-ws'); + symlinkSync(real, link); + const ctx = makeContext(link); + const adapter = new StaticHostAdapter({}); + const dispatcher = new Dispatcher({ adapter, tools: new NodeToolRuntime({ stateDir: path.join(base, 'state') }), ctx, policy: await adapter.loadPolicy(ctx) }); + const value = async (tool: string, args: unknown): Promise => { + const reply = await dispatcher.dispatch(tool, args); + if (!reply.ok) throw new Error(JSON.stringify(reply.error)); + return reply.value; + }; + expect(await value('read', { path: 'src/a.ts' })).toMatchObject({ path: 'src/a.ts' }); + expect(await value('glob', { pattern: '**/*' })).toMatchObject({ files: expect.arrayContaining(['src/a.ts', '..env']) }); + expect(await value('grep', { pattern: 'X' })).toEqual({ + columns: ['file', 'line', 'text'], + rows: expect.arrayContaining([['..env', 1, 'X'], ['src/a.ts', 1, 'const X = 1;']]), + count: 2, + truncated: false, + filtered: 0, + }); + expect(await value('edit', { path: 'src/a.ts', oldString: 'X = 1', newString: 'X = 2' })).toMatchObject({ path: 'src/a.ts' }); + expect(dispatcher.changedFiles).toEqual(['src/a.ts']); + } finally { + rmSync(base, { recursive: true, force: true }); + } + }); +}); diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts index ded4986..ddbe1ed 100644 --- a/src/core/dispatcher.ts +++ b/src/core/dispatcher.ts @@ -15,6 +15,7 @@ import type { PolicyLoadError, PolicySnapshot, PreparedCall, + ScriptValue, SessionContext, ToolCall, ToolResult, @@ -434,7 +435,7 @@ export class Dispatcher

{ } this.#calls[slot] = { id: prepared.id, tool: prepared.tool, summary, decision: 'allowed', durationMs: this.#elapsed(started) }; - return { ok: true, value: scriptResult(result, this.#opts.ctx.cwd) }; + return { ok: true, value: scriptResult(result, this.#canonicalCwd) }; } #toolFailure(err: unknown): Failure { @@ -560,20 +561,26 @@ function withRequestedPath(prepared: PreparedCall, call: ToolCall): PreparedCall return requested === undefined ? rest : { ...rest, requestedPath: requested }; } -/** Path relative to `cwd` when inside it, else the absolute path. */ +/** Path relative to `cwd` when inside it (a name like `..env` is inside), else the absolute path. */ export function displayPath(absPath: string, cwd: string): string { const rel = path.relative(cwd, absPath); - return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : absPath; + const inside = rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); + return inside ? rel.split(path.sep).join('/') : absPath; } /** * The result as the script sees it: paths inside `cwd` are relative to it * (they resolve back to the same file when passed to a binding), so a result - * the script returns does not repeat the workspace path in every entry. - * Hooks and the diff keep the tool runtime's absolute paths. + * the script returns does not repeat the workspace path in every entry, and + * grep matches are rows under one `columns` header. `cwd` is the real path of + * the session cwd, the form the tool runtime's paths take. Hooks and the diff + * keep the tool runtime's absolute paths. */ -export function scriptResult(result: ToolResult, cwd: string): ToolResult { - if ('matches' in result) return { ...result, matches: result.matches.map((m) => ({ ...m, file: displayPath(m.file, cwd) })) }; +export function scriptResult(result: ToolResult, cwd: string): ScriptValue { + if ('matches' in result) { + const rows = result.matches.map((m) => [displayPath(m.file, cwd), m.line, m.text] as const); + return { columns: ['file', 'line', 'text'], rows, count: rows.length, truncated: result.truncated, filtered: result.filtered }; + } if ('files' in result) return { ...result, files: result.files.map((f) => displayPath(f, cwd)) }; if ('path' in result) return { ...result, path: displayPath(result.path, cwd) }; return result; diff --git a/src/core/output.test.ts b/src/core/output.test.ts index 03bf5db..f318160 100644 --- a/src/core/output.test.ts +++ b/src/core/output.test.ts @@ -1,25 +1,58 @@ -import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; -import os from 'node:os'; import path from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; -import { CHANGED_FILES_SHOWN, DIFF_INLINE_CHARS, DIFF_SAMPLE_CHARS, ERROR_CAP_CHARS, FAILED_CALLS_SHOWN, SUCCESS_CAP_CHARS, compactRunResult, formatRunResult, truncateStructurally } from './output.js'; +import { describe, expect, it } from 'vitest'; +import { OverflowStore } from './overflow.js'; +import { + DIFF_INLINE_CHARS, + DIFF_STAT_FILES, + ERROR_CAP_CHARS, + RESULT_IN_NEXT_BLOCK, + SUCCESS_CAP_CHARS, + diffStat, + formatRunResult, + runResultView, + summarizeCalls, + type McpToolResponse, + type OverflowSink, +} from './output.js'; import { stateDirPath } from './state-dir.js'; import type { CallLogEntry, RunResult } from './types.js'; const base: RunResult = { ok: true, result: null, logs: [], calls: [], changedFiles: [], diff: '', warnings: [] }; -const dirs: string[] = []; -async function tmp(): Promise { - const d = await mkdtemp(path.join(os.tmpdir(), 'acm-out-')); - dirs.push(d); - return path.join(d, 'state'); -} -afterEach(async () => { - await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true }))); -}); const allowed = (i: number, tool = 'read'): CallLogEntry => ({ id: `c${i}`, tool, summary: `${tool} f${i}.txt`, decision: 'allowed', durationMs: 2 }); +const deniedCall = (i: number, reason = 'rule: Read(./secret-*) denied'): CallLogEntry => ({ id: `c${i}`, tool: 'read', summary: `read secret-${i}.txt`, decision: 'denied', reason, durationMs: 1 }); + +/** A unified diff of `files` files, each changing `lines` lines, in the tool runtime's format. */ +function fileDiffs(files: number, lines: number): string { + let out = ''; + for (let f = 0; f < files; f++) { + out += `--- a/src/f${f}.ts\n+++ b/src/f${f}.ts\n@@ -1,${lines} +1,${lines} @@\n`; + for (let i = 0; i < lines; i++) out += `-old line ${i} of file ${f}\n`; + for (let i = 0; i < lines; i++) out += `+new line ${i} of file ${f}\n`; + } + return out; +} + +const json = (r: McpToolResponse): Record => { + const parsed: unknown = JSON.parse(r.content[0]?.text ?? ''); + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not an object'); + return Object.fromEntries(Object.entries(parsed)); +}; +const all = (r: McpToolResponse): string => r.content.map((c) => c.text).join(''); +const total = (r: McpToolResponse): number => r.content.reduce((n, c) => n + c.text.length, 0); -describe('compactRunResult', () => { +/** The whole result kept for `readOverflow`, read back through the binding. */ +function kept(store: OverflowStore, r: McpToolResponse): unknown { + const overflow = json(r)['overflow']; + if (overflow === null || typeof overflow !== 'object' || !('id' in overflow)) throw new Error('no overflow id'); + const reply = store.read({ id: overflow.id, limit: 1_000_000 }); + if (!reply.ok || !('totalChars' in reply.value)) throw new Error('overflow not readable'); + return JSON.parse(reply.value.text); +} + +const failingSink: OverflowSink = { put: () => undefined }; + +describe('summarizeCalls', () => { it('turns the call log into counts and keeps denied and failed calls in full, without durations', () => { const calls: CallLogEntry[] = [ allowed(1), @@ -28,7 +61,7 @@ describe('compactRunResult', () => { { id: 'c4', tool: 'read', summary: 'read gone.txt', decision: 'error', reason: 'gone.txt does not exist', durationMs: 1 }, allowed(5), ]; - expect(compactRunResult({ ...base, calls }).view['calls']).toEqual({ + expect(summarizeCalls(calls)).toEqual({ total: 5, byTool: { read: 3, write: 1, bash: 1 }, denied: [{ id: 'c3', tool: 'bash', summary: 'bash rm x', reason: 'rule: rm is not allowed' }], @@ -36,130 +69,184 @@ describe('compactRunResult', () => { }); }); - it('does not grow with the number of allowed calls and caps the list of failed ones', () => { - const few = JSON.stringify(compactRunResult({ ...base, calls: Array.from({ length: 3 }, (_, i) => allowed(i)) }).view); - const many = JSON.stringify(compactRunResult({ ...base, calls: Array.from({ length: 3_000 }, (_, i) => allowed(i)) }).view); - expect(many.length).toBeLessThan(few.length + 10); - const denied = Array.from({ length: FAILED_CALLS_SHOWN + 7 }, (_, i): CallLogEntry => ({ ...allowed(i, 'bash'), decision: 'denied', reason: 'no' })); - const shown = (compactRunResult({ ...base, calls: denied }).view['calls'] as { denied: unknown[] }).denied; - expect(shown).toHaveLength(FAILED_CALLS_SHOWN + 1); - expect(shown.at(-1)).toBe('…[7 more]'); + it('D1: lists every denied call, however many', () => { + const out = formatRunResult({ ...base, result: 'caught all', calls: Array.from({ length: 25 }, (_, i) => deniedCall(i + 1)) }); + const calls = json(out)['calls']; + expect(calls).toMatchObject({ total: 25 }); + expect((calls as { denied: unknown[] }).denied).toEqual(Array.from({ length: 25 }, (_, i) => ({ id: `c${i + 1}`, tool: 'read', summary: `read secret-${i + 1}.txt`, reason: 'rule: Read(./secret-*) denied' }))); + expect(all(out)).not.toMatch(/more\]/); }); - it('leaves out empty fields and keeps the result, error, logs, warnings and rollback report', () => { - expect(Object.keys(compactRunResult({ ...base, result: 1 }).view).sort()).toEqual(['calls', 'ok', 'result']); - const rolledBack = { restored: ['a.txt'], skipped: [] }; - const failed: RunResult = { ...base, ok: false, error: { kind: 'denied', name: 'PermissionDenied', message: 'm' }, logs: ['l'], warnings: ['w'], rolledBack }; - expect(compactRunResult(failed).view).toEqual({ ok: false, result: null, error: failed.error, logs: ['l'], calls: { total: 0, byTool: {} }, warnings: ['w'], rolledBack }); + it('D1: lists every failed call and every changed file', () => { + const errors = Array.from({ length: 30 }, (_, i): CallLogEntry => ({ id: `c${i}`, tool: 'read', summary: `read m${i}`, decision: 'error', reason: 'missing', durationMs: 0 })); + const changedFiles = Array.from({ length: 40 }, (_, i) => `src/f${i}.ts`); + const view = json(formatRunResult({ ...base, calls: errors, changedFiles, diff: '--- a/x\n+++ b/x\n@@ -1,1 +1,1 @@\n-a\n+b\n' })); + expect((view['calls'] as { errors: unknown[] }).errors).toHaveLength(30); + expect(view['changedFiles']).toEqual(changedFiles); }); - it('returns a small diff whole and cuts a large one at a line end', () => { - const small = 'x'.repeat(DIFF_INLINE_CHARS - 1) + '\n'; - expect(compactRunResult({ ...base, diff: small })).toMatchObject({ diffClipped: false, view: { diff: small } }); - const line = '+0123456789\n'; - const large = line.repeat(Math.ceil((DIFF_INLINE_CHARS + 1) / line.length)); - const { view, diffClipped } = compactRunResult({ ...base, diff: large }); - const shown = String(view['diff']); - expect(diffClipped).toBe(true); - const kept = shown.slice(0, shown.indexOf('…[')); - expect(kept.length).toBeLessThanOrEqual(DIFF_SAMPLE_CHARS); - expect(kept.endsWith(line)).toBe(true); - expect(large.startsWith(kept)).toBe(true); - expect(shown).toContain(`…[${large.length - kept.length} more chars; overflowPath has the whole result]`); + it('keeps the size of a run with many allowed calls constant', () => { + const few = all(formatRunResult({ ...base, calls: Array.from({ length: 3 }, (_, i) => allowed(i)) })); + const many = all(formatRunResult({ ...base, calls: Array.from({ length: 3_000 }, (_, i) => allowed(i)) })); + expect(many.length - few.length).toBeLessThan(10); }); +}); - it('caps a long list of changed files', () => { - const changedFiles = Array.from({ length: CHANGED_FILES_SHOWN + 5 }, (_, i) => `f${i}.txt`); - const shown = compactRunResult({ ...base, changedFiles }).view['changedFiles'] as string[]; - expect(shown).toEqual([...changedFiles.slice(0, CHANGED_FILES_SHOWN), '…[5 more]']); +describe('runResultView', () => { + it('leaves empty fields out', () => { + expect(Object.keys(runResultView({ ...base, result: 1 }).view).sort()).toEqual(['calls', 'ok', 'result']); + const rolledBack = { restored: ['a'], skipped: [] }; + const failed: RunResult = { ...base, ok: false, error: { kind: 'error', name: 'Error', message: 'x' }, logs: ['l'], warnings: ['w'], rolledBack }; + expect(runResultView(failed).view).toEqual({ ok: false, result: null, error: failed.error, logs: ['l'], calls: { total: 0, byTool: {} }, warnings: ['w'], rolledBack }); + }); + + it('D6: verbose returns the log of every call and the whole diff', () => { + const diff = fileDiffs(30, 5); + const calls = [allowed(1), deniedCall(2)]; + const { view, cut } = runResultView({ ...base, calls, diff }, true); + expect(cut).toBe(false); + expect(view['calls']).toEqual(calls); + expect(view['diff']).toBe(diff); + expect(view['diffStat']).toBeUndefined(); }); }); -describe('formatRunResult', () => { - it('returns the whole result when verbose', async () => { - const result: RunResult = { ...base, calls: [allowed(1), allowed(2)], diff: 'd'.repeat(DIFF_INLINE_CHARS + 1) }; - const out = await formatRunResult(result, { stateDir: await tmp(), verbose: true }); - expect(JSON.parse(out.content[0]?.text ?? '')).toEqual(result); - }); - - it('saves the whole result when the compact view cut the diff, and points to the file', async () => { - const stateDir = await tmp(); - const result: RunResult = { ...base, result: 'done', calls: [allowed(1, 'write')], changedFiles: ['a.txt'], diff: '+line\n'.repeat(2_000) }; - const out = await formatRunResult(result, { stateDir }); - const shown = JSON.parse(out.content[0]?.text ?? '') as { diff: string; overflowPath: string; truncated?: boolean }; - expect(shown.truncated).toBeUndefined(); - expect(shown.diff.length).toBeLessThan(DIFF_SAMPLE_CHARS + 90); - expect(shown.diff).toContain('overflowPath'); - expect(JSON.parse(await readFile(shown.overflowPath, 'utf8'))).toEqual(result); - }); - - - it('returns compact JSON and isError', async () => { - const ok = await formatRunResult({ ...base, result: { a: 1 } }, { stateDir: await tmp() }); - expect(ok.isError).toBe(false); - expect(JSON.parse(ok.content[0]?.text ?? '')).toMatchObject({ ok: true, result: { a: 1 } }); - const err = await formatRunResult({ ...base, ok: false, error: { kind: 'error', name: 'Error', message: 'x' } }, { stateDir: await tmp() }); - expect(err.isError).toBe(true); - }); - - it('writes oversized success results to an overflow file and returns a valid preview', async () => { - const stateDir = await tmp(); - const big: RunResult = { ...base, result: { text: 'x'.repeat(100_000), list: Array.from({ length: 5_000 }, (_, i) => i) }, diff: 'd'.repeat(50_000) }; - const out = await formatRunResult(big, { stateDir }); - const text = out.content[0]?.text ?? ''; - expect(text.length).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); - const preview = JSON.parse(text) as { overflowPath: string; truncated: boolean; ok: boolean }; - expect(preview.truncated).toBe(true); - expect(preview.ok).toBe(true); - const full: unknown = JSON.parse(await readFile(preview.overflowPath, 'utf8')); - expect(full).toEqual(JSON.parse(JSON.stringify(big))); - if (process.platform !== 'win32') { - expect((await stat(preview.overflowPath)).mode & 0o777).toBe(0o600); - expect((await stat(stateDir)).mode & 0o777).toBe(0o700); - } +describe('diffStat', () => { + it('replaces a diff above the inline size, with at most ten files plus the totals', () => { + const diff = fileDiffs(30, 3); + expect(diff.length).toBeGreaterThan(DIFF_INLINE_CHARS); + const store = new OverflowStore(); + const out = formatRunResult({ ...base, changedFiles: ['src/f0.ts'], diff }, { overflow: store }); + const view = json(out); + expect(view['diff']).toBeUndefined(); + const stat = view['diffStat'] as { files: Record; moreFiles: number; total: string }; + expect(Object.keys(stat.files)).toHaveLength(DIFF_STAT_FILES); + expect(stat.files['src/f0.ts']).toBe('+3 -3'); + expect(stat.moreFiles).toBe(20); + expect(stat.total).toBe('30 files +90 -90'); + // The whole diff stays readable. + expect(kept(store, out)).toMatchObject({ diff }); }); - it('caps error results lower', async () => { - const big: RunResult = { ...base, ok: false, error: { kind: 'error', name: 'Error', message: 'm'.repeat(20_000) }, logs: ['l'.repeat(20_000)] }; - const out = await formatRunResult(big, { stateDir: await tmp() }); - const text = out.content[0]?.text ?? ''; - expect(text.length).toBeLessThanOrEqual(ERROR_CAP_CHARS); - expect(JSON.parse(text)).toMatchObject({ ok: false, truncated: true, error: { name: 'Error' } }); + it('keeps a small diff whole', () => { + const small = fileDiffs(1, 2); + expect(json(formatRunResult({ ...base, diff: small }))).toMatchObject({ diff: small }); }); - it('still returns a preview when the overflow file cannot be written', async () => { - const big: RunResult = { ...base, result: 'x'.repeat(60_000) }; - const out = await formatRunResult(big, { stateDir: '\0invalid' }); - const preview = JSON.parse(out.content[0]?.text ?? '') as Record; - expect(preview['overflowPath']).toBeUndefined(); - expect(String(preview['note'])).toContain('could not be saved'); + it('counts hunk lines from the hunk header, so removed lines that start with -- are not file headers', () => { + const diff = '--- a/a.md\n+++ b/a.md\n@@ -1,2 +1,2 @@\n--- not a header\n+++ not one either\n keep\n\\ No newline at end of file\n--- /dev/null\n+++ b/new.txt\n@@ -0,0 +1 @@\n+x\n'; + expect(diffStat(diff)).toEqual({ files: { 'a.md': '+1 -1', 'new.txt': '+1 -0' }, total: '2 files +2 -1' }); }); }); -describe('truncateStructurally', () => { - it('always returns valid JSON within the cap', () => { - const deep: Record = {}; - let cur = deep; - for (let i = 0; i < 50; i++) { - const next: Record = { s: 'y'.repeat(1_000) }; - cur['n'] = next; - cur = next; - } - for (const cap of [40, 200, 1_000, 5_000]) { - const text = truncateStructurally({ ok: true, deep, arr: new Array(1000).fill('z'.repeat(100)) }, cap, { overflowPath: '/state/x.json' }); - expect(text.length).toBeLessThanOrEqual(cap); - expect(() => JSON.parse(text)).not.toThrow(); +describe('formatRunResult: plain text result', () => { + const text = Array.from({ length: 20 }, (_, i) => `line "${i}" \\ of output`).join('\n'); + + it('sends a multi-line string result above 200 chars unescaped in a second block', () => { + const out = formatRunResult({ ...base, result: text, calls: [allowed(1)] }); + expect(out.content).toHaveLength(2); + expect(json(out)).toMatchObject({ ok: true, result: RESULT_IN_NEXT_BLOCK, calls: { total: 1 } }); + expect(out.content[1]?.text).toBe(text); + }); + + it('keeps short strings, single-line strings and other values in the JSON', () => { + for (const result of ['short\nstring', 'x'.repeat(5_000), { text }, 42]) { + const out = formatRunResult({ ...base, result }); + expect(out.content).toHaveLength(1); + expect(json(out)['result']).toEqual(result); } }); }); -describe('truncateStructurally with wide objects', () => { - it('cuts objects with many keys instead of dropping everything', () => { - const wide = Object.fromEntries(Array.from({ length: 50_000 }, (_, i) => [`k${i}`, i])); - const text = truncateStructurally({ ok: true, result: wide }, 30_000); - const parsed = JSON.parse(text) as { result: Record }; - expect(text.length).toBeLessThanOrEqual(30_000); - expect(parsed.result['k0']).toBe(0); +describe('formatRunResult: response cap', () => { + it('sets isError on failed runs', () => { + expect(formatRunResult({ ...base, result: { a: 1 } }).isError).toBe(false); + expect(formatRunResult({ ...base, ok: false, error: { kind: 'error', name: 'Error', message: 'x' } }).isError).toBe(true); + }); + + it('keeps the start and end of a huge result, reports its size and keeps the rest for readOverflow', () => { + const lines = Array.from({ length: 50_000 }, (_, i) => `row ${i}`).join('\n'); + const result: RunResult = { ...base, result: lines, calls: [allowed(1)] }; + const store = new OverflowStore(); + const out = formatRunResult(result, { overflow: store }); + expect(total(out)).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + const view = json(out); + expect(view).toMatchObject({ ok: true, result: RESULT_IN_NEXT_BLOCK, truncated: true, calls: { total: 1 } }); + const overflow = view['overflow'] as { id: string; chars: number }; + expect(overflow.chars).toBe(JSON.stringify(result).length); + const shown = out.content[1]?.text ?? ''; + expect(shown.startsWith('row 0\nrow 1\n')).toBe(true); + expect(shown.endsWith('row 49998\nrow 49999')).toBe(true); + expect(shown).toContain(`readOverflow(${JSON.stringify(overflow.id)})`); + expect(kept(store, out)).toEqual(result); + }); + + it('cuts a huge non-string result as JSON text in the second block', () => { + const result: RunResult = { ...base, result: { list: Array.from({ length: 20_000 }, (_, i) => ({ i })) } }; + const out = formatRunResult(result, { overflow: new OverflowStore() }); + expect(total(out)).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + expect(json(out)['result']).toBe(RESULT_IN_NEXT_BLOCK); + expect(out.content[1]?.text.startsWith('{"list":[{"i":0},')).toBe(true); + }); + + it('D1: above the cap, denied calls stay whole entries and the rest is in the overflow', () => { + const calls = Array.from({ length: 2_000 }, (_, i) => deniedCall(i, `hook: ${'policy text '.repeat(10)}`)); + const store = new OverflowStore(); + const out = formatRunResult({ ...base, result: 'r', calls }, { overflow: store }); + expect(total(out)).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + const denied = (json(out)['calls'] as { denied: unknown[] }).denied; + const entries = denied.slice(0, -1); + expect(entries.length).toBeGreaterThan(50); + entries.forEach((e, i) => expect(e).toEqual({ id: `c${i}`, tool: 'read', summary: `read secret-${i}.txt`, reason: calls[i]?.reason })); + expect(denied.at(-1)).toBe(`…[${2_000 - entries.length} more in overflow]`); + expect((kept(store, out) as RunResult).calls).toHaveLength(2_000); + }); + + it('caps error results lower', () => { + const big: RunResult = { ...base, ok: false, error: { kind: 'error', name: 'Error', message: 'm'.repeat(20_000) }, logs: ['l'.repeat(20_000)] }; + const out = formatRunResult(big, { overflow: new OverflowStore() }); + expect(total(out)).toBeLessThanOrEqual(ERROR_CAP_CHARS); + expect(json(out)).toMatchObject({ ok: false, truncated: true, error: { name: 'Error' } }); + }); + + it('D2: never names an overflow that could not be kept', () => { + const big: RunResult = { ...base, result: 'x\n'.repeat(60_000), calls: Array.from({ length: 3_000 }, (_, i) => deniedCall(i)) }; + const out = formatRunResult(big, { overflow: failingSink }); + expect(total(out)).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + expect(all(out)).not.toMatch(/overflow/i); + expect(json(out)).toMatchObject({ truncated: true, chars: JSON.stringify(big).length }); + const diffOnly = formatRunResult({ ...base, diff: fileDiffs(30, 3) }, { overflow: failingSink }); + expect(all(diffOnly)).not.toMatch(/overflow/i); + expect(json(diffOnly)['diffStat']).toBeDefined(); + }); + + it('stays under the cap with valid JSON whatever the shape', () => { + let seed = 7; + const rand = (n: number): number => ((seed = (seed * 1_103_515_245 + 12_345) % 2_147_483_648), seed % n); + for (let round = 0; round < 40; round++) { + const result: RunResult = { + ...base, + ok: rand(3) !== 0, + ...(rand(2) === 0 ? { error: { kind: 'error' as const, name: 'Error', message: 'e'.repeat(rand(30_000)), stack: 's\n'.repeat(rand(5_000)) } } : {}), + result: rand(2) === 0 ? 'q"\n'.repeat(rand(40_000)) : { deep: Array.from({ length: rand(5_000) }, (_, i) => ({ i, s: 'z'.repeat(rand(50)) })) }, + logs: Array.from({ length: rand(3_000) }, (_, i) => `log ${i} ${'"'.repeat(rand(40))}`), + calls: Array.from({ length: rand(1_500) }, (_, i) => (rand(2) === 0 ? allowed(i) : deniedCall(i, 'r'.repeat(rand(400))))), + changedFiles: Array.from({ length: rand(400) }, (_, i) => `src/${'d/'.repeat(rand(10))}f${i}.ts`), + diff: fileDiffs(rand(40), rand(30)), + warnings: Array.from({ length: rand(200) }, (_, i) => `warning ${i} ${'w'.repeat(rand(200))}`), + }; + for (const verbose of [false, true]) { + const out = formatRunResult(result, { overflow: new OverflowStore(), verbose }); + expect(total(out)).toBeLessThanOrEqual(result.ok ? SUCCESS_CAP_CHARS : ERROR_CAP_CHARS); + expect(json(out)['ok']).toBe(result.ok); + } + } + }); + + it('serializes values JSON cannot represent instead of throwing', () => { + const circular: Record = { n: 1n }; + circular['self'] = circular; + expect(json(formatRunResult({ ...base, result: circular }))['result']).toEqual({ n: '1', self: '[circular]' }); }); }); diff --git a/src/core/output.ts b/src/core/output.ts index ab31f33..bcffe1c 100644 --- a/src/core/output.ts +++ b/src/core/output.ts @@ -1,190 +1,312 @@ -import { randomBytes } from 'node:crypto'; -import { writeFile } from 'node:fs/promises'; -import path from 'node:path'; import { errorMessage } from './errors.js'; -import { ensureStateDir } from './state-dir.js'; import type { CallLogEntry, RunResult } from './types.js'; -/** Largest text of a successful result. */ -export const SUCCESS_CAP_CHARS = 30_000; +/** Response budget in tokens, well below Claude Code's MAX_MCP_OUTPUT_TOKENS (25,000). */ +export const RESPONSE_CAP_TOKENS = 10_000; +/** Characters per token used to turn the token budget into characters. */ +export const CHARS_PER_TOKEN = 4; +/** Largest text (all content blocks together) of a successful result. */ +export const SUCCESS_CAP_CHARS = RESPONSE_CAP_TOKENS * CHARS_PER_TOKEN; /** Largest text of an error result (Claude cuts the middle of long errors). */ export const ERROR_CAP_CHARS = 9_500; +/** A combined diff up to this size is returned whole; a larger one becomes `diffStat`. */ +export const DIFF_INLINE_CHARS = 1_500; +/** Files listed in `diffStat` before the rest is counted. */ +export const DIFF_STAT_FILES = 10; +/** A string result with a line break and more characters than this comes as plain text in a second content block. */ +export const TEXT_BLOCK_MIN_CHARS = 200; +/** Value of `result` in the JSON block when the result is in the second block. */ +export const RESULT_IN_NEXT_BLOCK = '[in the next text block]'; + export interface McpToolResponse { [key: string]: unknown; content: { type: 'text'; text: string }[]; isError: boolean; } -/** A combined diff up to this size is returned whole. */ -export const DIFF_INLINE_CHARS = 1_500; -/** How much of a larger diff is returned; the whole result goes to a file. */ -export const DIFF_SAMPLE_CHARS = 600; -/** Changed files listed before the rest is counted. */ -export const CHANGED_FILES_SHOWN = 10; -/** Denied or failed calls listed in full before the rest is counted. */ -export const FAILED_CALLS_SHOWN = 20; +/** Where the whole result goes when a response cuts something. */ +export interface OverflowSink { + /** Keeps `text` and returns its id, or undefined when it could not be kept. */ + put(text: string): string | undefined; +} export interface FormatOptions { - /** Directory for overflow files. Created 0700 when needed. */ - readonly stateDir: string; - /** Return every call and the whole diff instead of the compact view. */ + /** Keeps what the response cuts, for `readOverflow`. Without it nothing is kept. */ + readonly overflow?: OverflowSink; + /** Return the log of every call and the whole diff instead of the compact view. */ readonly verbose?: boolean; readonly successCap?: number; readonly errorCap?: number; } -interface Limits { - readonly str: number; - readonly arr: number; - readonly depth: number; -} - -const LEVELS: readonly Limits[] = [ - { str: 8_000, arr: 500, depth: 12 }, - { str: 2_000, arr: 100, depth: 10 }, - { str: 600, arr: 40, depth: 8 }, - { str: 200, arr: 15, depth: 6 }, - { str: 80, arr: 6, depth: 4 }, - { str: 30, arr: 3, depth: 3 }, -]; - -function shrink(value: unknown, limits: Limits, depth: number): unknown { - if (typeof value === 'string') { - return value.length <= limits.str ? value : `${value.slice(0, limits.str)}…[${value.length - limits.str} more chars]`; - } - if (value === null || typeof value !== 'object') return value; - if (depth >= limits.depth) return Array.isArray(value) ? `[array of ${value.length} items]` : '[object]'; - if (Array.isArray(value)) { - const kept = value.slice(0, limits.arr).map((item) => shrink(item, limits, depth + 1)); - if (value.length > limits.arr) kept.push(`…[${value.length - limits.arr} more items]`); - return kept; - } - const out: Record = {}; - const entries = Object.entries(value); - for (const [key, item] of entries.slice(0, limits.arr)) out[key] = shrink(item, limits, depth + 1); - if (entries.length > limits.arr) out['…'] = `[${entries.length - limits.arr} more keys]`; - return out; -} - /** JSON text of `value`; values JSON cannot represent become strings instead of throwing. */ export function safeStringify(value: unknown): string { const seen = new WeakSet(); try { - return JSON.stringify(value, (_key, v: unknown) => { - if (typeof v === 'bigint') return v.toString(); - if (v !== null && typeof v === 'object') { - if (seen.has(v)) return '[circular]'; - seen.add(v); - } - return v; - }) ?? 'null'; + return ( + JSON.stringify(value, (_key, v: unknown) => { + if (typeof v === 'bigint') return v.toString(); + if (v !== null && typeof v === 'object') { + if (seen.has(v)) return '[circular]'; + seen.add(v); + } + return v; + }) ?? 'null' + ); } catch (err) { return JSON.stringify({ unserializable: errorMessage(err) }); } } -/** - * Shrinks a JSON-compatible value until its JSON text fits `cap`, keeping the - * structure valid: long strings and arrays are cut with explicit markers. - * `extra` fields are added at the top level untouched. - */ -export function truncateStructurally(value: unknown, cap: number, extra: Record = {}): string { - const plain: unknown = JSON.parse(safeStringify(value)); - const base = plain !== null && typeof plain === 'object' && !Array.isArray(plain) ? plain : { value: plain }; - for (const limits of LEVELS) { - const shrunk = shrink(base, limits, 0); - const text = safeStringify({ ...(shrunk !== null && typeof shrunk === 'object' ? shrunk : { value: shrunk }), ...extra, truncated: true }); - if (text.length <= cap) return text; - } - // Last resort: only the essentials, clipped to fit. - const essentials: Record = { ...extra, truncated: true }; - if ('ok' in base) essentials['ok'] = base.ok; - if ('error' in base) essentials['error'] = shrink(base.error, { str: 200, arr: 3, depth: 2 }, 0); - let text = safeStringify(essentials); - if (text.length > cap) text = safeStringify({ truncated: true, ...('ok' in base ? { ok: base.ok } : {}) }); - return text.length <= cap ? text : '{"truncated":true}'; -} - -async function writeOverflow(stateDir: string, text: string): Promise { - const dir = await ensureStateDir(stateDir); - const file = path.join(dir, `run-${Date.now()}-${randomBytes(6).toString('hex')}.json`); - await writeFile(file, text, { mode: 0o600, flag: 'wx' }); - return file; -} - -function clipList(items: readonly T[], shown: number): (T | string)[] { - return items.length <= shown ? [...items] : [...items.slice(0, shown), `…[${items.length - shown} more]`]; -} +type FailedCall = Pick & { readonly reason?: string }; -/** The call log as counts; only calls that were denied or failed keep their entry (without the duration). */ -export function summarizeCalls(calls: readonly CallLogEntry[]): Record { +/** The call log as counts plus every denied and failed call (without the duration). */ +export function summarizeCalls(calls: readonly CallLogEntry[]): { total: number; byTool: Record; denied?: FailedCall[]; errors?: FailedCall[] } { const byTool: Record = {}; for (const c of calls) byTool[c.tool] = (byTool[c.tool] ?? 0) + 1; - const failed = (decision: CallLogEntry['decision']): unknown[] => - clipList( - calls.filter((c) => c.decision === decision).map(({ id, tool, summary, reason }) => ({ id, tool, summary, ...(reason === undefined ? {} : { reason }) })), - FAILED_CALLS_SHOWN, - ); + const failed = (decision: CallLogEntry['decision']): FailedCall[] => + calls.filter((c) => c.decision === decision).map(({ id, tool, summary, reason }) => ({ id, tool, summary, ...(reason === undefined ? {} : { reason }) })); const denied = failed('denied'); const errors = failed('error'); return { total: calls.length, byTool, ...(denied.length > 0 ? { denied } : {}), ...(errors.length > 0 ? { errors } : {}) }; } +/** Lines added and removed by a unified diff. */ +export interface DiffStat { + /** `+added -removed` of the first `DIFF_STAT_FILES` files, in diff order. */ + readonly files: Record; + /** Files changed beyond those listed. */ + readonly moreFiles?: number; + /** `N files +added -removed` over the whole diff. */ + readonly total: string; +} + /** - * The default view of a `RunResult`: what the model needs to go on, without - * the parts that grow with the number of calls. The call log becomes counts - * plus the denied and failed calls, a large diff is cut to its first lines - * (`diffClipped`), a long list of changed files is cut, empty fields are left out. + * Per-file line counts of a combined unified diff (as the tool runtime writes + * it: `--- a/x`, `+++ b/x`, `@@ -a,b +c,d @@` hunks). Hunk lines are counted + * from the hunk header, so a removed line that starts with `--` is not taken + * for a file header. */ -export function compactRunResult(result: RunResult): { readonly view: Record; readonly diffClipped: boolean } { - const { logs, calls, changedFiles, diff, warnings, ...rest } = result; - const diffClipped = diff.length > DIFF_INLINE_CHARS; - let shownDiff = diff; - if (diffClipped) { - const head = diff.slice(0, DIFF_SAMPLE_CHARS); - const lineEnd = head.lastIndexOf('\n'); - shownDiff = `${lineEnd > 0 ? head.slice(0, lineEnd + 1) : head}…[${diff.length - (lineEnd > 0 ? lineEnd + 1 : head.length)} more chars; overflowPath has the whole result]`; +export function diffStat(diff: string, shown: number = DIFF_STAT_FILES): DiffStat { + const counts = new Map(); + let current: { added: number; removed: number } | undefined; + let oldLeft = 0; + let newLeft = 0; + let oldName: string | undefined; + for (const line of diff.split('\n')) { + if (oldLeft > 0 || newLeft > 0) { + if (line.startsWith('\\')) continue; + if (current && line.startsWith('+')) (current.added++, newLeft--); + else if (current && line.startsWith('-')) (current.removed++, oldLeft--); + else (oldLeft--, newLeft--); + continue; + } + if (line.startsWith('--- ')) { + oldName = line.slice(4); + continue; + } + if (line.startsWith('+++ ')) { + const newName = line.slice(4); + const name = (newName === '/dev/null' ? (oldName ?? newName) : newName).replace(/^[ab]\//, ''); + current = counts.get(name) ?? { added: 0, removed: 0 }; + counts.set(name, current); + continue; + } + const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line); + if (hunk) { + oldLeft = hunk[1] === undefined ? 1 : Number(hunk[1]); + newLeft = hunk[2] === undefined ? 1 : Number(hunk[2]); + } } - const view = { + const entries = [...counts.entries()]; + let added = 0; + let removed = 0; + for (const [, c] of entries) (added += c.added, removed += c.removed); + const files = Object.fromEntries(entries.slice(0, shown).map(([name, c]) => [name, `+${c.added} -${c.removed}`])); + return { + files, + ...(entries.length > shown ? { moreFiles: entries.length - shown } : {}), + total: `${entries.length} file${entries.length === 1 ? '' : 's'} +${added} -${removed}`, + }; +} + +/** + * The view of a `RunResult` the model gets: empty fields left out and, unless + * `verbose`, the call log as counts plus every denied and failed call, and a + * diff above `DIFF_INLINE_CHARS` as `diffStat`. `cut` is true when the view + * dropped something (the diff) that only the whole result has. + */ +export function runResultView(result: RunResult, verbose = false): { readonly view: Record; readonly cut: boolean } { + const { logs, calls, changedFiles, diff, warnings, ...rest } = result; + const bigDiff = !verbose && diff.length > DIFF_INLINE_CHARS; + const view: Record = { ...rest, ...(logs.length > 0 ? { logs } : {}), - calls: summarizeCalls(calls), - ...(changedFiles.length > 0 ? { changedFiles: clipList(changedFiles, CHANGED_FILES_SHOWN) } : {}), - ...(shownDiff !== '' ? { diff: shownDiff } : {}), + calls: verbose ? calls : summarizeCalls(calls), + ...(changedFiles.length > 0 ? { changedFiles } : {}), + ...(diff === '' ? {} : bigDiff ? { diffStat: diffStat(diff) } : { diff }), ...(warnings.length > 0 ? { warnings } : {}), }; - return { view, diffClipped }; + return { view, cut: bigDiff }; +} + +/** Text of a result that goes in the second block, or undefined when it stays in the JSON. */ +function plainText(value: unknown): string | undefined { + return typeof value === 'string' && value.length > TEXT_BLOCK_MIN_CHARS && value.includes('\n') ? value : undefined; +} + +function response(json: Record, second: string | undefined, isError: boolean): McpToolResponse { + const content: McpToolResponse['content'] = [{ type: 'text', text: safeStringify(json) }]; + if (second !== undefined) content.push({ type: 'text', text: second }); + return { content, isError }; +} + +function size(r: McpToolResponse): number { + return r.content.reduce((n, c) => n + c.text.length, 0); +} + +/** Start and end of `text` within about `budget` characters, cut at line breaks when one is near. */ +export function headTail(text: string, budget: number, marker: (cut: number) => string): string { + if (text.length <= budget) return text; + const room = Math.max(0, budget - marker(text.length).length); + let headEnd = Math.floor(room * 0.6); + let tailStart = text.length - (room - headEnd); + const nl = text.lastIndexOf('\n', headEnd); + if (nl > headEnd * 0.8) headEnd = nl + 1; + const tl = text.indexOf('\n', tailStart); + if (tl !== -1 && tl < tailStart + (text.length - tailStart) * 0.2) tailStart = tl + 1; + return `${text.slice(0, headEnd)}${marker(tailStart - headEnd)}${text.slice(tailStart)}`; +} + +/** Lists in the view that are cut by entry count when the rest does not fit. */ +const LISTS: readonly (readonly string[])[] = [['calls', 'denied'], ['calls', 'errors'], ['calls'], ['changedFiles'], ['warnings'], ['rolledBack', 'restored'], ['rolledBack', 'skipped']]; + +function getList(view: Record, at: readonly string[]): unknown[] | undefined { + let node: unknown = view; + for (const key of at) { + if (node === null || typeof node !== 'object' || Array.isArray(node)) return undefined; + node = Object.getOwnPropertyDescriptor(node, key)?.value; + } + return Array.isArray(node) ? node : undefined; +} + +function setList(view: Record, at: readonly string[], list: unknown[]): Record { + const [key, ...more] = at; + if (key === undefined) return view; + const child = view[key]; + if (more.length === 0) return { ...view, [key]: list }; + if (child === null || typeof child !== 'object' || Array.isArray(child)) return view; + return { ...view, [key]: setList({ ...child }, more, list) }; +} + +/** `view` with each long list cut to its first `keep` entries plus a marker. */ +function cutLists(view: Record, keep: number, more: (n: number) => string): Record { + let out = view; + for (const at of LISTS) { + const list = getList(out, at); + if (list !== undefined && list.length > keep) out = setList(out, at, [...list.slice(0, keep), more(list.length - keep)]); + } + return out; +} + +/** `view` with strings above `max` characters anywhere in it cut with a marker. */ +function clipObject(view: Record, max: number): Record { + return Object.fromEntries(Object.entries(view).map(([k, v]) => [k, clipStrings(v, max)])); +} + +function clipStrings(value: unknown, max: number): unknown { + if (typeof value === 'string') return value.length <= max ? value : `${value.slice(0, max)}…[${value.length - max} chars cut]`; + if (Array.isArray(value)) return value.map((v) => clipStrings(v, max)); + if (value !== null && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, clipStrings(v, max)])); + return value; } /** - * Formats a `RunResult` as an MCP tool response: JSON text, `isError` when - * the run failed. The text is the compact view (`compactRunResult`) unless - * `verbose`. When the view cut the diff, or the text is above the cap, the - * whole result is written to an overflow file (mode 0600) and the response - * carries `overflowPath`; above the cap the text is a structurally truncated - * preview. + * Formats a `RunResult` as an MCP tool response: a JSON block (`isError` when + * the run failed) and, when the result is a multi-line string longer than + * `TEXT_BLOCK_MIN_CHARS`, the string as plain text in a second block. + * + * Nothing the model needs disappears: denied and failed calls and changed + * files are listed whole. When the view leaves something out (a large diff) + * or the response is above the cap (`SUCCESS_CAP_CHARS`, `ERROR_CAP_CHARS`), + * the whole result is kept in `opts.overflow` and the response carries + * `overflow: {id, chars}` for `readOverflow`. Above the cap, the result, the + * logs and a verbose diff keep their start and end, and long lists their + * first entries, each cut marked; `truncated: true` is set. A response never + * names an overflow that could not be kept. */ -export async function formatRunResult(result: RunResult, opts: FormatOptions): Promise { +export function formatRunResult(result: RunResult, opts: FormatOptions = {}): McpToolResponse { const isError = !result.ok; const cap = isError ? (opts.errorCap ?? ERROR_CAP_CHARS) : (opts.successCap ?? SUCCESS_CAP_CHARS); - const compact = opts.verbose === true ? undefined : compactRunResult(result); - const shown: unknown = compact ? compact.view : result; - const text = safeStringify(shown); - const fits = text.length <= cap; - if (fits && compact?.diffClipped !== true) return { content: [{ type: 'text', text }], isError }; + const { view, cut } = runResultView(result, opts.verbose === true); + const text = plainText(view['result']); + const whole = text === undefined ? view : { ...view, result: RESULT_IN_NEXT_BLOCK }; + const plain = response(whole, text, isError); + if (!cut && size(plain) <= cap) return plain; const full = safeStringify(result); - let extra: Record; - try { - const overflowPath = await writeOverflow(opts.stateDir, full); - extra = fits - ? { overflowPath } - : { overflowPath, note: `Result was ${full.length} chars; the full JSON is in the file at overflowPath (open it with the host's file reading tool).` }; - } catch (err) { - extra = { note: `${fits ? 'The diff is cut' : `Result was ${full.length} chars`} and the whole result could not be saved: ${errorMessage(err)}` }; + const id = opts.overflow?.put(full); + const overflow = id === undefined ? undefined : { id, chars: full.length }; + const noted = response(overflow ? { ...whole, overflow } : whole, text, isError); + if (size(noted) <= cap) return noted; + return capped(view, overflow, full.length, cap, isError); +} + +/** The response cut to `cap` characters: lists, then the result, logs and diff by start and end. */ +function capped(view: Record, overflow: { id: string; chars: number } | undefined, fullChars: number, cap: number, isError: boolean): McpToolResponse { + const where = overflow ? `; readOverflow(${JSON.stringify(overflow.id)}) has the whole result` : ''; + const marker = (n: number): string => `\n…[${n} chars cut${where}]\n`; + const more = (n: number): string => `…[${n} more${overflow ? ' in overflow' : ''}]`; + const { result, logs, diff, ...envelope } = view; + const resultText = result === undefined ? undefined : typeof result === 'string' ? result : safeStringify(result); + const logText = Array.isArray(logs) ? logs.join('\n') : undefined; + const diffText = typeof diff === 'string' ? diff : undefined; + const top = { truncated: true, ...(overflow ? { overflow } : { chars: fullChars }) }; + + for (let scale = 1; scale > 0.05; scale *= 0.8) { + const budget = Math.floor(cap * scale); + // The envelope (status, error, calls, files, warnings) comes first: it keeps all it needs but a quarter of + // the budget, which the result, logs and diff share. Lists lose entries before any string is clipped. + const bulk = [resultText, logText, diffText].map((t) => (t === undefined ? 0 : t.length)); + const envMax = budget - Math.min(bulk.reduce((a, b) => a + b, 0), Math.floor(budget / 4)) - 200; + let env: Record = { ...envelope, ...top }; + for (let keep = 1_000; safeStringify(env).length > envMax && keep >= 1; keep = Math.floor(keep / 2)) env = { ...cutLists(envelope, keep, more), ...top }; + if (safeStringify(env).length > envMax) env = { ...clipObject(cutLists(envelope, 0, more), 300), ...top }; + const shares = share(bulk, Math.max(0, budget - safeStringify(env).length - 200)); + const json: Record = { ...env }; + let second: string | undefined; + if (resultText !== undefined) { + const shown = headTail(resultText, shares[0] ?? 0, marker); + const whole = shown === resultText ? plainText(result) : shown; + if (shown === resultText && whole === undefined) json['result'] = result; + else (json['result'] = RESULT_IN_NEXT_BLOCK), (second = whole); + } + if (logText !== undefined) json['logs'] = headTail(logText, Math.floor((shares[1] ?? 0) / 1.2), marker).split('\n'); + if (diffText !== undefined) json['diff'] = headTail(diffText, Math.floor((shares[2] ?? 0) / 1.2), marker); + const out = response(order(json, view), second, isError); + if (size(out) <= cap) return out; } - const noted = fits ? safeStringify({ ...compact?.view, ...extra }) : undefined; - if (noted !== undefined && noted.length <= cap) return { content: [{ type: 'text', text: noted }], isError }; - return { content: [{ type: 'text', text: truncateStructurally(shown, cap, extra) }], isError }; + return response({ ok: view['ok'], ...top }, undefined, isError); +} + +/** Splits `total` among parts of the given sizes: small parts whole, the rest evenly. */ +function share(sizes: readonly number[], total: number): number[] { + const out = sizes.map(() => 0); + const order = sizes.map((s, i) => [s, i] as const).filter(([s]) => s > 0).sort((a, b) => a[0] - b[0]); + let left = total; + order.forEach(([s, i], k) => { + const fair = Math.floor(left / (order.length - k)); + out[i] = Math.min(s, fair); + left -= out[i] ?? 0; + }); + return out; +} + +/** `json` with its keys in the order of `like` (extra keys last), so a cut response reads like a whole one. */ +function order(json: Record, like: Record): Record { + const out: Record = {}; + for (const key of Object.keys(like)) if (key in json) out[key] = json[key]; + for (const [key, value] of Object.entries(json)) if (!(key in out)) out[key] = value; + return out; } diff --git a/src/core/overflow.test.ts b/src/core/overflow.test.ts new file mode 100644 index 0000000..5e0a416 --- /dev/null +++ b/src/core/overflow.test.ts @@ -0,0 +1,89 @@ +import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { OVERFLOW_TTL_MS, OverflowStore, READ_OVERFLOW_DEFAULT_LIMIT, READ_OVERFLOW_MAX_LIMIT, removeLegacyOverflowFiles } from './overflow.js'; +import type { CallReply } from './types.js'; + +function slice(reply: CallReply): { text: string; offset: number; totalChars: number; truncated: boolean } { + if (!reply.ok || !('totalChars' in reply.value)) throw new Error(`expected a slice, got ${JSON.stringify(reply)}`); + return reply.value; +} + +function failure(reply: CallReply): { code: string; message: string } { + if (reply.ok) throw new Error('expected a failure'); + return reply.error; +} + +describe('OverflowStore', () => { + it('returns opaque random ids and reads back slices by offset and limit', () => { + const store = new OverflowStore(); + const text = Array.from({ length: 1_000 }, (_, i) => `${i}`).join(','); + const id = store.put(text) ?? ''; + expect(id).toMatch(/^ov_[A-Za-z0-9_-]{22}$/); + expect(store.put(text)).not.toBe(id); + expect(slice(store.read({ id }))).toEqual({ text, offset: 0, totalChars: text.length, truncated: false }); + expect(slice(store.read({ id, offset: 4, limit: 3 }))).toEqual({ text: text.slice(4, 7), offset: 4, totalChars: text.length, truncated: true }); + expect(slice(store.read({ id, offset: text.length + 10 }))).toMatchObject({ text: '', truncated: false }); + }); + + it('applies the default limit', () => { + const store = new OverflowStore(); + const id = store.put('x'.repeat(READ_OVERFLOW_DEFAULT_LIMIT + 5)) ?? ''; + expect(slice(store.read({ id }))).toMatchObject({ truncated: true, totalChars: READ_OVERFLOW_DEFAULT_LIMIT + 5 }); + expect(slice(store.read({ id })).text).toHaveLength(READ_OVERFLOW_DEFAULT_LIMIT); + }); + + it('rejects invalid arguments at the boundary', () => { + const store = new OverflowStore(); + const id = store.put('abc') ?? ''; + for (const args of [undefined, null, 'id', { id: 1 }, {}, { id, offset: -1 }, { id, offset: 1.5 }, { id, limit: 0 }, { id, limit: READ_OVERFLOW_MAX_LIMIT + 1 }, { id, extra: true }, { id: 'x'.repeat(100) }]) { + expect(failure(store.read(args)).code).toBe('invalid-args'); + } + }); + + it('rejects unknown ids, expired ids and ids of another server session', () => { + let now = 0; + const store = new OverflowStore({ now: () => now }); + const other = new OverflowStore({ now: () => now }); + const id = store.put('secret') ?? ''; + expect(failure(other.read({ id })).code).toBe('not-found'); + expect(failure(store.read({ id: 'ov_AAAAAAAAAAAAAAAAAAAAAA' })).code).toBe('not-found'); + expect(failure(store.read({ id: '../state/run-1.json' })).code).toBe('not-found'); + now = OVERFLOW_TTL_MS - 1; + expect(slice(store.read({ id })).text).toBe('secret'); + now = OVERFLOW_TTL_MS; + expect(failure(store.read({ id })).message).toMatch(/unknown or expired/); + expect(store.size).toBe(0); + }); + + it('drops the oldest entries past its size and refuses an entry larger than all of it', () => { + const store = new OverflowStore({ maxChars: 10 }); + const a = store.put('aaaa') ?? ''; + const b = store.put('bbbb') ?? ''; + const c = store.put('cccc') ?? ''; + expect(failure(store.read({ id: a })).code).toBe('not-found'); + expect(slice(store.read({ id: b })).text).toBe('bbbb'); + expect(slice(store.read({ id: c })).text).toBe('cccc'); + expect(store.put('x'.repeat(11))).toBeUndefined(); + store.clear(); + expect(store.size).toBe(0); + }); +}); + +describe('removeLegacyOverflowFiles', () => { + it('removes only the overflow files older versions wrote', async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), 'acm-legacy-')); + try { + await writeFile(path.join(dir, 'run-1794816485423-78a1c4afd792.json'), '{}'); + await writeFile(path.join(dir, 'run-1-aaaaaaaaaaaa.json'), '{}'); + await writeFile(path.join(dir, 'run-notes.json'), '{}'); + await writeFile(path.join(dir, 'journal-x.json'), '{}'); + expect(await removeLegacyOverflowFiles(dir)).toBe(2); + expect((await readdir(dir)).sort()).toEqual(['journal-x.json', 'run-notes.json']); + expect(await removeLegacyOverflowFiles(path.join(dir, 'missing'))).toBe(0); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/core/overflow.ts b/src/core/overflow.ts new file mode 100644 index 0000000..60ec1a5 --- /dev/null +++ b/src/core/overflow.ts @@ -0,0 +1,134 @@ +import { randomBytes } from 'node:crypto'; +import { readdir, rm } from 'node:fs/promises'; +import path from 'node:path'; +import { z } from 'zod'; +import { formatIssues } from './schemas.js'; +import type { BindingError, CallReply, OverflowSlice } from './types.js'; + +/** How long a kept result stays readable. */ +export const OVERFLOW_TTL_MS = 30 * 60_000; +/** Total characters the store keeps; the oldest entries go first. */ +export const OVERFLOW_MAX_CHARS = 32_000_000; +/** Characters `readOverflow` returns when the script gives no limit. */ +export const READ_OVERFLOW_DEFAULT_LIMIT = 100_000; +/** Largest `limit` a script may ask for. */ +export const READ_OVERFLOW_MAX_LIMIT = 1_000_000; + +const ID_PATTERN = /^ov_[A-Za-z0-9_-]{22}$/; + +const ReadOverflowArgsSchema = z.strictObject({ + id: z.string().max(64), + offset: z.number().int().min(0).optional(), + limit: z.number().int().min(1).max(READ_OVERFLOW_MAX_LIMIT).optional(), +}); + +export interface OverflowStoreOptions { + readonly ttlMs?: number; + readonly maxChars?: number; + /** Clock, for tests. */ + readonly now?: () => number; +} + +interface Entry { + readonly text: string; + readonly expiresAt: number; +} + +/** + * In-memory store of the run results a response cut. Ids are random and + * opaque; entries live only in this server process (one MCP session), expire + * after `ttlMs` and are never written to disk. + */ +export class OverflowStore { + readonly #entries = new Map(); + readonly #ttlMs: number; + readonly #maxChars: number; + readonly #now: () => number; + #chars = 0; + + constructor(opts: OverflowStoreOptions = {}) { + this.#ttlMs = opts.ttlMs ?? OVERFLOW_TTL_MS; + this.#maxChars = opts.maxChars ?? OVERFLOW_MAX_CHARS; + this.#now = opts.now ?? Date.now; + } + + /** Number of live entries. */ + get size(): number { + this.#prune(); + return this.#entries.size; + } + + /** Keeps `text` and returns its id, or undefined when it cannot be kept. */ + put(text: string): string | undefined { + this.#prune(); + if (text.length > this.#maxChars) return undefined; + for (const [id, entry] of this.#entries) { + if (this.#chars + text.length <= this.#maxChars) break; + this.#drop(id, entry); + } + const id = `ov_${randomBytes(16).toString('base64url')}`; + this.#entries.set(id, { text, expiresAt: this.#now() + this.#ttlMs }); + this.#chars += text.length; + return id; + } + + /** The `readOverflow` binding. `args` comes from the script and is validated here. */ + read(args: unknown): CallReply { + const parsed = ReadOverflowArgsSchema.safeParse(args); + if (!parsed.success) return toolError('invalid-args', `readOverflow: ${formatIssues(parsed.error)}`); + const { id, offset = 0, limit = READ_OVERFLOW_DEFAULT_LIMIT } = parsed.data; + this.#prune(); + const entry = ID_PATTERN.test(id) ? this.#entries.get(id) : undefined; + if (entry === undefined) return toolError('not-found', `readOverflow: no kept result with id ${JSON.stringify(id.slice(0, 40))} (unknown or expired)`); + const text = entry.text.slice(offset, offset + limit); + const value: OverflowSlice = { text, offset, totalChars: entry.text.length, truncated: offset + text.length < entry.text.length }; + return { ok: true, value }; + } + + /** Drops every entry. */ + clear(): void { + this.#entries.clear(); + this.#chars = 0; + } + + #prune(): void { + const now = this.#now(); + for (const [id, entry] of this.#entries) if (entry.expiresAt <= now) this.#drop(id, entry); + } + + #drop(id: string, entry: Entry): void { + this.#entries.delete(id); + this.#chars -= entry.text.length; + } +} + +function toolError(code: Extract['code'], message: string): CallReply { + return { ok: false, error: { name: 'ToolError', code, message } }; +} + +/** Name of the overflow files older versions wrote to the state directory. */ +const LEGACY_OVERFLOW_FILE = /^run-\d+-[0-9a-f]{12}\.json$/; + +/** + * Deletes the overflow files older versions left in `stateDir` (whole run + * results, never cleaned up). Only files with that exact name pattern are + * touched. Returns how many were removed; never rejects. + */ +export async function removeLegacyOverflowFiles(stateDir: string): Promise { + let names: string[]; + try { + names = await readdir(stateDir); + } catch { + return 0; + } + let removed = 0; + for (const name of names.filter((n) => LEGACY_OVERFLOW_FILE.test(n))) { + try { + await rm(path.join(stateDir, name), { force: true }); + removed++; + } catch { + // Left for a later start. + } + } + return removed; +} diff --git a/src/core/run.ts b/src/core/run.ts index eb9a44e..7a5da13 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -3,6 +3,7 @@ import { errorMessage } from './errors.js'; import { DEFAULT_RUN_TIMEOUT_MS, MAX_RUN_TIMEOUT_MS, type RunArgs } from './schemas.js'; import type { CallLogEntry, + CallReply, HostAdapter, LogLevel, PolicyLoadError, @@ -41,8 +42,13 @@ export interface RunDeps

{ readonly stopGraceMs?: number; /** Upper bound of a transaction rollback. */ readonly rollbackTimeoutMs?: number; + /** Serves the `readOverflow` binding (results earlier responses of this server cut). */ + readonly overflow?: { read(args: unknown): CallReply }; } +/** Binding that reads back what a response cut; it never reaches the host, it only reads this server's memory. */ +export const READ_OVERFLOW_BINDING = 'readOverflow'; + type Bounded = { readonly done: true; readonly value: T } | { readonly done: false; readonly why: 'aborted' | 'timeout' }; /** @@ -179,6 +185,11 @@ function runError(stopReason: StopReason | undefined, outcome: SandboxOutcome, d return undefined; } +function readOverflow(store: RunDeps['overflow'], args: unknown): CallReply { + if (store === undefined) return { ok: false, error: { name: 'ToolError', code: 'not-found', message: 'readOverflow: this server keeps no cut results' } }; + return store.read(args); +} + /** * Runs one script end to end: loads the policy, starts the transaction, * runs the sandbox with the dispatcher behind its bindings, enforces the @@ -239,7 +250,7 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise active.dispatch(tool, args), + onCall: (tool, args) => (tool === READ_OVERFLOW_BINDING ? Promise.resolve(readOverflow(deps.overflow, args)) : active.dispatch(tool, args)), onLog: (level, text) => logs.add(level, text), }); } catch (err) { diff --git a/src/core/schemas.ts b/src/core/schemas.ts index cf2728d..8acabad 100644 --- a/src/core/schemas.ts +++ b/src/core/schemas.ts @@ -91,7 +91,7 @@ export const ToolArgsSchemas = { glob: GlobArgsSchema, } as const; -function formatIssues(error: z.ZodError): string { +export function formatIssues(error: z.ZodError): string { return error.issues .map((issue) => { const where = issue.path.length > 0 ? issue.path.join('.') : 'args'; @@ -160,7 +160,7 @@ export const RUN_INPUT_JSON_SCHEMA: { code: { type: 'string', description: - 'Body of an async JavaScript function. Use await with the bindings bash, read, write, edit, grep, glob; the return value is the result.', + 'Body of an async JavaScript function. Use await with the bindings bash, read, write, edit, grep, glob, readOverflow; the return value is the result.', }, verbose: { type: 'boolean', diff --git a/src/core/types.ts b/src/core/types.ts index 4dfb1a0..729cca3 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -219,6 +219,29 @@ export interface ToolResultMap { /** Any tool result. */ export type ToolResult = ToolResultMap[ToolName]; +/** `grep` result as the script sees it: one row per match, paths relative to the session cwd when inside it. */ +export interface ScriptGrepResult { + readonly columns: readonly ['file', 'line', 'text']; + readonly rows: readonly (readonly [file: string, line: number, text: string])[]; + /** Number of rows. */ + readonly count: number; + readonly truncated: boolean; + readonly filtered: number; +} + +/** What `readOverflow(id, offset?, limit?)` resolves to: a slice of a result a response cut. */ +export interface OverflowSlice { + readonly text: string; + /** Character offset of `text` in the kept result. */ + readonly offset: number; + readonly totalChars: number; + /** True when the kept result goes on after `text`. */ + readonly truncated: boolean; +} + +/** A binding's resolved value as the script receives it. */ +export type ScriptValue = Exclude | ScriptGrepResult | OverflowSlice; + // --------------------------------------------------------------------------- // Prepared calls: the exact effect that is authorized and then committed. // --------------------------------------------------------------------------- @@ -582,7 +605,7 @@ export type BindingError = /** Reply to one binding call. Never thrown: the dispatcher always resolves. */ export type CallReply = - | { readonly ok: true; readonly value: ToolResult } + | { readonly ok: true; readonly value: ScriptValue } | { readonly ok: false; readonly error: BindingError }; /** Options of `Sandbox.run`. */ @@ -674,6 +697,4 @@ export interface RunResult { readonly rolledBack?: RollbackReport; /** Notes the model must know, e.g. bash effects that were not rolled back. */ readonly warnings: readonly string[]; - /** Set by output shaping when the full result was written to a file. */ - readonly overflowPath?: string; } diff --git a/src/hosts/claude/regressions.test.ts b/src/hosts/claude/regressions.test.ts index af35f87..97bbeba 100644 --- a/src/hosts/claude/regressions.test.ts +++ b/src/hosts/claude/regressions.test.ts @@ -3,7 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { Dispatcher } from '../../core/dispatcher.js'; -import type { GlobResult, GrepResult, PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; +import type { GlobResult, PolicySnapshot, ScriptGrepResult, PreparedCall, SessionContext } from '../../core/types.js'; import { MemoryToolRuntime, makeContext } from '../../testing/index.js'; import { ClaudeHostAdapter, type ClaudePolicy } from './adapter.js'; import { runContextHook } from './context-hook.js'; @@ -160,7 +160,7 @@ describe('recursive grep and glob', () => { if (!grep.ok || !glob.ok) throw new Error('search failed'); // The script sees paths relative to the session cwd. const keep = (file: string): boolean => !s.policy.payload.isReadDenied(path.resolve(s.project, file)); - const grepFiles = ('matches' in grep.value ? (grep.value as GrepResult).matches : []).map((m) => m.file); + const grepFiles = ('rows' in grep.value ? (grep.value as ScriptGrepResult).rows : []).map(([file]) => file); const globFiles = 'files' in glob.value ? (glob.value as GlobResult).files : []; expect(grepFiles).toContain('.env'); // unfiltered, the secret leaks expect(grepFiles.filter(keep)).toEqual(['a.txt']); diff --git a/src/sandbox/child.ts b/src/sandbox/child.ts index 7cda85e..d303d7b 100644 --- a/src/sandbox/child.ts +++ b/src/sandbox/child.ts @@ -205,6 +205,9 @@ const SHIM = String.raw`(function (hostCall, hostLog, hostDone, maxResultChars, edit: function edit(arg) { return invoke('edit', arg); }, grep: function grep(arg) { return invoke('grep', arg); }, glob: function glob(arg) { return invoke('glob', arg); }, + readOverflow: function readOverflow(id, offset, limit) { + return invoke('readOverflow', id !== null && typeof id === 'object' ? id : { id: id, offset: offset, limit: limit }); + }, }; var names = objectKeys(bindings); for (var b = 0; b < names.length; b++) define(names[b], bindings[names[b]]); diff --git a/src/sandbox/quickjs-sandbox.test.ts b/src/sandbox/quickjs-sandbox.test.ts index 6c24dba..0968f74 100644 --- a/src/sandbox/quickjs-sandbox.test.ts +++ b/src/sandbox/quickjs-sandbox.test.ts @@ -4,7 +4,7 @@ import { createServer } from 'node:net'; 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 type { CallReply, LogLevel, SandboxOutcome, ScriptValue } from '../core/types.js'; import { childEntryPath, childEnv, childExecArgv, permissionFlag, QuickJsSandbox, SandboxUnavailableError, type QuickJsSandboxOptions } from './quickjs-sandbox.js'; interface Recorded { @@ -24,7 +24,7 @@ const echo: OnCall = async (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 }; + return { ok: true, value: value as ScriptValue }; } async function run( @@ -241,7 +241,7 @@ describe('QuickJsSandbox: no ambient authority', () => { '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', + 'console', 'bash', 'read', 'write', 'edit', 'grep', 'glob', 'readOverflow', ]), )); const result = value(outcome); diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 515a066..4bf82fa 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -77,7 +77,11 @@ describe('MCP server', () => { _meta: { 'anthropic/alwaysLoad': true }, inputSchema: { type: 'object', required: ['code'] }, }); - expect(tools[0]?.description).toContain('bash({command'); + const description = tools[0]?.description ?? ''; + for (const binding of ['bash', 'read', 'write', 'edit', 'grep', 'glob', 'readOverflow']) expect(description).toContain(`declare function ${binding}(`); + expect(description).toContain('QuickJS ES2023; no require/process/fs; inspect one sample file before batching edits'); + expect(description).toContain("columns: ['file', 'line', 'text']"); + expect(description).not.toMatch(/overflowPath|Example/); expect(tools[0]?.inputSchema.properties).toHaveProperty('verbose'); // Claude Code writes server instructions to the prompt cache again in every session. expect(client.getInstructions()).toBeUndefined(); @@ -178,9 +182,10 @@ describe('MCP server', () => { expect(unknown.isError).toBe(true); const text = textOf(unknown); expect(text.length).toBeLessThanOrEqual(9_500); - const body = JSON.parse(text) as { overflowPath?: string; truncated?: boolean }; + const body = JSON.parse(text) as { overflow?: { id: string }; truncated?: boolean }; expect(body.truncated).toBe(true); - expect(typeof body.overflowPath).toBe('string'); + expect(body.overflow?.id).toMatch(/^ov_/); + expect(text).not.toContain('acm-test-state'); const invalid = await client.callTool({ name: 'run', arguments: { code: 'x', transaction: 'y'.repeat(100_000) } }); expect(invalid.isError).toBe(true); diff --git a/src/server/mcp.ts b/src/server/mcp.ts index e3fca87..07c49b2 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -4,7 +4,8 @@ import { fileURLToPath } from 'node:url'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { CallToolRequestSchema, ListToolsRequestSchema, type Tool } from '@modelcontextprotocol/sdk/types.js'; import { errorMessage } from '../core/errors.js'; -import { DIFF_INLINE_CHARS, formatRunResult, type McpToolResponse } from '../core/output.js'; +import { DIFF_INLINE_CHARS, TEXT_BLOCK_MIN_CHARS, formatRunResult, type McpToolResponse } from '../core/output.js'; +import { OverflowStore, removeLegacyOverflowFiles } from '../core/overflow.js'; import { runScript, toRunRequest } from '../core/run.js'; import { RUN_INPUT_JSON_SCHEMA, parseRunArgs } from '../core/schemas.js'; import { stateDirPath } from '../core/state-dir.js'; @@ -16,26 +17,24 @@ import { createRuntime, type Runtime, type RuntimeFactory } from './runtime.js'; export const SERVER_NAME = 'agent-code-mode'; /** - * Everything the model needs to write a script. It lives in the tool - * description, not in the server `instructions`: Claude Code puts server - * instructions in the per-session environment message, where they are written - * to the prompt cache again in every session, while tool definitions sit in - * the prefix that sessions share. + * Everything the model needs to write a script: the binding signatures and + * one line of rules. It lives in the tool description, not in the server + * `instructions`: Claude Code puts server instructions in the per-session + * environment message, where they are written to the prompt cache again in + * every session, while tool definitions sit in the prefix sessions share. + * Kept short on purpose: a worked example script made the model copy its + * shape into unrelated tasks. */ -export const RUN_DESCRIPTION = `Run a JavaScript script that calls the host's tools. Prefer it when a step needs several tool calls: batch many reads, searches, edits and commands into one script instead of calling tools one by one. A script can look, decide and change things in the same call, so finish the step in one script when you can (each extra call is another model round trip), and return only what you need: filter and aggregate in the script. -The script is the body of an async function; return a value to get it back. Globals (all async, each call subject to the host permission rules and hooks): - bash({command, cwd?, timeoutMs?}) -> {exitCode, signal, stdout, stderr, truncated, timedOut} - read({path, offset?, limit?}) -> {path, content, startLine, totalLines, truncated} - write({path, content}) -> {path, created, diff} - edit({path, oldString, newString, replaceAll?}) -> {path, replacements, matchStrategy, diff} - grep({pattern, path?, glob?, ignoreCase?, maxResults?}) -> {matches: [{file, line, text}], truncated, filtered} - glob({pattern, path?, maxResults?}) -> {files, truncated, filtered} - console.log/info/warn/error -read's content is the exact text of the file, final newline included. Paths in results are relative to the working directory. -A denied call rejects with an Error named PermissionDenied; other failures reject with ToolError. -In bash, name every file literally: a glob (src/*), a variable or $(...) as a file argument gets the whole command denied when nobody can approve it. Find, read and loop over files with glob, read, grep and JavaScript instead. -Pass transaction: true to roll back file changes if the script fails or a call is denied (bash effects are never rolled back). -Returns JSON: {ok, result | error, logs, calls: {total, byTool, denied, errors}, changedFiles, diff, warnings}; empty fields are left out, and a long list of changed files and a diff above ${DIFF_INLINE_CHARS} chars are cut (verbose: true returns every call and the whole diff).`; +export const RUN_DESCRIPTION = `Run a JavaScript script (the body of an async function; return a value to get it back) that batches calls to these globals. Each call is checked against the host's permission rules and hooks; a denied call rejects with an Error named PermissionDenied, other failures with ToolError. Paths in results are relative to the working directory. +declare function bash(a: {command: string; cwd?: string; timeoutMs?: number}): Promise<{exitCode: number | null; signal: string | null; stdout: string; stderr: string; truncated: boolean; timedOut: boolean}>; +declare function read(a: {path: string; offset?: number; limit?: number}): Promise<{path: string; content: string /* exact text */; startLine: number; totalLines: number; truncated: boolean}>; +declare function write(a: {path: string; content: string}): Promise<{path: string; created: boolean; diff: string}>; +declare function edit(a: {path: string; oldString: string; newString: string; replaceAll?: boolean}): Promise<{path: string; replacements: number; matchStrategy: string; diff: string}>; +declare function grep(a: {pattern: string; path?: string; glob?: string; ignoreCase?: boolean; maxResults?: number}): Promise<{columns: ['file', 'line', 'text']; rows: [string, number, string][]; count: number; truncated: boolean; filtered: number}>; +declare function glob(a: {pattern: string; path?: string; maxResults?: number}): Promise<{files: string[]; truncated: boolean; filtered: number}>; +declare function readOverflow(id: string, offset?: number, limit?: number): Promise<{text: string; offset: number; totalChars: number; truncated: boolean}>; // the whole result JSON a response cut +type Response = {ok: boolean; result?: unknown; error?: {name: string; message: string}; logs?: string[]; calls: {total: number; byTool: Record; denied?: object[]; errors?: object[]}; changedFiles?: string[]; diff?: string; diffStat?: {files: Record; moreFiles?: number; total: string}; warnings?: string[]; truncated?: true; overflow?: {id: string; chars: number}}; // a multi-line string result over ${TEXT_BLOCK_MIN_CHARS} chars comes as plain text in a second block; a diff over ${DIFF_INLINE_CHARS} chars comes as diffStat +QuickJS ES2023; no require/process/fs; inspect one sample file before batching edits`; export const RUN_TOOL: Tool = { name: 'run', @@ -58,6 +57,8 @@ export interface McpServerOptions { readonly rootsTimeoutMs?: number; /** Restore journals left by dead server processes for each workspace first seen. Default true. */ readonly recoverJournals?: boolean; + /** Keeps what responses cut, for `readOverflow`. Default: a new store for this server. */ + readonly overflow?: OverflowStore; } /** A failed `RunResult` for protocol and validation errors, so they go through the same capped formatter. */ @@ -104,6 +105,9 @@ export function createMcpServer(opts: McpServerOptions): Server { const factory = opts.createRuntime ?? ((host: HostKind) => createRuntime(host, { env, serverCwd, stateDir })); const recoverJournals = opts.recoverJournals ?? opts.createRuntime === undefined; const recoveredRoots = new Set(); + // Cut results live in this process only; older versions wrote them to the state directory and never removed them. + const overflow = opts.overflow ?? new OverflowStore(); + if (opts.overflow === undefined) void removeLegacyOverflowFiles(stateDir); /** Rolls back what runs of crashed server processes left in this workspace, once per root; returns warnings for the model. */ const recoverFor = async (ctx: SessionContext): Promise => { if (!recoverJournals) return []; @@ -128,6 +132,7 @@ export function createMcpServer(opts: McpServerOptions): Server { }; const server = new Server({ name: SERVER_NAME, version: opts.version }, { capabilities: { tools: {} } }); + server.onclose = () => overflow.clear(); const listRoots = async (): Promise => { if (!server.getClientCapabilities()?.roots) return []; @@ -143,7 +148,7 @@ export function createMcpServer(opts: McpServerOptions): Server { server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { let verbose = false; - const respond = (result: RunResult): Promise => formatRunResult(result, { stateDir, verbose }); + const respond = (result: RunResult): McpToolResponse => formatRunResult(result, { overflow, verbose }); if (request.params.name !== RUN_TOOL.name) return respond(errorResult(`unknown tool ${JSON.stringify(request.params.name)}`)); const args = parseRunArgs(request.params.arguments); if (!args.ok) return respond(errorResult(`invalid run arguments: ${args.message}`)); @@ -162,10 +167,11 @@ export function createMcpServer(opts: McpServerOptions): Server { ctx, signal: extra.signal, maxTimeoutMs: runtime.maxTimeoutMs, + overflow, }); const result = recoveryWarnings.length === 0 ? ran : { ...ran, warnings: [...recoveryWarnings, ...ran.warnings] }; await appendRunLog(env[RUN_LOG_ENV], ctx, result); - return await respond(result); + return respond(result); } catch (err) { return respond(errorResult(`internal error: ${errorMessage(err)}`)); } diff --git a/src/testing/memory-tool-runtime.test.ts b/src/testing/memory-tool-runtime.test.ts new file mode 100644 index 0000000..818f993 --- /dev/null +++ b/src/testing/memory-tool-runtime.test.ts @@ -0,0 +1,44 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import type { PolicySnapshot, ReadResult, ToolRuntime } from '../core/types.js'; +import { NodeToolRuntime } from '../tools/runtime.js'; +import { makeContext } from './context.js'; +import { MemoryToolRuntime } from './memory-tool-runtime.js'; + +const FILES: Record = { + 'final.txt': 'a\nb\n', + 'nofinal.txt': 'a\nb\nc', + 'crlf.txt': 'a\r\nb\r\n', + 'empty.txt': '', + 'nl.txt': '\n', + 'blank.txt': 'a\n\n\n', +}; +const POLICY: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; +const WINDOWS = [{}, { offset: 1, limit: 2 }, { offset: 2, limit: 1 }, { offset: 2 }, { offset: 3, limit: 5 }, { offset: 9 }]; + +async function readWith(tools: ToolRuntime, root: string, file: string, window: { offset?: number; limit?: number }): Promise { + const prepared = await tools.prepare({ id: 'c1', tool: 'read', args: { path: file, ...window } }, makeContext(root), POLICY); + const result = await tools.commit(prepared, new AbortController().signal); + if (!('totalLines' in result)) throw new Error('not a read result'); + return { ...result, path: path.relative(root, result.path) }; +} + +describe('MemoryToolRuntime.read', () => { + it('D5: counts lines, cuts windows and keeps the exact text like NodeToolRuntime', async () => { + const dir = mkdtempSync(path.join(os.tmpdir(), 'acm-mem-')); + try { + for (const [name, text] of Object.entries(FILES)) writeFileSync(path.join(dir, name), text); + const node = new NodeToolRuntime({ stateDir: path.join(dir, '.state') }); + const memory = new MemoryToolRuntime({ root: '/ws', files: FILES }); + for (const name of Object.keys(FILES)) { + for (const window of WINDOWS) { + expect({ name, window, ...(await readWith(memory, '/ws', name, window)) }).toEqual({ name, window, ...(await readWith(node, dir, name, window)) }); + } + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index 6691bdd..8250cc6 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -283,11 +283,14 @@ export class MemoryToolRuntime implements ToolRuntime { const { absPath, offset, limit } = prepared.effect; const content = this.files.get(absPath); if (content === undefined) throw new ToolError('not-found', `${absPath} does not exist`); - const lines = content.split('\n'); + // Same line accounting as NodeToolRuntime: a final newline ends the last line, it does not start one. + const lines = content === '' ? [] : content.split('\n'); + if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop(); const window = lines.slice(offset - 1, offset - 1 + limit); this.commits.push({ id: prepared.id, tool: 'read', target: absPath }); - const more = offset - 1 + window.length < lines.length; - return { path: absPath, content: `${window.join('\n')}${more ? '\n' : ''}`, startLine: offset, totalLines: lines.length, truncated: offset - 1 + limit < lines.length }; + const unterminated = offset - 1 + window.length >= lines.length && !content.endsWith('\n'); + const text = window.length === 0 ? '' : `${window.join('\n')}${unterminated ? '' : '\n'}`; + return { path: absPath, content: text, startLine: offset, totalLines: lines.length, truncated: offset - 1 + window.length < lines.length }; } case 'grep': { const { absRoot, pattern, ignoreCase, maxResults, glob } = prepared.effect; diff --git a/test/attack/harness.ts b/test/attack/harness.ts index b66e4b8..96fd4d1 100644 --- a/test/attack/harness.ts +++ b/test/attack/harness.ts @@ -107,8 +107,10 @@ export function snapshot(dir: string): Record { export interface Server { /** Calls `run` with `verbose: true` and returns the parsed result (full call log and diff). */ run(code: string, opts?: { transaction?: boolean; timeoutMs?: number; signal?: AbortSignal }): Promise; - /** Calls `run` and returns the raw text of the response. */ + /** Calls `run` and returns the raw text of the response (all content blocks, joined). */ runText(code: string): Promise; + /** Calls `run` and returns each content block's text. */ + runBlocks(code: string): Promise; close(): Promise; } @@ -126,10 +128,10 @@ async function serve(runtime: Runtime, lab: Lab, meta: Record, const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); await server.connect(serverTransport); await client.connect(clientTransport); - const call = async (args: Record, signal?: AbortSignal): Promise => { + const call = async (args: Record, signal?: AbortSignal): Promise => { const res = await client.callTool({ name: 'run', arguments: args, _meta: meta }, CallToolResultSchema, { timeout: 120_000, ...(signal ? { signal } : {}) }); - const parsed = z.object({ content: z.array(z.object({ type: z.literal('text'), text: z.string() })).min(1) }).parse(res); - return parsed.content[0]?.text ?? ''; + const parsed = z.object({ content: z.array(z.object({ type: z.literal('text'), text: z.string() })).min(1).max(2) }).parse(res); + return parsed.content.map((c) => c.text); }; return { async run(code, opts = {}) { @@ -138,9 +140,14 @@ async function serve(runtime: Runtime, lab: Lab, meta: Record, { code, verbose: true, ...(opts.transaction ? { transaction: true } : {}), ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}) }, opts.signal, ); - return RunOutputSchema.parse(JSON.parse(text)); + const [head = '', plain] = text; + const body: unknown = JSON.parse(head); + // A multi-line string result comes as plain text in the second block. + const whole = plain !== undefined && body !== null && typeof body === 'object' ? { ...body, result: plain } : body; + return RunOutputSchema.parse(whole); }, - runText: (code) => call({ code }), + runText: async (code) => (await call({ code })).join(''), + runBlocks: (code) => call({ code }), async close() { await client.close(); await server.close(); diff --git a/test/attack/paths.test.ts b/test/attack/paths.test.ts index 5f71b9a..89c325b 100644 --- a/test/attack/paths.test.ts +++ b/test/attack/paths.test.ts @@ -128,7 +128,7 @@ describe('grep and glob never return a file the Read rules deny', () => { expect(out.ok).toBe(true); const text = JSON.stringify(out.result); expect(text).not.toContain('secret'); - expect(out.result).toMatchObject({ matches: [{ file: 'src/app.ts' }], filtered: 2 }); + expect(out.result).toMatchObject({ columns: ['file', 'line', 'text'], rows: [['src/app.ts', 1, expect.any(String)]], count: 1, filtered: 2 }); }); it('glob over the root drops the denied entries', async () => { diff --git a/test/attack/run-limits.test.ts b/test/attack/run-limits.test.ts index e5a9e77..57442b9 100644 --- a/test/attack/run-limits.test.ts +++ b/test/attack/run-limits.test.ts @@ -152,3 +152,50 @@ describe('oversized outputs are capped', () => { expect(out.result).toMatchObject({ truncated: true }); }); }); + +describe('readOverflow reads back what a response cut, in this server session only', () => { + const overflowOf = (text: string): { id: string; chars: number } => { + const body: unknown = JSON.parse(text); + const overflow = body !== null && typeof body === 'object' && 'overflow' in body ? body.overflow : undefined; + if (overflow === null || typeof overflow !== 'object' || !('id' in overflow) || typeof overflow.id !== 'string' || !('chars' in overflow) || typeof overflow.chars !== 'number') { + throw new Error(`no overflow in ${text.slice(0, 200)}`); + } + return { id: overflow.id, chars: overflow.chars }; + }; + + it('a cut result is readable whole from the next script, with no file path in the response', async () => { + const { lab, server } = await start({}); + const blocks = await server.runBlocks(`return Array.from({ length: 30000 }, (_, i) => 'line ' + i).join('\\n');`); + const text = blocks.join(''); + expect(text.length).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + expect(text).not.toContain(lab.stateDir); + expect(readdirSync(lab.stateDir).filter((f) => f.startsWith('run-'))).toEqual([]); + const { id, chars } = overflowOf(blocks[0] ?? ''); + const out = await server.run( + `const parts = []; let offset = 0; + for (;;) { const s = await readOverflow(${JSON.stringify(id)}, offset, 50000); parts.push(s.text); offset += s.text.length; if (!s.truncated) break; } + const whole = JSON.parse(parts.join('')); + const lines = whole.result.split('\\n'); + return { chars: offset, lines: lines.length, last: lines[lines.length - 1] };`, + ); + expect(out.result).toEqual({ chars, lines: 30_000, last: 'line 29999' }); + }); + + it('an id from another server session, a made-up id and bad arguments are refused', async () => { + const { lab, server } = await start({}); + const { id } = overflowOf((await server.runBlocks(`return 'x\\n'.repeat(30000);`))[0] ?? ''); + const other = await claudeServer(lab, { permissions: { defaultMode: 'bypassPermissions' } }); + try { + const out = await other.run( + `const errors = []; + for (const args of [[${JSON.stringify(id)}], ['ov_AAAAAAAAAAAAAAAAAAAAAA'], ['../state/run-1.json'], [${JSON.stringify(id)}, -1], [${JSON.stringify(id)}, 0, 0]]) { + try { await readOverflow(...args); errors.push('read'); } catch (e) { errors.push(e.name + ':' + e.code); } + } + return errors;`, + ); + expect(out.result).toEqual(['ToolError:not-found', 'ToolError:not-found', 'ToolError:not-found', 'ToolError:invalid-args', 'ToolError:invalid-args']); + } finally { + await other.close(); + } + }); +}); From ab93007cde6a2a2c431ceda2f8da9f174ca3eb8d Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:48:12 -0300 Subject: [PATCH 03/13] Benchmark: paired runs, equal warm-up, baseline build arm, pass^k and bootstrap CIs, harder tasks Arms of one host run back to back per task with the order rotated each round; every arm gets the same warm-up run, kept out of the numbers. A B0/C0 arm runs another agent-code-mode build (--acm-ref or --acm-dist) in the same matrix. The report adds real request counts, pass@1 and pass^k, cost per solved task and paired cluster-bootstrap 95% CIs. T9-T12 add multi-file, contract-preserving and edge-case tasks with hidden tests. Run workspaces now live outside the repository so agents cannot read hidden tests or solutions. Co-Authored-By: Claude Opus 5.5 --- bench/.gitignore | 2 + bench/lib/claude.ts | 11 +- bench/lib/codex.ts | 1 + bench/lib/record.ts | 39 ++- bench/lib/stats.ts | 79 +++++ bench/report.ts | 202 ++++++++++++- bench/run.ts | 285 +++++++++++++++--- bench/tasks/T10/files/src/catalog/export.js | 10 + bench/tasks/T10/files/src/catalog/labels.js | 11 + bench/tasks/T10/files/src/catalog/promo.js | 8 + bench/tasks/T10/files/src/catalog/receipt.js | 10 + bench/tasks/T10/files/src/catalog/summary.js | 14 + bench/tasks/T10/files/src/catalog/table.js | 13 + bench/tasks/T10/files/src/index.js | 8 + bench/tasks/T10/files/src/lib/price.js | 11 + bench/tasks/T10/files/test/catalog.test.js | 18 ++ bench/tasks/T10/hidden/price-contract.test.js | 86 ++++++ bench/tasks/T10/solution/apply.ts | 9 + .../T10/solution/files/src/catalog/export.js | 10 + .../T10/solution/files/src/catalog/labels.js | 11 + .../T10/solution/files/src/catalog/promo.js | 8 + .../T10/solution/files/src/catalog/receipt.js | 10 + .../T10/solution/files/src/catalog/summary.js | 14 + .../T10/solution/files/src/catalog/table.js | 11 + bench/tasks/T10/solution/files/src/index.js | 15 + .../tasks/T10/solution/files/src/lib/price.js | 11 + bench/tasks/T10/verify.ts | 83 +++++ bench/tasks/T11/files/src/lib/split.js | 6 + bench/tasks/T11/files/test/split.test.js | 7 + bench/tasks/T11/hidden/split-rules.test.js | 85 ++++++ bench/tasks/T11/solution/apply.ts | 9 + .../tasks/T11/solution/files/src/lib/split.js | 32 ++ bench/tasks/T11/verify.ts | 18 ++ bench/tasks/T12/logs.ts | 87 ++++++ bench/tasks/T12/solution/apply.ts | 7 + bench/tasks/T12/verify.ts | 16 + bench/tasks/T9/files/src/billing/discounts.js | 14 + bench/tasks/T9/files/src/billing/invoice.js | 11 + bench/tasks/T9/files/src/billing/lines.js | 18 ++ bench/tasks/T9/files/src/billing/quote.js | 9 + bench/tasks/T9/files/src/billing/statement.js | 18 ++ bench/tasks/T9/files/src/billing/tax.js | 13 + bench/tasks/T9/files/test/billing.test.js | 27 ++ .../T9/hidden/billing-consistency.test.js | 75 +++++ bench/tasks/T9/solution/apply.ts | 9 + .../solution/files/src/billing/discounts.js | 14 + .../T9/solution/files/src/billing/lines.js | 18 ++ bench/tasks/T9/verify.ts | 18 ++ bench/tasks/checks.ts | 36 ++- bench/tasks/index.ts | 69 ++++- bench/tasks/setup.ts | 25 ++ bench/tasks/types.ts | 8 +- bench/test/isolation.test.ts | 18 +- bench/test/parsers.test.ts | 18 ++ bench/test/report.test.ts | 114 ++++++- bench/test/run.test.ts | 223 +++++++++++++- bench/test/verifiers.test.ts | 75 ++++- 57 files changed, 1997 insertions(+), 90 deletions(-) create mode 100644 bench/tasks/T10/files/src/catalog/export.js create mode 100644 bench/tasks/T10/files/src/catalog/labels.js create mode 100644 bench/tasks/T10/files/src/catalog/promo.js create mode 100644 bench/tasks/T10/files/src/catalog/receipt.js create mode 100644 bench/tasks/T10/files/src/catalog/summary.js create mode 100644 bench/tasks/T10/files/src/catalog/table.js create mode 100644 bench/tasks/T10/files/src/index.js create mode 100644 bench/tasks/T10/files/src/lib/price.js create mode 100644 bench/tasks/T10/files/test/catalog.test.js create mode 100644 bench/tasks/T10/hidden/price-contract.test.js create mode 100644 bench/tasks/T10/solution/apply.ts create mode 100644 bench/tasks/T10/solution/files/src/catalog/export.js create mode 100644 bench/tasks/T10/solution/files/src/catalog/labels.js create mode 100644 bench/tasks/T10/solution/files/src/catalog/promo.js create mode 100644 bench/tasks/T10/solution/files/src/catalog/receipt.js create mode 100644 bench/tasks/T10/solution/files/src/catalog/summary.js create mode 100644 bench/tasks/T10/solution/files/src/catalog/table.js create mode 100644 bench/tasks/T10/solution/files/src/index.js create mode 100644 bench/tasks/T10/solution/files/src/lib/price.js create mode 100644 bench/tasks/T10/verify.ts create mode 100644 bench/tasks/T11/files/src/lib/split.js create mode 100644 bench/tasks/T11/files/test/split.test.js create mode 100644 bench/tasks/T11/hidden/split-rules.test.js create mode 100644 bench/tasks/T11/solution/apply.ts create mode 100644 bench/tasks/T11/solution/files/src/lib/split.js create mode 100644 bench/tasks/T11/verify.ts create mode 100644 bench/tasks/T12/logs.ts create mode 100644 bench/tasks/T12/solution/apply.ts create mode 100644 bench/tasks/T12/verify.ts create mode 100644 bench/tasks/T9/files/src/billing/discounts.js create mode 100644 bench/tasks/T9/files/src/billing/invoice.js create mode 100644 bench/tasks/T9/files/src/billing/lines.js create mode 100644 bench/tasks/T9/files/src/billing/quote.js create mode 100644 bench/tasks/T9/files/src/billing/statement.js create mode 100644 bench/tasks/T9/files/src/billing/tax.js create mode 100644 bench/tasks/T9/files/test/billing.test.js create mode 100644 bench/tasks/T9/hidden/billing-consistency.test.js create mode 100644 bench/tasks/T9/solution/apply.ts create mode 100644 bench/tasks/T9/solution/files/src/billing/discounts.js create mode 100644 bench/tasks/T9/solution/files/src/billing/lines.js create mode 100644 bench/tasks/T9/verify.ts diff --git a/bench/.gitignore b/bench/.gitignore index 3c1b3b2..febded4 100644 --- a/bench/.gitignore +++ b/bench/.gitignore @@ -1 +1,3 @@ +# Old default work dir (now /acm-bench, outside the checkout). The runner refuses a +# --work-dir inside the repo; this line only keeps leftovers of older runs out of git. .work/ diff --git a/bench/lib/claude.ts b/bench/lib/claude.ts index a4429aa..3cf498a 100644 --- a/bench/lib/claude.ts +++ b/bench/lib/claude.ts @@ -79,6 +79,8 @@ const ToolResult = z.object({ type: z.literal('tool_result'), tool_use_id: z.str /** Error text of a blocked call (hook deny, permission rule), as opposed to an ordinary tool failure. */ export const DENIAL_TEXT = /denied|blocked|hook|protected|not allowed|permission/i; const MessageEvent = z.object({ type: z.enum(['assistant', 'user']), message: z.object({ content: z.union([z.string(), z.array(ContentBlock)]) }).passthrough() }).passthrough(); +/** An assistant event with the request's usage. Claude streams one event per content block, all with the same message id. */ +const AssistantUsage = z.object({ type: z.literal('assistant'), message: z.object({ id: z.string().min(1), usage: z.object({ output_tokens: z.number() }).passthrough() }).passthrough() }).passthrough(); const InitEvent = z.object({ type: z.literal('system'), subtype: z.literal('init'), @@ -142,7 +144,8 @@ export function parseClaudeTranscript(text: string): ParsedRun { let availableTools: string[] | null = null; let hostContext: { agents: string[]; plugins: string[]; memory: boolean } | null = null; let result: z.infer | undefined; - const evidence: Record = { result: [], toolUse: [], innerCalls: [] }; + const evidence: Record = { result: [], toolUse: [], innerCalls: [], requests: [] }; + const requestIds = new Set(); lines.forEach((line, i) => { if (line.trim() === '') return; @@ -165,6 +168,11 @@ export function parseClaudeTranscript(text: string): ParsedRun { evidence['result'] = [i + 1]; return; } + const req = AssistantUsage.safeParse(event); + if (req.success && !requestIds.has(req.data.message.id)) { + requestIds.add(req.data.message.id); + evidence['requests']?.push(i + 1); + } const msg = MessageEvent.safeParse(event); if (!msg.success || typeof msg.data.message.content === 'string') return; for (const block of msg.data.message.content) { @@ -202,6 +210,7 @@ export function parseClaudeTranscript(text: string): ParsedRun { const r: z.infer = result; return { turns: r.num_turns, + requests: requestIds.size === 0 ? null : requestIds.size, hostDurationMs: r.duration_ms, usage: { input: r.usage.input_tokens, diff --git a/bench/lib/codex.ts b/bench/lib/codex.ts index 5613990..c36456a 100644 --- a/bench/lib/codex.ts +++ b/bench/lib/codex.ts @@ -337,6 +337,7 @@ export function parseCodexTranscript(json: string, requests: string | null): Par return { turns, + requests: turns, hostDurationMs: null, usage: { input: Math.max(0, input - cached - cacheWrite), output, cacheCreation: cacheWrite, cacheRead: cached, reasoning }, hostCostUsd: null, diff --git a/bench/lib/record.ts b/bench/lib/record.ts index e6d256e..2814eb4 100644 --- a/bench/lib/record.ts +++ b/bench/lib/record.ts @@ -2,11 +2,35 @@ 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; +/** The tool surface of an arm: what the host is configured with. */ export type ArmId = 'A' | 'B' | 'C'; +/** + * Baseline arms: the agent-code-mode arm of a host (Claude B, Codex C) run against another build of + * agent-code-mode (`--acm-ref` / `--acm-dist`), so two versions are measured in the same matrix. + */ +export const BASELINE_ARMS = { claude: 'B0', codex: 'C0' } as const; +export type BenchArm = ArmId | 'B0' | 'C0'; +export const BENCH_ARMS: readonly BenchArm[] = ['A', 'B', 'C', 'B0', 'C0']; + +/** The arm whose tool surface a bench arm uses (a baseline arm is its host's agent-code-mode arm). */ +export function surfaceArm(arm: BenchArm): ArmId { + return arm === 'B0' ? 'B' : arm === 'C0' ? 'C' : arm; +} + +/** True for the arms that run an agent-code-mode build. */ +export function isAcmArm(host: 'claude' | 'codex', arm: BenchArm): boolean { + const s = surfaceArm(arm); + return host === 'claude' ? s === 'B' : s === 'C'; +} + +/** Arms a host runs: its own arms plus, with a baseline build, its baseline arm. */ +export function hostArms(host: 'claude' | 'codex', withBaseline: boolean): BenchArm[] { + return withBaseline ? [...HOST_ARMS[host], BASELINE_ARMS[host]] : [...HOST_ARMS[host]]; +} 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)' }, + claude: { A: 'native tools', B: 'agent-code-mode (strict)', B0: 'agent-code-mode baseline build (strict)' }, + codex: { A: 'native tools (direct)', B: 'Codex code mode', C: 'agent-code-mode (strict)', C0: 'agent-code-mode baseline build (strict)' }, }; const Counts = z.record(z.string(), z.number().int().nonnegative()); @@ -36,8 +60,13 @@ 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). */ + /** Claude `num_turns` (it counts tool-use rounds, not model requests); Codex number of model requests (rollout token records). */ turns: z.number().int().nonnegative().nullable(), + /** + * Model requests, counted from usage events: Claude distinct assistant `message.id`s that carry usage + * (one request can stream several assistant events), Codex rollout token records. Null when not observable. + */ + requests: z.number().int().nonnegative().nullable().default(null), /** Host-reported duration (Claude `duration_ms`), null when the host does not report one. */ hostDurationMs: z.number().nonnegative().nullable(), usage: UsageSchema.nullable(), @@ -71,8 +100,10 @@ export const RunRecordSchema = z.object({ configHash: z.string().regex(/^[0-9a-f]{12}$/), config: z.record(z.string(), z.unknown()), host: z.enum(['claude', 'codex']), - arm: z.enum(['A', 'B', 'C']), + arm: z.enum(['A', 'B', 'C', 'B0', 'C0']), armLabel: z.string(), + /** A warmup run: made before the matrix to warm the prompt cache, kept apart and out of every statistic. */ + warmup: z.boolean().default(false), task: z.string(), run: z.number().int().positive(), round: z.number().int().positive(), diff --git a/bench/lib/stats.ts b/bench/lib/stats.ts index 9eefa49..34abeaa 100644 --- a/bench/lib/stats.ts +++ b/bench/lib/stats.ts @@ -1,3 +1,5 @@ +import { Rng } from './rng.ts'; + export interface Spread { readonly median: number; readonly min: number; @@ -13,3 +15,80 @@ export function spread(values: readonly number[]): Spread | null { 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 }; } + +export function mean(values: readonly number[]): number | null { + if (values.length === 0) return null; + return values.reduce((s, v) => s + v, 0) / values.length; +} + +function choose(n: number, k: number): number { + if (k < 0 || k > n) return 0; + let r = 1; + for (let i = 1; i <= k; i++) r = (r * (n - k + i)) / i; + return r; +} + +/** + * pass^k of one task (Yao et al. 2024): the chance that k runs drawn without replacement from the n + * observed runs all pass, C(c, k) / C(n, k) for c passes. k may not exceed n (there is no estimate of + * k runs from fewer runs), so this throws instead of extrapolating. + */ +export function passHatK(passes: number, runs: number, k: number): number { + if (!Number.isInteger(k) || k < 1 || k > runs) throw new RangeError(`pass^k needs 1 <= k <= runs (k ${k}, runs ${runs})`); + if (passes < 0 || passes > runs) throw new RangeError(`passes ${passes} out of 0..${runs}`); + return choose(passes, k) / choose(runs, k); +} + +/** Linear-interpolation quantile (type 7) of a sorted array. */ +function quantile(sorted: readonly number[], q: number): number { + const pos = (sorted.length - 1) * q; + const lo = Math.floor(pos); + const hi = Math.ceil(pos); + const a = sorted[lo] as number; + const b = sorted[hi] as number; + return a + (b - a) * (pos - lo); +} + +export interface PairedTask { + /** Per-run values of the reference arm on this task. */ + readonly a: readonly number[]; + /** Per-run values of the compared arm on this task. */ + readonly b: readonly number[]; +} + +export interface BootstrapCi { + /** Mean over tasks of (mean of b - mean of a): the observed difference. */ + readonly estimate: number; + readonly lo: number; + readonly hi: number; + /** Tasks in the comparison (each one a cluster). */ + readonly tasks: number; + readonly iterations: number; + readonly seed: number; + /** True when the interval contains zero: the data do not show a difference. */ + readonly crossesZero: boolean; +} + +/** + * Paired cluster bootstrap over tasks, percentile 95% interval: each iteration draws as many tasks as + * there are, with replacement, keeps all runs of both arms of each drawn task, and takes the mean over + * the drawn tasks of the per-task difference of means (b - a). Every task weighs the same however many + * runs it has. Null with fewer than 2 tasks (a single cluster has no spread to resample). + */ +export function pairedBootstrap(tasks: readonly PairedTask[], opts: { readonly seed: number; readonly iterations?: number }): BootstrapCi | null { + const usable = tasks.filter((t) => t.a.length > 0 && t.b.length > 0); + if (usable.length < 2) return null; + const diffs = usable.map((t) => (mean(t.b) as number) - (mean(t.a) as number)); + const iterations = opts.iterations ?? 10_000; + const rng = new Rng(opts.seed); + const stats: number[] = []; + for (let it = 0; it < iterations; it++) { + let sum = 0; + for (let i = 0; i < diffs.length; i++) sum += diffs[Math.floor(rng.next() * diffs.length)] as number; + stats.push(sum / diffs.length); + } + stats.sort((x, y) => x - y); + const lo = quantile(stats, 0.025); + const hi = quantile(stats, 0.975); + return { estimate: mean(diffs) as number, lo, hi, tasks: usable.length, iterations, seed: opts.seed, crossesZero: lo <= 0 && hi >= 0 }; +} diff --git a/bench/report.ts b/bench/report.ts index ea2a33e..a00773e 100644 --- a/bench/report.ts +++ b/bench/report.ts @@ -1,8 +1,9 @@ +import { createHash } from 'node:crypto'; 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'; +import { mean, pairedBootstrap, passHatK, spread, type BootstrapCi, type Spread } from './lib/stats.ts'; /** Aggregates run records into `summary.json` and a Markdown table snippet for the README. */ @@ -18,11 +19,18 @@ export interface GroupSummary { readonly validRuns: number; readonly invalidRuns: number; readonly invalidReasons: readonly string[]; - /** Over valid runs. Null when there is no valid run. */ + /** pass@1: share of valid runs that passed. Null when there is no valid run. */ readonly passRate: number | null; + /** pass^k with k = the valid runs of this group: 1 when every valid run passed, else 0. */ + readonly passAll: number | null; + /** Sum of the cost of all valid runs (failed ones included) over the passing runs; null with no pass or no cost. */ + readonly costPerSolvedUsd: number | null; /** Over all runs (a fallback in a strict arm makes the run invalid, so it would never show over valid runs). */ readonly fallbackRate: number | null; + /** Claude `num_turns` (tool-use rounds), Codex requests. */ readonly turns: Spread | null; + /** Model requests counted from usage events. */ + readonly requests: Spread | null; readonly inputTokens: Spread | null; readonly outputTokens: Spread | null; readonly cacheCreationTokens: Spread | null; @@ -33,13 +41,55 @@ export interface GroupSummary { readonly runIds: readonly string[]; } +/** One arm over every task of a cohort (runs that differ only in task and arm). */ +export interface ArmSummary { + readonly host: 'claude' | 'codex'; + readonly cohort: string; + readonly arm: string; + readonly armLabel: string; + readonly tasks: number; + readonly validRuns: number; + readonly runs: number; + /** Mean over tasks of the per-task pass rate (every task weighs the same). */ + readonly pass1: number | null; + /** Mean over tasks of the per-task pass^k estimate C(c, k) / C(n, k); k is the same for every arm of the cohort. */ + readonly passHatK: { readonly k: number; readonly value: number } | null; + /** Mean over tasks of the per-task mean cost per run. */ + readonly costPerRunUsd: number | null; + /** All valid runs' cost (failed ones included) over the passing runs. */ + readonly costPerSolvedUsd: number | null; + readonly requests: Spread | null; + readonly turns: Spread | null; +} + +/** Difference `arm - reference` over the tasks both have, with paired cluster-bootstrap 95% intervals. */ +export interface Comparison { + readonly host: 'claude' | 'codex'; + readonly cohort: string; + readonly arm: string; + readonly reference: string; + readonly tasks: readonly string[]; + /** Difference in pass rate (fraction, b - a). */ + readonly pass: BootstrapCi | null; + /** Difference in mean cost per run (USD, b - a). */ + readonly costUsd: BootstrapCi | null; +} + export interface Summary { readonly generatedAt: string; readonly dryRun: boolean; readonly environment: unknown; readonly groups: readonly GroupSummary[]; + readonly arms: readonly ArmSummary[]; + readonly comparisons: readonly Comparison[]; + readonly bootstrap: { readonly seed: number; readonly iterations: number; readonly method: string }; + /** Warmup runs: listed, never in a statistic. */ + readonly warmup: { readonly runs: number; readonly costUsd: number; readonly runIds: readonly string[] }; } +export const BOOTSTRAP_SEED = 20261116; +export const BOOTSTRAP_ITERATIONS = 10_000; + async function findRecords(dir: string): Promise { const out: string[] = []; let entries; @@ -68,7 +118,8 @@ export async function loadRecords(resultsDir: string): Promise { const HOST_ORDER = ['claude', 'codex']; -export function summarize(records: readonly RunRecord[]): GroupSummary[] { +export function summarize(all: readonly RunRecord[]): GroupSummary[] { + const records = all.filter((r) => !r.warmup); const groups = new Map; runs: RunRecord[] }>(); for (const r of records) { const key = `${r.host}|${r.task}|${r.arm}|${r.configHash}`; @@ -81,6 +132,7 @@ export function summarize(records: readonly RunRecord[]): GroupSummary[] { 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')); + const passes = valid.filter((r) => r.verify.pass).length; out.push({ host, task, @@ -92,9 +144,12 @@ export function summarize(records: readonly RunRecord[]): GroupSummary[] { 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, + passRate: valid.length === 0 ? null : passes / valid.length, + passAll: valid.length === 0 ? null : passHatK(passes, valid.length, valid.length), + costPerSolvedUsd: costPerSolved(valid), fallbackRate: runs.length === 0 ? null : runs.filter((r) => r.fallback).length / runs.length, turns: nums((r) => r.parsed?.turns), + requests: nums((r) => r.parsed?.requests), inputTokens: nums((r) => r.parsed?.usage?.input), outputTokens: nums((r) => r.parsed?.usage?.output), cacheCreationTokens: nums((r) => r.parsed?.usage?.cacheCreation), @@ -107,6 +162,103 @@ export function summarize(records: readonly RunRecord[]): GroupSummary[] { 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) || a.configHash.localeCompare(b.configHash)); } +function costPerSolved(valid: readonly RunRecord[]): number | null { + const passes = valid.filter((r) => r.verify.pass).length; + if (passes === 0 || valid.some((r) => r.costUsd === null)) return null; + return valid.reduce((sum, r) => sum + (r.costUsd ?? 0), 0) / passes; +} + +/** Config keys that differ between the cells of one comparison (task and arm); the rest must match. */ +const CELL_KEYS = new Set(['task', 'arm', 'armDefinitionSha256', 'promptSha256', 'taskTreeSha256', 'acmBuild']); + +/** Runs share a cohort when their configs differ only in task and arm. */ +export function cohortKey(r: RunRecord): string { + const rest = Object.fromEntries(Object.entries(r.config).filter(([k]) => !CELL_KEYS.has(k)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); + return createHash('sha256').update(`${r.host}|${JSON.stringify(rest)}`).digest('hex').slice(0, 8); +} + +type Cells = Map>; // arm -> task -> valid runs + +function cohorts(records: readonly RunRecord[]): Map { + const out = new Map(); + for (const r of records) { + if (r.warmup || !r.valid) continue; + const key = cohortKey(r); + const c = out.get(key) ?? { host: r.host, cells: new Map() }; + const byTask = c.cells.get(r.arm) ?? new Map(); + byTask.set(r.task, [...(byTask.get(r.task) ?? []), r]); + c.cells.set(r.arm, byTask); + out.set(key, c); + } + return out; +} + +/** Per-arm aggregates over the tasks of each cohort. */ +export function summarizeArms(records: readonly RunRecord[]): ArmSummary[] { + const out: ArmSummary[] = []; + const all = records.filter((r) => !r.warmup); + for (const [cohort, { host, cells }] of cohorts(records)) { + // One k for the whole cohort: the fewest valid runs of any cell, so no arm is scored on more runs than it has. + const k = Math.min(...[...cells.values()].flatMap((t) => [...t.values()].map((runs) => runs.length))); + for (const [arm, byTask] of [...cells.entries()].sort(([a], [b]) => a.localeCompare(b))) { + const tasks = [...byTask.values()]; + const valid = tasks.flat(); + const passOf = (runs: readonly RunRecord[]): number => runs.filter((r) => r.verify.pass).length; + const costs = tasks.map((runs) => runs.map((r) => r.costUsd)).filter((c): c is number[] => c.every((v) => v !== null)); + out.push({ + host, + cohort, + arm, + armLabel: ARM_LABELS[host][arm] ?? arm, + tasks: tasks.length, + validRuns: valid.length, + runs: all.filter((r) => r.arm === arm && cohortKey(r) === cohort).length, + pass1: mean(tasks.map((runs) => passOf(runs) / runs.length)), + passHatK: k >= 1 ? { k, value: mean(tasks.map((runs) => passHatK(passOf(runs), runs.length, k))) as number } : null, + costPerRunUsd: costs.length === tasks.length ? mean(costs.map((c) => mean(c) as number)) : null, + costPerSolvedUsd: costPerSolved(valid), + requests: spread(valid.map((r) => r.parsed?.requests).filter((v): v is number => typeof v === 'number')), + turns: spread(valid.map((r) => r.parsed?.turns).filter((v): v is number => typeof v === 'number')), + }); + } + } + return out.sort((a, b) => HOST_ORDER.indexOf(a.host) - HOST_ORDER.indexOf(b.host) || a.cohort.localeCompare(b.cohort) || a.arm.localeCompare(b.arm)); +} + +/** The pairs compared: every arm against the native arm A, and each baseline build against its current arm. */ +function comparedPairs(arms: readonly string[]): [string, string][] { + const pairs: [string, string][] = []; + if (arms.includes('A')) for (const a of arms) if (a !== 'A') pairs.push([a, 'A']); + for (const [cur, base] of [['B', 'B0'], ['C', 'C0']] as const) if (arms.includes(cur) && arms.includes(base)) pairs.push([cur, base]); + return pairs; +} + +export function compareArms(records: readonly RunRecord[], seed = BOOTSTRAP_SEED, iterations = BOOTSTRAP_ITERATIONS): Comparison[] { + const out: Comparison[] = []; + for (const [cohort, { host, cells }] of cohorts(records)) { + for (const [arm, reference] of comparedPairs([...cells.keys()].sort())) { + const a = cells.get(reference) ?? new Map(); + const b = cells.get(arm) ?? new Map(); + const tasks = [...a.keys()].filter((t) => b.has(t)).sort(); + const pairsOf = (pick: (r: RunRecord) => number | null) => + tasks.map((t) => ({ a: (a.get(t) ?? []).map(pick), b: (b.get(t) ?? []).map(pick) })).filter((p) => p.a.every((v) => v !== null) && p.b.every((v) => v !== null)) as { a: number[]; b: number[] }[]; + const passPairs = pairsOf((r) => (r.verify.pass ? 1 : 0)); + const costPairs = pairsOf((r) => r.costUsd); + out.push({ + host, + cohort, + arm, + reference, + tasks, + pass: pairedBootstrap(passPairs, { seed, iterations }), + // Every task needs a cost on both sides, or the cost interval would cover a different task set. + costUsd: costPairs.length === tasks.length ? pairedBootstrap(costPairs, { seed, iterations }) : null, + }); + } + } + return out; +} + 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)})`; @@ -116,6 +268,15 @@ const int = (v: number): string => (Number.isInteger(v) ? String(v) : v.toFixed( 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 usdOrDash = (v: number | null): string => (v === null ? '–' : usd(v)); +const signed = (v: number, unit: (x: number) => string): string => `${v >= 0 ? '+' : '-'}${unit(Math.abs(v))}`; +const pp = (v: number): string => `${(v * 100).toFixed(1)} pp`; + +function ciCell(ci: BootstrapCi | null, unit: (x: number) => string): string { + if (ci === null) return '– (needs 2+ tasks)'; + const text = `${signed(ci.estimate, unit)} [${signed(ci.lo, unit)}, ${signed(ci.hi, unit)}]`; + return ci.crossesZero ? `${text} **CI crosses 0: no difference shown**` : text; +} const EnvSchema = z.object({ invocations: z.array(z.record(z.string(), z.unknown())) }).passthrough(); @@ -127,13 +288,35 @@ export function markdownTable(summary: Summary): string { if (new Set(keys).size !== keys.length) { lines.push('> Some host/task/arm rows appear more than once: those runs used different configs (see Config) and are reported separately, never pooled.', ''); } - lines.push('| Host | Task | Arm | Config | Pass | Turns | Input | Output | Cache write | Cache read | Cost | Wall | Fallback | Valid/runs |'); - lines.push('|---|---|---|---|---|---|---|---|---|---|---|---|---|---|'); + lines.push('Requests are model requests counted from usage events; num_turns is the host counter (Claude counts tool-use rounds, so parallel tool calls inflate it). pass^n: every valid run of the cell passed. Cost/solved: cost of all valid runs, failed ones included, over the passing runs.', ''); + lines.push('| Host | Task | Arm | Config | Pass@1 | Pass^n | Requests | num_turns | Input | Output | Cache write | Cache read | Cost | Cost/solved | Wall | Fallback | Valid/runs |'); + lines.push('|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|'); for (const g of summary.groups) { lines.push( - `| ${g.host} | ${g.task} | ${g.arm} ${g.armLabel} | ${g.configHash} | ${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} |`, + `| ${g.host} | ${g.task} | ${g.arm} ${g.armLabel} | ${g.configHash} | ${pct(g.passRate)} | ${pct(g.passAll)} | ${fmt(g.requests, int)} | ${fmt(g.turns, int)} | ${fmt(g.inputTokens, int)} | ${fmt(g.outputTokens, int)} | ${fmt(g.cacheCreationTokens, int)} | ${fmt(g.cacheReadTokens, int)} | ${fmt(g.costUsd, usd)} | ${usdOrDash(g.costPerSolvedUsd)} | ${fmt(g.wallMs, secs)} | ${pct(g.fallbackRate)} | ${g.validRuns}/${g.runs} |`, ); } + if (summary.arms.length > 0) { + lines.push('', '### Arms over all tasks', '', 'Cohort: runs whose configs differ only in task and arm. Pass@1 and cost/run are means over tasks (each task weighs the same); pass^k uses one k per cohort, the fewest valid runs of any cell, never more than the runs made.', ''); + lines.push('| Host | Cohort | Arm | Tasks | Pass@1 | Pass^k | Cost/run | Cost/solved | Requests | num_turns | Valid/runs |'); + lines.push('|---|---|---|---|---|---|---|---|---|---|---|'); + for (const a of summary.arms) { + lines.push( + `| ${a.host} | ${a.cohort} | ${a.arm} ${a.armLabel} | ${a.tasks} | ${pct(a.pass1)} | ${a.passHatK === null ? '–' : `${pct(a.passHatK.value)} (k=${a.passHatK.k})`} | ${usdOrDash(a.costPerRunUsd)} | ${usdOrDash(a.costPerSolvedUsd)} | ${fmt(a.requests, int)} | ${fmt(a.turns, int)} | ${a.validRuns}/${a.runs} |`, + ); + } + } + if (summary.comparisons.length > 0) { + lines.push('', '### Comparisons', '', `Arm minus reference over the tasks both ran: estimate [95% CI], paired cluster bootstrap over tasks (${summary.bootstrap.iterations} resamples, seed ${summary.bootstrap.seed}). An interval that crosses 0 does not show a difference.`, ''); + lines.push('| Host | Cohort | Arm vs reference | Tasks | Δ pass@1 | Δ cost/run |'); + lines.push('|---|---|---|---|---|---|'); + for (const c of summary.comparisons) { + lines.push(`| ${c.host} | ${c.cohort} | ${c.arm} vs ${c.reference} | ${c.tasks.length} | ${ciCell(c.pass, pp)} | ${ciCell(c.costUsd, usd)} |`); + } + } + if (summary.warmup.runs > 0) { + lines.push('', `Warmup: ${summary.warmup.runs} run(s), ${usd(summary.warmup.costUsd)}, kept under warmup/ and out of every number above.`); + } 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), '```', '', '
'); @@ -152,11 +335,16 @@ async function readEnvironment(resultsDir: string): Promise { /** 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 warm = records.filter((r) => r.warmup); const summary: Summary = { generatedAt: now.toISOString(), dryRun: records.length > 0 && records.every((r) => r.dryRun), environment: await readEnvironment(resultsDir), groups: summarize(records), + arms: summarizeArms(records), + comparisons: compareArms(records), + bootstrap: { seed: BOOTSTRAP_SEED, iterations: BOOTSTRAP_ITERATIONS, method: 'paired cluster bootstrap over tasks, percentile 95% interval of the mean per-task difference' }, + warmup: { runs: warm.length, costUsd: warm.reduce((s, r) => s + (r.costUsd ?? 0), 0), runIds: warm.map((r) => r.id).sort() }, }; const markdown = markdownTable(summary); await writeFile(path.join(resultsDir, 'summary.json'), `${JSON.stringify(summary, null, 2)}\n`); diff --git a/bench/run.ts b/bench/run.ts index d7ac103..7271481 100644 --- a/bench/run.ts +++ b/bench/run.ts @@ -1,7 +1,7 @@ import { execFileSync } from 'node:child_process'; -import { existsSync } from 'node:fs'; +import { existsSync, realpathSync } from 'node:fs'; import { createHash } from 'node:crypto'; -import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { mkdir, readdir, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { parseArgs } from 'node:util'; @@ -12,10 +12,10 @@ import { catalogForArm, CODEX_FEATURES_OFF, EMPTY_MCP_SERVER, catalogHasModel, c import { createCodexHome, installCleanupHandlers, removeCodexHome, sweepStaleHomes } from './lib/codex-home.ts'; import { costFromUsage, loadPricing, type Pricing } from './lib/pricing.ts'; import { runProcess } from './lib/proc.ts'; -import { ARM_LABELS, checkArm, checkSurface, CLAUDE_ARM_SURFACE, CODEX_COMMON_NON_FILE, HOST_ARMS, RunRecordSchema, type ArmId, type ParsedRun, type RunRecord } from './lib/record.ts'; +import { ARM_LABELS, BASELINE_ARMS, BENCH_ARMS, checkArm, checkSurface, CLAUDE_ARM_SURFACE, CODEX_COMMON_NON_FILE, hostArms, isAcmArm, RunRecordSchema, surfaceArm, type ArmId, type BenchArm, type ParsedRun, type RunRecord } from './lib/record.ts'; import { Rng } from './lib/rng.ts'; import { defaultSanitizeContext, sanitize, sanitizeTree, writeSanitized, type SanitizeContext } from './lib/sanitize.ts'; -import { claudeProjectSettings, CODEX_HOOK_MATCHER, createWorkspace, hookCommand, workspaceDiff, type HostId } from './lib/workspace.ts'; +import { claudeProjectSettings, CODEX_HOOK_MATCHER, createWorkspace, hookCommand, initialTree, 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'; @@ -23,7 +23,10 @@ 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. + * canned transcripts instead of model calls. `--acm-ref ` or `--acm-dist ` adds a baseline + * arm (Claude B0, Codex C0) that runs another agent-code-mode build in the same matrix. + * Workspaces live outside the checkout (default `/acm-bench`): an agent that walks up from its + * workspace must not reach bench/tasks, where the hidden tests and reference solutions are. */ export const REPO_ROOT = path.resolve(import.meta.dirname, '..'); @@ -38,7 +41,7 @@ const csv = (allowed: readonly T[]) => const OptionsSchema = z.object({ host: z.enum(['claude', 'codex', 'all']).default('all'), - arms: csv(['A', 'B', 'C'] as const).optional(), + arms: csv(BENCH_ARMS).optional(), tasks: csv(TASK_IDS).optional(), runs: z.coerce.number().int().min(1).max(50).default(3), seed: z.coerce.number().int().nonnegative().optional(), @@ -49,14 +52,58 @@ const OptionsSchema = z.object({ 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')), + workDir: z.string().default(() => defaultWorkDir()), 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), -}); + /** Baseline agent-code-mode build: a git ref of this repo, built in a temporary directory... */ + acmRef: z.string().min(1).optional(), + /** ...or the `dist` directory of a build made elsewhere (must contain cli.js). */ + acmDist: z.string().min(1).optional(), +}).refine((o) => o.acmRef === undefined || o.acmDist === undefined, { message: '--acm-ref and --acm-dist are mutually exclusive' }); export type Options = z.infer; +/** Default work dir: outside the checkout, so no run workspace has the repo (and bench/tasks) above it. */ +export function defaultWorkDir(): string { + return path.join(os.tmpdir(), 'acm-bench'); +} + +/** `p` with symlinks resolved as far as it exists (the rest appended), so a link into the repo is caught. */ +function realish(p: string): string { + const abs = path.resolve(p); + let head = abs; + const tail: string[] = []; + for (;;) { + try { + return path.join(realpathSync(head), ...tail.reverse()); + } catch { + const parent = path.dirname(head); + if (parent === head) return abs; + tail.push(path.basename(head)); + head = parent; + } + } +} + +/** True when `p` is the checkout or inside it. */ +export function insideRepo(p: string, repo: string = REPO_ROOT): boolean { + const rel = path.relative(realish(repo), realish(p)); + return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); +} + +/** + * Throws unless the run workspace is outside the checkout and no directory above it holds `bench/tasks` + * (hidden tests, reference solutions): the agent's file tools and shell can climb out of the workspace. + */ +export function assertWorkspaceIsolated(ws: string, repo: string = REPO_ROOT): void { + if (insideRepo(ws, repo)) throw new Error(`run workspace ${ws} is inside the repository checkout: hidden tests and solutions under bench/tasks would be readable`); + for (let dir = realish(ws); ; dir = path.dirname(dir)) { + if (existsSync(path.join(dir, 'bench', 'tasks'))) throw new Error(`run workspace ${ws} has ${dir}/bench/tasks above it: hidden tests and solutions would be readable`); + if (path.dirname(dir) === dir) return; + } +} + export function parseOptions(argv: readonly string[]): Options { const { values } = parseArgs({ args: [...argv], @@ -78,6 +125,8 @@ export function parseOptions(argv: readonly string[]): Options { date: { type: 'string' }, 'dry-run': { type: 'boolean' }, force: { type: 'boolean' }, + 'acm-ref': { type: 'string' }, + 'acm-dist': { type: 'string' }, }, strict: true, }); @@ -99,34 +148,67 @@ export function parseOptions(argv: readonly string[]): Options { date: values.date, dryRun: values['dry-run'], force: values.force, + acmRef: values['acm-ref'], + acmDist: values['acm-dist'], }); } export interface PlannedRun { readonly host: HostId; readonly task: TaskId; - readonly arm: ArmId; + readonly arm: BenchArm; readonly run: number; readonly round: number; readonly orderIndex: number; + /** Position of the arm inside its (round, host, task) block, 0-based. */ + readonly position: number; + /** A warmup run (kept apart from the matrix and its statistics). */ + readonly warmup?: boolean; } -/** 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 }[] = []; +/** The arms of each host that run, given `--arms` and whether there is a baseline build. */ +export function armsFor(host: HostId, arms: readonly BenchArm[] | undefined, withBaseline: boolean): BenchArm[] { + return hostArms(host, withBaseline).filter((a) => arms === undefined || arms.includes(a)); +} + +/** + * Paired schedule. Each round has one block per host x task, in a seeded order, and a block holds the + * runs of every arm of that host on that task back to back, so the arms of a task are always measured + * at the same time. Inside a block the arm order is a seeded base order rotated by one place per round + * (a Latin square): over any `arms` consecutive rounds each arm takes each position once. + */ +export function planRuns(hosts: readonly HostId[], tasks: readonly TaskId[], arms: readonly BenchArm[] | undefined, runs: number, seed: number, withBaseline = false): PlannedRun[] { + const rng = new Rng(seed); + const blocks: { host: HostId; task: TaskId; arms: BenchArm[] }[] = []; 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 list = armsFor(host, arms, withBaseline); + if (list.length === 0) continue; + for (const task of tasks) blocks.push({ host, task, arms: rng.shuffle(list) }); } 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 }); + for (const b of new Rng(seed + round * 7919).shuffle(blocks)) { + const k = b.arms.length; + for (let position = 0; position < k; position++) { + const arm = b.arms[(position + round - 1) % k] as BenchArm; + plan.push({ host: b.host, task: b.task, arm, run: round, round, orderIndex: plan.length, position }); + } + } } return plan; } -export function runId(p: Pick): string { - return `${p.host}-${p.task}-${p.arm}-r${p.run}`; +/** Task every warmup run uses: the cheapest one (the cache prefix it warms is the arm's system prompt and tools). */ +export const WARMUP_TASK: TaskId = 'T1'; + +/** One warmup run per host and arm of the plan, in a seeded order, all arms alike. */ +export function planWarmup(plan: readonly PlannedRun[], seed: number): PlannedRun[] { + const pairs = [...new Map(plan.map((p) => [`${p.host}|${p.arm}`, { host: p.host, arm: p.arm }])).values()]; + return new Rng(seed ^ 0x5eed).shuffle(pairs).map((p, i) => ({ host: p.host, arm: p.arm, task: WARMUP_TASK, run: 1, round: 1, orderIndex: i, position: i, warmup: true })); +} + +export function runId(p: Pick): string { + return `${p.warmup === true ? 'warmup-' : ''}${p.host}-${p.task}-${p.arm}-r${p.run}`; } /** Results of a run live under its config hash, so a run made with other settings is never taken for this one. */ @@ -134,6 +216,11 @@ export function runResultDir(resultsDir: string, p: Pick, configHash: string): string { + return path.join(resultsDir, 'warmup', invocation, p.host, p.task, p.arm, configHash); +} + async function exists(p: string): Promise { try { await stat(p); @@ -216,6 +303,81 @@ export interface Context { readonly seed: number; readonly versions: Readonly>; readonly git: { readonly commit: string | null; readonly dirty: boolean | null }; + /** Baseline agent-code-mode build of the B0/C0 arms, or null without `--acm-ref`/`--acm-dist`. */ + readonly baseline: AcmBuild | null; + /** Timestamp of this invocation, naming its warmup directory. */ + readonly invocation: string; +} + +export interface AcmBuild { + /** `ref:` or `dist:`: what the config hash records. */ + readonly id: string; + /** Server entry (`cli.js`) of the build. */ + readonly entry: string; +} + +/** The agent-code-mode server an arm runs: the baseline build for B0/C0, this checkout's dist otherwise. */ +function serverEntryFor(ctx: Context, arm: BenchArm): string { + if (arm === 'B0' || arm === 'C0') { + if (ctx.baseline === null) throw new Error(`arm ${arm} needs --acm-ref or --acm-dist`); + return ctx.baseline.entry; + } + return ctx.serverEntry; +} + +/** Content hash of a build directory (sorted relative paths and bytes), for `--acm-dist`. */ +async function dirHash(dir: string): Promise { + const hash = createHash('sha256'); + const files = (await readdir(dir, { recursive: true, withFileTypes: true })).filter((e) => e.isFile()).map((e) => path.join(e.parentPath, e.name)).sort(); + for (const f of files) { + hash.update(path.relative(dir, f).split(path.sep).join('/')); + hash.update('\0'); + hash.update(await readFile(f)); + hash.update('\0'); + } + return hash.digest('hex'); +} + +/** + * Resolves the baseline build. `--acm-dist `: an existing build (its cli.js runs with the + * node_modules it can resolve from there). `--acm-ref `: the commit, without bench/ and test/, is + * exported with `git archive` into `/acm-builds/`, linked to this checkout's node_modules and built with its own + * `npm run build` (reused on later invocations). Refused when the ref's package-lock.json differs from + * this checkout's: the shared node_modules would not be the dependencies that version declares. + */ +export async function resolveBaseline(opts: Pick, workDir: string): Promise { + if (opts.acmDist !== undefined) { + const dir = path.resolve(opts.acmDist); + const entry = path.join(dir, 'cli.js'); + if (!(await exists(entry))) throw new Error(`--acm-dist ${dir} has no cli.js (pass the dist directory of a build)`); + return { id: `dist:${(await dirHash(dir)).slice(0, 12)}`, entry }; + } + if (opts.acmRef === undefined) return null; + const commit = tryExec('git', ['rev-parse', '--verify', '--quiet', `${opts.acmRef}^{commit}`], REPO_ROOT); + if (commit === null || commit === '') throw new Error(`--acm-ref ${opts.acmRef} is not a commit of this repository`); + const dir = path.join(workDir, 'acm-builds', commit); + const entry = path.join(dir, 'dist', 'cli.js'); + const build = { id: `ref:${commit.slice(0, 12)}`, entry }; + // A build made before bench/ was left out of the archive would hold hidden tests next to the runs. + if ((await exists(path.join(dir, 'bench'))) || (await exists(path.join(dir, 'test')))) await rm(dir, { recursive: true, force: true }); + if (opts.dryRun || (await exists(path.join(dir, '.built')))) return build; + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); + const tar = `${dir}.tar`; + // Only what the build needs: no bench/ (hidden tests, solutions) next to the run workspaces. + execFileSync('git', ['archive', '--format=tar', '-o', tar, commit, '--', '.', ':(exclude)bench', ':(exclude)test'], { cwd: REPO_ROOT, stdio: 'ignore' }); + execFileSync('tar', ['-xf', tar, '-C', dir], { stdio: 'ignore' }); + await rm(tar, { force: true }); + const lock = async (d: string): Promise => readFile(path.join(d, 'package-lock.json'), 'utf8').catch(() => null); + if ((await lock(dir)) !== (await lock(REPO_ROOT))) { + await rm(dir, { recursive: true, force: true }); + throw new Error(`--acm-ref ${opts.acmRef}: its package-lock.json differs from this checkout's; build it in its own checkout and pass --acm-dist `); + } + await symlink(path.join(REPO_ROOT, 'node_modules'), path.join(dir, 'node_modules'), 'dir'); + execFileSync('npm', ['run', 'build'], { cwd: dir, stdio: ['ignore', 'ignore', 'pipe'], timeout: 600_000 }); + if (!(await exists(entry))) throw new Error(`--acm-ref ${opts.acmRef}: the build produced no dist/cli.js`); + await writeFile(path.join(dir, '.built'), `${commit}\n`); + return build; } function stableJson(value: unknown): string { @@ -237,20 +399,21 @@ function sha256(text: string): string { /** What the host is actually given for an arm (args, settings, config), with machine paths replaced by placeholders. */ function armDefinition(ctx: Context, p: Pick): string { const task = TASKS[p.task]; + const arm = surfaceArm(p.arm); const fixture = generateFixture(ctx.opts.fixtureSeed); let def: unknown; if (p.host === 'claude') { def = { - args: claudeArgs({ arm: p.arm, model: ctx.opts.claudeModel, effort: ctx.opts.claudeEffort, maxTurns: ctx.opts.maxTurns, settingsFile: '', mcpConfigFile: '' }), + args: claudeArgs({ arm, model: ctx.opts.claudeModel, effort: ctx.opts.claudeEffort, maxTurns: ctx.opts.maxTurns, settingsFile: '', mcpConfigFile: '' }), settings: claudeProjectSettings(task, fixture), - mcp: claudeMcpConfig(p.arm, ''), + mcp: claudeMcpConfig(arm, ''), isolation: claudeIsolationMethod(existsSync(path.join(sourceClaudeConfig(), '.credentials.json'))), }; } else { - const catalog = ctx.rawCatalog === null ? null : catalogForArm(p.arm, ctx.rawCatalog); + const catalog = ctx.rawCatalog === null ? null : catalogForArm(arm, ctx.rawCatalog); def = { args: codexArgs('', task.protectedHook), - config: codexConfigToml({ arm: p.arm, model: ctx.opts.codexModel, effort: ctx.opts.codexEffort, codexHome: '', catalogFile: catalog === null ? null : '', serverEntry: '', nodePath: 'node', emptyServerEntry: '' }), + config: codexConfigToml({ arm, model: ctx.opts.codexModel, effort: ctx.opts.codexEffort, codexHome: '', catalogFile: catalog === null ? null : '', serverEntry: '', nodePath: 'node', emptyServerEntry: '' }), hooks: task.protectedHook ? codexHooksJson(CODEX_HOOK_MATCHER, hookCommand(fixture.facts.protectedFile)) : null, catalogSha256: catalog === null ? null : sha256(catalog), }; @@ -273,10 +436,14 @@ export function runConfig(ctx: Context, p: Pick = { 'claude-settings.json': settings, 'mcp-config.json': mcp, 'command.txt': `claude ${args.map((a) => (a === '' ? '""' : a)).join(' ')}\n` }; - if (ctx.opts.dryRun) return { ...(await cannedTranscript('claude', p.arm)), stderr: '', exitCode: 0, timedOut: false, wallMs: 0, configs }; + if (ctx.opts.dryRun) return { ...(await cannedTranscript('claude', arm)), stderr: '', exitCode: 0, timedOut: false, wallMs: 0, configs }; const stdoutFile = path.join(runWork, 'stdout.jsonl'); const stderrFile = path.join(runWork, 'stderr.txt'); const configDir = path.join(runWork, 'claude-config'); @@ -343,17 +511,18 @@ async function runCodex(ctx: Context, p: PlannedRun, runWork: string, ws: string await mkdir(codexHome, { recursive: true, mode: 0o700 }); try { // The auth link is placed last, right before the host runs, and the home is registered for cleanup. - const catalog = ctx.rawCatalog === null ? null : catalogForArm(p.arm, ctx.rawCatalog); + const arm = surfaceArm(p.arm); + const catalog = ctx.rawCatalog === null ? null : catalogForArm(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, emptyServerEntry: EMPTY_MCP_SERVER }); + const config = codexConfigToml({ arm, model: ctx.opts.codexModel, effort: ctx.opts.codexEffort, codexHome, catalogFile, serverEntry: serverEntryFor(ctx, p.arm), nodePath: process.execPath, emptyServerEntry: EMPTY_MCP_SERVER }); 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 }; + if (ctx.opts.dryRun) return { ...(await cannedTranscript('codex', arm)), stderr: '', exitCode: 0, timedOut: false, wallMs: 0, configs }; createCodexHome(codexHome, sourceCodexHome()); let availableTools: string[] | null = null; try { @@ -385,6 +554,9 @@ export async function executeRun(ctx: Context, p: PlannedRun): Promise' }, @@ -463,6 +635,7 @@ export async function executeRun(ctx: Context, p: PlannedRun): Promise { const opts = parseOptions(argv); const date = opts.date ?? new Date().toISOString().slice(0, 10); const workDir = path.resolve(opts.workDir); + if (insideRepo(workDir)) { + process.stderr.write(`--work-dir ${workDir} is inside the repository checkout; run workspaces there could read the hidden tests and solutions in bench/tasks. Use a directory outside it (default: ${defaultWorkDir()}).\n`); + return 2; + } installCleanupHandlers(); for (const stale of sweepStaleHomes(workDir)) process.stderr.write(`removed a temp CODEX_HOME left by an interrupted run: ${path.relative(workDir, stale)}\n`); const resultsRoot = opts.out !== undefined ? path.resolve(opts.out) : opts.dryRun ? path.join(workDir, 'dry-run', 'results') : path.join(BENCH_DIR, 'results'); @@ -569,14 +746,29 @@ export async function main(argv: readonly string[]): Promise { const seed = opts.seed ?? (await lastSeed(resultsDir)) ?? Math.floor(Math.random() * 2 ** 31); 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); + const withBaseline = opts.acmRef !== undefined || opts.acmDist !== undefined; + const baselineArms: BenchArm[] = [BASELINE_ARMS.claude, BASELINE_ARMS.codex]; + if (!withBaseline && opts.arms?.some((a) => baselineArms.includes(a))) { + process.stderr.write('arms B0/C0 run a baseline build: pass --acm-ref or --acm-dist \n'); + return 2; + } + const plan = planRuns(hosts, tasks, opts.arms, opts.runs, seed, withBaseline); if (plan.length === 0) { process.stderr.write('nothing to run: no arm of the chosen hosts matches --arms\n'); return 2; } + let baseline: AcmBuild | null = null; + if (withBaseline && plan.some((p) => baselineArms.includes(p.arm))) { + try { + baseline = await resolveBaseline(opts, workDir); + } catch (err) { + process.stderr.write(`${err instanceof Error ? err.message : String(err)}\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')); + const needsServer = plan.some((p) => p.arm !== 'B0' && p.arm !== 'C0' && isAcmArm(p.host, p.arm)); 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; @@ -622,6 +814,9 @@ export async function main(argv: readonly string[]): Promise { runsPerArm: opts.runs, tasks, arms: opts.arms ?? 'all', + schedule: 'paired blocks (every arm of a host x task back to back), arm order rotated per round from a seeded base order', + warmup: `one ${WARMUP_TASK} run per host x arm before the matrix, kept under warmup/ and out of the statistics`, + baseline: baseline === null ? null : { id: baseline.id, arms: Object.values(BASELINE_ARMS) }, timeoutMin: opts.timeoutMin, hosts: Object.fromEntries( hosts.map((h) => [ @@ -637,17 +832,21 @@ export async function main(argv: readonly string[]): Promise { agentCodeModeDirty: git.dirty, }); - const ctx: Context = { opts: { ...opts, workDir }, date, resultsDir, pricing: loadPricing(), serverEntry, rawCatalog, seed, versions, git }; - process.stdout.write(`${opts.dryRun ? 'DRY RUN ' : ''}${plan.length} runs, seed ${seed}, results in ${path.relative(process.cwd(), resultsDir) || resultsDir}\n`); - let failures = 0; - const surfaces = new Map(); + const invocation = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z'); + const ctx: Context = { opts: { ...opts, workDir }, date, resultsDir, pricing: loadPricing(), serverEntry, rawCatalog, seed, versions, git, baseline, invocation }; + const pending: PlannedRun[] = []; for (const p of plan) { const hash = configHash(runConfig(ctx, p)); - const recordFile = path.join(runResultDir(resultsDir, p, hash), 'record.json'); - if (!opts.force && (await exists(recordFile))) { - process.stdout.write(`skip ${runId(p)} (already recorded with config ${hash})\n`); - continue; - } + if (!opts.force && (await exists(path.join(runResultDir(resultsDir, p, hash), 'record.json')))) process.stdout.write(`skip ${runId(p)} (already recorded with config ${hash})\n`); + else pending.push(p); + } + // Warm every arm of every host that still has runs, the same way, so no arm starts on a cold cache. + const warmHosts = new Set(pending.map((p) => p.host)); + const warmup = pending.length === 0 ? [] : planWarmup(plan.filter((p) => warmHosts.has(p.host)), seed); + process.stdout.write(`${opts.dryRun ? 'DRY RUN ' : ''}${pending.length} runs (+${warmup.length} warmup), seed ${seed}, results in ${path.relative(process.cwd(), resultsDir) || resultsDir}\n`); + let failures = 0; + const surfaces = new Map(); + for (const p of [...warmup, ...pending]) { try { const record = await executeRun(ctx, p); const tools = record.parsed?.availableTools; diff --git a/bench/tasks/T10/files/src/catalog/export.js b/bench/tasks/T10/files/src/catalog/export.js new file mode 100644 index 0000000..6c9723f --- /dev/null +++ b/bench/tasks/T10/files/src/catalog/export.js @@ -0,0 +1,10 @@ +import { formatPrice } from '../lib/price.js'; + +/** CSV export: prices are always plain USD amounts. */ +export function csvRow(item) { + return [item.sku, item.name, formatPrice(item.cents, undefined, false)].join(','); +} + +export function csv(items) { + return ['sku,name,price', ...items.map(csvRow)].join('\n'); +} diff --git a/bench/tasks/T10/files/src/catalog/labels.js b/bench/tasks/T10/files/src/catalog/labels.js new file mode 100644 index 0000000..64b9d4e --- /dev/null +++ b/bench/tasks/T10/files/src/catalog/labels.js @@ -0,0 +1,11 @@ +import { formatPrice } from '../lib/price.js'; + +/** Shelf label: the price with its symbol. */ +export function priceLabel(item) { + return `${item.name} ${formatPrice(item.cents, item.currency)}`; +} + +/** Label for screen readers and plain-text receipts: no symbol, currency code after the amount. */ +export function plainLabel(item) { + return `${item.name} ${formatPrice(item.cents, item.currency, false)}`; +} diff --git a/bench/tasks/T10/files/src/catalog/promo.js b/bench/tasks/T10/files/src/catalog/promo.js new file mode 100644 index 0000000..660d955 --- /dev/null +++ b/bench/tasks/T10/files/src/catalog/promo.js @@ -0,0 +1,8 @@ +import * as price from '../lib/price.js'; + +/** Banner prices for the euro store. */ +export const euro = (cents) => price.formatPrice(cents, 'EUR'); + +export function banner(item) { + return `Now only ${euro(item.cents)} (was ${price.formatPrice(item.wasCents, 'EUR', true)})`; +} diff --git a/bench/tasks/T10/files/src/catalog/receipt.js b/bench/tasks/T10/files/src/catalog/receipt.js new file mode 100644 index 0000000..9338e4c --- /dev/null +++ b/bench/tasks/T10/files/src/catalog/receipt.js @@ -0,0 +1,10 @@ +import { formatPrice as money } from '../lib/price.js'; + +/** Receipt lines: " x ", plain amounts in the receipt currency. */ +export function receiptLines(lines, currency = 'USD') { + return lines.map((l) => `${l.qty} x ${l.name} ${money(l.qty * l.cents, currency, false)}`); +} + +export function receiptTotal(lines, currency) { + return `TOTAL ${money(lines.reduce((s, l) => s + l.qty * l.cents, 0), currency)}`; +} diff --git a/bench/tasks/T10/files/src/catalog/summary.js b/bench/tasks/T10/files/src/catalog/summary.js new file mode 100644 index 0000000..49107b7 --- /dev/null +++ b/bench/tasks/T10/files/src/catalog/summary.js @@ -0,0 +1,14 @@ +import { formatPrice } from '../lib/price.js'; + +/** One-line total of items (all in one currency; USD when none is given). */ +export function summaryLine(items, currency) { + const total = items.reduce((sum, item) => sum + item.cents, 0); + return `Total (${items.length} items): ${formatPrice(total, currency)}`; +} + +/** Totals per currency, plain (no symbols), sorted by currency code. */ +export function totalsByCurrency(items) { + const totals = new Map(); + for (const item of items) totals.set(item.currency ?? 'USD', (totals.get(item.currency ?? 'USD') ?? 0) + item.cents); + return [...totals.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([cur, cents]) => formatPrice(cents, cur, false)); +} diff --git a/bench/tasks/T10/files/src/catalog/table.js b/bench/tasks/T10/files/src/catalog/table.js new file mode 100644 index 0000000..03e28b1 --- /dev/null +++ b/bench/tasks/T10/files/src/catalog/table.js @@ -0,0 +1,13 @@ +import { formatPrice } from '../lib/price.js'; + +const fmt = (cents, ...rest) => formatPrice(cents, ...rest); + +/** Text table of rows { name, cents, currency?, showSymbol? }. */ +export function priceTable(rows) { + return rows.map((row) => `${row.name.padEnd(12)} ${fmt(row.cents, row.currency, row.showSymbol)}`).join('\n'); +} + +/** Price difference between two rows, in the first row's currency. */ +export function priceDelta(a, b) { + return fmt(b.cents - a.cents, a.currency); +} diff --git a/bench/tasks/T10/files/src/index.js b/bench/tasks/T10/files/src/index.js new file mode 100644 index 0000000..1730c98 --- /dev/null +++ b/bench/tasks/T10/files/src/index.js @@ -0,0 +1,8 @@ +/** Public API of acme-orders. Code outside this repository imports from here. */ +export { formatPrice } from './lib/price.js'; +export { priceLabel, plainLabel } from './catalog/labels.js'; +export { csv, csvRow } from './catalog/export.js'; +export { priceTable, priceDelta } from './catalog/table.js'; +export { summaryLine, totalsByCurrency } from './catalog/summary.js'; +export { receiptLines, receiptTotal } from './catalog/receipt.js'; +export { banner } from './catalog/promo.js'; diff --git a/bench/tasks/T10/files/src/lib/price.js b/bench/tasks/T10/files/src/lib/price.js new file mode 100644 index 0000000..96212da --- /dev/null +++ b/bench/tasks/T10/files/src/lib/price.js @@ -0,0 +1,11 @@ +/** Price formatting for the catalog. Amounts are integer cents. */ + +const SYMBOLS = { USD: '$', EUR: '€', GBP: '£' }; + +export function formatPrice(cents, currency = 'USD', withSymbol = true) { + const sign = cents < 0 ? '-' : ''; + const abs = Math.abs(cents); + const amount = `${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, '0')}`; + if (!withSymbol) return `${sign}${amount} ${currency}`; + return `${sign}${SYMBOLS[currency] ?? `${currency} `}${amount}`; +} diff --git a/bench/tasks/T10/files/test/catalog.test.js b/bench/tasks/T10/files/test/catalog.test.js new file mode 100644 index 0000000..4338b19 --- /dev/null +++ b/bench/tasks/T10/files/test/catalog.test.js @@ -0,0 +1,18 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { formatPrice, priceLabel, plainLabel, csvRow, priceTable, summaryLine } from '../src/index.js'; + +test('public formatPrice keeps the positional form', () => { + assert.equal(formatPrice(123456), '$1234.56'); + assert.equal(formatPrice(250, 'EUR'), '€2.50'); + assert.equal(formatPrice(250, 'EUR', false), '2.50 EUR'); +}); + +test('catalog labels and exports', () => { + const item = { sku: 'SKU-APPLE', name: 'Apples', cents: 199, currency: 'GBP' }; + assert.equal(priceLabel(item), 'Apples £1.99'); + assert.equal(plainLabel(item), 'Apples 1.99 GBP'); + assert.equal(csvRow(item), 'SKU-APPLE,Apples,1.99 USD'); + assert.equal(priceTable([{ name: 'Apples', cents: 199 }]), 'Apples $1.99'); + assert.equal(summaryLine([item, item]), 'Total (2 items): $3.98'); +}); diff --git a/bench/tasks/T10/hidden/price-contract.test.js b/bench/tasks/T10/hidden/price-contract.test.js new file mode 100644 index 0000000..c7f8499 --- /dev/null +++ b/bench/tasks/T10/hidden/price-contract.test.js @@ -0,0 +1,86 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { formatPrice } from '../src/lib/price.js'; +import * as api from '../src/index.js'; +import { priceLabel, plainLabel } from '../src/catalog/labels.js'; +import { csv, csvRow } from '../src/catalog/export.js'; +import { priceTable, priceDelta } from '../src/catalog/table.js'; +import { summaryLine, totalsByCurrency } from '../src/catalog/summary.js'; +import { receiptLines, receiptTotal } from '../src/catalog/receipt.js'; +import { banner, euro } from '../src/catalog/promo.js'; + +// The formatter before the change: every output must stay exactly what it gave. +const SYMBOLS = { USD: '$', EUR: '€', GBP: '£' }; +function before(cents, currency = 'USD', withSymbol = true) { + const sign = cents < 0 ? '-' : ''; + const abs = Math.abs(cents); + const amount = `${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, '0')}`; + if (!withSymbol) return `${sign}${amount} ${currency}`; + return `${sign}${SYMBOLS[currency] ?? `${currency} `}${amount}`; +} + +const AMOUNTS = [0, 5, 199, 100000, -250, -7]; +const CURRENCIES = [undefined, 'USD', 'EUR', 'GBP', 'JPY']; +const SYMBOL_FLAGS = [undefined, true, false]; + +test('src/lib/price.js takes an options object', () => { + for (const cents of AMOUNTS) { + assert.equal(formatPrice(cents), before(cents)); + assert.equal(formatPrice(cents, {}), before(cents)); + for (const currency of CURRENCIES) { + for (const symbol of SYMBOL_FLAGS) assert.equal(formatPrice(cents, { currency, symbol }), before(cents, currency, symbol)); + } + } +}); + +test('src/index.js keeps the positional form and accepts the options form', () => { + for (const cents of AMOUNTS) { + assert.equal(api.formatPrice(cents), before(cents)); + for (const currency of CURRENCIES) { + for (const symbol of SYMBOL_FLAGS) { + assert.equal(api.formatPrice(cents, currency, symbol), before(cents, currency, symbol)); + assert.equal(api.formatPrice(cents, { currency, symbol }), before(cents, currency, symbol)); + } + } + } +}); + +const ITEMS = [ + { sku: 'SKU-APPLE', name: 'Apples', cents: 199, currency: 'GBP' }, + { sku: 'SKU-BREAD', name: 'Bread', cents: 350 }, + { sku: 'SKU-CHEESE', name: 'Cheese', cents: 1205, currency: 'EUR' }, + { sku: 'SKU-DATES', name: 'Dates', cents: -40, currency: 'JPY' }, +]; + +test('catalog outputs are unchanged', () => { + for (const item of ITEMS) { + assert.equal(priceLabel(item), `${item.name} ${before(item.cents, item.currency)}`); + assert.equal(plainLabel(item), `${item.name} ${before(item.cents, item.currency, false)}`); + assert.equal(csvRow(item), [item.sku, item.name, before(item.cents, undefined, false)].join(',')); + } + assert.equal(csv(ITEMS).split('\n').length, ITEMS.length + 1); + const rows = [ + { name: 'Apples', cents: 199 }, + { name: 'Bread', cents: 350, currency: 'EUR' }, + { name: 'Cheese', cents: 1205, currency: 'GBP', showSymbol: false }, + { name: 'Dates', cents: 99, showSymbol: true }, + { name: 'Eggs', cents: 12, currency: 'JPY', showSymbol: undefined }, + ]; + assert.equal(priceTable(rows), rows.map((r) => `${r.name.padEnd(12)} ${before(r.cents, r.currency, r.showSymbol)}`).join('\n')); + assert.equal(priceDelta(rows[1], rows[0]), before(199 - 350, 'EUR')); + assert.equal(priceDelta(rows[0], rows[2]), before(1205 - 199)); + assert.equal(summaryLine(ITEMS), `Total (4 items): ${before(199 + 350 + 1205 - 40)}`); + assert.equal(summaryLine(ITEMS, 'EUR'), `Total (4 items): ${before(199 + 350 + 1205 - 40, 'EUR')}`); + assert.deepEqual(totalsByCurrency(ITEMS), [before(1205, 'EUR', false), before(199, 'GBP', false), before(-40, 'JPY', false), before(350, 'USD', false)]); +}); + +test('aliased and namespace callers are unchanged', () => { + const lines = [{ qty: 2, name: 'Apples', cents: 199 }, { qty: 1, name: 'Honey', cents: 1250 }]; + assert.deepEqual(receiptLines(lines), ['2 x Apples 3.98 USD', '1 x Honey 12.50 USD']); + assert.deepEqual(receiptLines(lines, 'GBP'), ['2 x Apples 3.98 GBP', '1 x Honey 12.50 GBP']); + assert.equal(receiptTotal(lines), `TOTAL ${before(1648)}`); + assert.equal(receiptTotal(lines, 'EUR'), `TOTAL ${before(1648, 'EUR')}`); + assert.equal(euro(5), before(5, 'EUR')); + assert.equal(banner({ cents: 900, wasCents: 1200 }), `Now only ${before(900, 'EUR')} (was ${before(1200, 'EUR', true)})`); + assert.equal(api.banner({ cents: -1, wasCents: 0 }), `Now only ${before(-1, 'EUR')} (was ${before(0, 'EUR')})`); +}); diff --git a/bench/tasks/T10/solution/apply.ts b/bench/tasks/T10/solution/apply.ts new file mode 100644 index 0000000..9fdec03 --- /dev/null +++ b/bench/tasks/T10/solution/apply.ts @@ -0,0 +1,9 @@ +import { writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; +import { filesFrom } from '../../setup.ts'; + +export async function applySolution(workspace: string, _facts: FixtureFacts): Promise { + for (const [file, text] of filesFrom(path.join(import.meta.dirname, 'files'))) await writeFile(path.join(workspace, ...file.split('/')), text); + return 'formatPrice now takes { currency, symbol }; every caller passes options; src/index.js wraps it to keep the positional form.'; +} diff --git a/bench/tasks/T10/solution/files/src/catalog/export.js b/bench/tasks/T10/solution/files/src/catalog/export.js new file mode 100644 index 0000000..3ebb985 --- /dev/null +++ b/bench/tasks/T10/solution/files/src/catalog/export.js @@ -0,0 +1,10 @@ +import { formatPrice } from '../lib/price.js'; + +/** CSV export: prices are always plain USD amounts. */ +export function csvRow(item) { + return [item.sku, item.name, formatPrice(item.cents, { symbol: false })].join(','); +} + +export function csv(items) { + return ['sku,name,price', ...items.map(csvRow)].join('\n'); +} diff --git a/bench/tasks/T10/solution/files/src/catalog/labels.js b/bench/tasks/T10/solution/files/src/catalog/labels.js new file mode 100644 index 0000000..5cd9c39 --- /dev/null +++ b/bench/tasks/T10/solution/files/src/catalog/labels.js @@ -0,0 +1,11 @@ +import { formatPrice } from '../lib/price.js'; + +/** Shelf label: the price with its symbol. */ +export function priceLabel(item) { + return `${item.name} ${formatPrice(item.cents, { currency: item.currency })}`; +} + +/** Label for screen readers and plain-text receipts: no symbol, currency code after the amount. */ +export function plainLabel(item) { + return `${item.name} ${formatPrice(item.cents, { currency: item.currency, symbol: false })}`; +} diff --git a/bench/tasks/T10/solution/files/src/catalog/promo.js b/bench/tasks/T10/solution/files/src/catalog/promo.js new file mode 100644 index 0000000..f164f3e --- /dev/null +++ b/bench/tasks/T10/solution/files/src/catalog/promo.js @@ -0,0 +1,8 @@ +import * as price from '../lib/price.js'; + +/** Banner prices for the euro store. */ +export const euro = (cents) => price.formatPrice(cents, { currency: 'EUR' }); + +export function banner(item) { + return `Now only ${euro(item.cents)} (was ${price.formatPrice(item.wasCents, { currency: 'EUR', symbol: true })})`; +} diff --git a/bench/tasks/T10/solution/files/src/catalog/receipt.js b/bench/tasks/T10/solution/files/src/catalog/receipt.js new file mode 100644 index 0000000..a8709f9 --- /dev/null +++ b/bench/tasks/T10/solution/files/src/catalog/receipt.js @@ -0,0 +1,10 @@ +import { formatPrice as money } from '../lib/price.js'; + +/** Receipt lines: " x ", plain amounts in the receipt currency. */ +export function receiptLines(lines, currency = 'USD') { + return lines.map((l) => `${l.qty} x ${l.name} ${money(l.qty * l.cents, { currency, symbol: false })}`); +} + +export function receiptTotal(lines, currency) { + return `TOTAL ${money(lines.reduce((s, l) => s + l.qty * l.cents, 0), { currency })}`; +} diff --git a/bench/tasks/T10/solution/files/src/catalog/summary.js b/bench/tasks/T10/solution/files/src/catalog/summary.js new file mode 100644 index 0000000..aef21a1 --- /dev/null +++ b/bench/tasks/T10/solution/files/src/catalog/summary.js @@ -0,0 +1,14 @@ +import { formatPrice } from '../lib/price.js'; + +/** One-line total of items (all in one currency; USD when none is given). */ +export function summaryLine(items, currency) { + const total = items.reduce((sum, item) => sum + item.cents, 0); + return `Total (${items.length} items): ${formatPrice(total, { currency })}`; +} + +/** Totals per currency, plain (no symbols), sorted by currency code. */ +export function totalsByCurrency(items) { + const totals = new Map(); + for (const item of items) totals.set(item.currency ?? 'USD', (totals.get(item.currency ?? 'USD') ?? 0) + item.cents); + return [...totals.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([cur, cents]) => formatPrice(cents, { currency: cur, symbol: false })); +} diff --git a/bench/tasks/T10/solution/files/src/catalog/table.js b/bench/tasks/T10/solution/files/src/catalog/table.js new file mode 100644 index 0000000..0e073d2 --- /dev/null +++ b/bench/tasks/T10/solution/files/src/catalog/table.js @@ -0,0 +1,11 @@ +import { formatPrice } from '../lib/price.js'; + +/** Text table of rows { name, cents, currency?, showSymbol? }. */ +export function priceTable(rows) { + return rows.map((row) => `${row.name.padEnd(12)} ${formatPrice(row.cents, { currency: row.currency, symbol: row.showSymbol })}`).join('\n'); +} + +/** Price difference between two rows, in the first row's currency. */ +export function priceDelta(a, b) { + return formatPrice(b.cents - a.cents, { currency: a.currency }); +} diff --git a/bench/tasks/T10/solution/files/src/index.js b/bench/tasks/T10/solution/files/src/index.js new file mode 100644 index 0000000..ec0b379 --- /dev/null +++ b/bench/tasks/T10/solution/files/src/index.js @@ -0,0 +1,15 @@ +/** Public API of acme-orders. Code outside this repository imports from here. */ +import { formatPrice as formatWithOptions } from './lib/price.js'; + +/** Accepts the options form and, for existing callers, the old positional form (cents, currency, withSymbol). */ +export function formatPrice(cents, currencyOrOptions, withSymbol) { + if (currencyOrOptions !== null && typeof currencyOrOptions === 'object') return formatWithOptions(cents, currencyOrOptions); + return formatWithOptions(cents, { currency: currencyOrOptions, symbol: withSymbol }); +} + +export { priceLabel, plainLabel } from './catalog/labels.js'; +export { csv, csvRow } from './catalog/export.js'; +export { priceTable, priceDelta } from './catalog/table.js'; +export { summaryLine, totalsByCurrency } from './catalog/summary.js'; +export { receiptLines, receiptTotal } from './catalog/receipt.js'; +export { banner } from './catalog/promo.js'; diff --git a/bench/tasks/T10/solution/files/src/lib/price.js b/bench/tasks/T10/solution/files/src/lib/price.js new file mode 100644 index 0000000..7dc1923 --- /dev/null +++ b/bench/tasks/T10/solution/files/src/lib/price.js @@ -0,0 +1,11 @@ +/** Price formatting for the catalog. Amounts are integer cents. */ + +const SYMBOLS = { USD: '$', EUR: '€', GBP: '£' }; + +export function formatPrice(cents, { currency = 'USD', symbol = true } = {}) { + const sign = cents < 0 ? '-' : ''; + const abs = Math.abs(cents); + const amount = `${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, '0')}`; + if (!symbol) return `${sign}${amount} ${currency}`; + return `${sign}${SYMBOLS[currency] ?? `${currency} `}${amount}`; +} diff --git a/bench/tasks/T10/verify.ts b/bench/tasks/T10/verify.ts new file mode 100644 index 0000000..ccc3a28 --- /dev/null +++ b/bench/tasks/T10/verify.ts @@ -0,0 +1,83 @@ +import { readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { checkScope, Checks, failedTests, readWorkspaceFile, runHiddenTests, runNodeTests } from '../checks.ts'; +import { filesFrom } from '../setup.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export const T10_FILES = path.join(import.meta.dirname, 'files'); +const HIDDEN = Object.fromEntries(filesFrom(path.join(import.meta.dirname, 'hidden'))); + +/** The top-level arguments of each `formatPrice(...)` call in `source` (strings and nesting respected). */ +export function formatPriceCalls(source: string): string[][] { + const calls: string[][] = []; + // `import { formatPrice as money }` makes `money(` a call of it too. + const aliases = [...source.matchAll(/\bformatPrice\s+as\s+([A-Za-z_$][\w$]*)/g)].map((m) => m[1] as string); + const re = new RegExp(`\\b(?:${['formatPrice', ...aliases].join('|')})\\s*\\(`, 'g'); + for (let m = re.exec(source); m !== null; m = re.exec(source)) { + // A declaration (`function formatPrice(`) is not a call. + if (/(?:function|as)\s+$/.test(source.slice(0, m.index))) continue; + const args: string[] = []; + let depth = 0; + let quote: string | null = null; + let cur = ''; + for (let i = m.index + m[0].length; i < source.length; i++) { + const ch = source[i] as string; + if (quote !== null) { + cur += ch; + if (ch === '\\') { + cur += source[i + 1] ?? ''; + i++; + } else if (ch === quote) quote = null; + continue; + } + if (ch === "'" || ch === '"' || ch === '`') quote = ch; + if (ch === '(' || ch === '{' || ch === '[') depth++; + if (ch === ')' || ch === '}' || ch === ']') { + if (depth === 0) { + if (cur.trim() !== '') args.push(cur.trim()); + break; + } + depth--; + } + if (ch === ',' && depth === 0) { + args.push(cur.trim()); + cur = ''; + continue; + } + cur += ch; + } + calls.push(args); + } + return calls; +} + +async function listJs(workspace: string, dir: string): Promise { + const out: string[] = []; + for (const e of await readdir(path.join(workspace, dir), { withFileTypes: true }).catch(() => [])) { + 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 visible = await runNodeTests(ctx.workspace); + checks.check(visible.ok && visible.fail === 0, `node --test passes (pass ${visible.pass}, fail ${visible.fail})`); + const hidden = await runHiddenTests(ctx.workspace, HIDDEN); + checks.check(hidden.ok && hidden.fail === 0 && hidden.pass > 0, `hidden tests pass (pass ${hidden.pass}, fail ${hidden.fail}${hidden.fail > 0 ? `: ${failedTests(hidden.output).join('; ')}` : ''})`); + // Callers inside the repo use the new form. A variable second argument may hold options (the hidden + // tests judge its behavior); a third argument, a spread or a literal currency/undefined is the old form. + const positional: string[] = []; + for (const file of await listJs(ctx.workspace, 'src')) { + if (file === 'src/index.js') continue; + for (const args of formatPriceCalls((await readWorkspaceFile(ctx.workspace, file)) ?? '')) { + const second = args[1]; + if (args.some((a) => a.startsWith('...')) || args.length > 2 || (second !== undefined && /^(['"`]|undefined$|null$|true$|false$|-?\d)/.test(second))) positional.push(`${file}: formatPrice(${args.join(', ')})`); + } + } + checks.check(positional.length === 0, positional.length === 0 ? 'every formatPrice call in src/ uses the options form' : `positional formatPrice calls left: ${positional.join('; ')}`); + await checkScope(checks, ctx.workspace, ctx.initial, (f) => f.startsWith('src/')); + return checks.result(); +} diff --git a/bench/tasks/T11/files/src/lib/split.js b/bench/tasks/T11/files/src/lib/split.js new file mode 100644 index 0000000..eafa163 --- /dev/null +++ b/bench/tasks/T11/files/src/lib/split.js @@ -0,0 +1,6 @@ +/** + * Splits an amount of cents into integer shares proportional to weights (see the task for the rules). + */ +export function splitCents(totalCents, weights) { + throw new Error('splitCents is not implemented yet'); +} diff --git a/bench/tasks/T11/files/test/split.test.js b/bench/tasks/T11/files/test/split.test.js new file mode 100644 index 0000000..afc8b9b --- /dev/null +++ b/bench/tasks/T11/files/test/split.test.js @@ -0,0 +1,7 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { splitCents } from '../src/lib/split.js'; + +test('splits 100 cents three ways', () => { + assert.deepEqual(splitCents(100, [1, 1, 1]), [34, 33, 33]); +}); diff --git a/bench/tasks/T11/hidden/split-rules.test.js b/bench/tasks/T11/hidden/split-rules.test.js new file mode 100644 index 0000000..f88ce74 --- /dev/null +++ b/bench/tasks/T11/hidden/split-rules.test.js @@ -0,0 +1,85 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { splitCents } from '../src/lib/split.js'; + +const same = (actual, expected) => { + assert.equal(actual.length, expected.length); + actual.forEach((v, i) => assert.ok(Object.is(v, expected[i]), `share ${i}: got ${Object.is(v, -0) ? '-0' : v}, expected ${expected[i]}`)); +}; + +test('largest remainders, ties to the lower index', () => { + same(splitCents(10, [1, 3]), [3, 7]); + same(splitCents(7, [1, 1, 1, 1]), [2, 2, 2, 1]); + same(splitCents(3, [1, 2, 1, 2]), [1, 1, 0, 1]); + same(splitCents(100, [3, 3, 1]), [43, 43, 14]); + same(splitCents(1, [1, 1, 1]), [1, 0, 0]); + same(splitCents(2, [1, 2, 2]), [0, 1, 1]); +}); + +test('sums exactly and keeps zero weights at zero', () => { + same(splitCents(5, [0, 1, 0]), [0, 5, 0]); + const shares = splitCents(99_999, [17, 1, 1, 400, 3]); + assert.equal(shares.reduce((a, b) => a + b, 0), 99_999); + shares.forEach((s) => assert.ok(Number.isInteger(s))); +}); + +test('negative totals mirror positive ones and never give -0', () => { + same(splitCents(-100, [1, 1, 1]), [-34, -33, -33]); + same(splitCents(-1, [1, 1]), [-1, 0]); + same(splitCents(0, [1, 2]), [0, 0]); + same(splitCents(-5, [0, 1]), [0, -5]); +}); + +test('all-zero weights', () => { + same(splitCents(0, [0, 0]), [0, 0]); + assert.throws(() => splitCents(1, [0, 0]), RangeError); + assert.throws(() => splitCents(-1, [0]), RangeError); +}); + +test('invalid input throws RangeError', () => { + for (const [total, weights] of [ + [1.5, [1]], + [Number.NaN, [1]], + [2 ** 53, [1]], + ['10', [1]], + [10, []], + [10, [1, -1]], + [10, [1.5, 1]], + [10, [Number.POSITIVE_INFINITY]], + [10, [Number.NaN]], + ]) { + assert.throws(() => splitCents(total, weights), RangeError, `${String(total)} / ${JSON.stringify(weights)}`); + } +}); + +test('exact for the largest safe totals', () => { + const max = Number.MAX_SAFE_INTEGER; + same(splitCents(max, [1, 2]), [3002399751580330, 6004799503160661]); + same(splitCents(-max, [1, 2]), [-3002399751580330, -6004799503160661]); + same(splitCents(10, [max, 1]), [10, 0]); + // Products past 2^53: floating point loses the cents here. + same(splitCents(max, [2, 3, 5]), [1801439850948198, 2702159776422297, 4503599627370496]); + same(splitCents(max - 1, [7, 11]), [3502799710177052, 5504399544563938]); + same(splitCents(max, [max, max - 1]), [4503599627370496, 4503599627370495]); +}); + +test('does not change the weights array', () => { + const weights = [3, 1, 2]; + splitCents(60, weights); + assert.deepEqual(weights, [3, 1, 2]); +}); + +test('object weights give an object with the same keys, ties in key order', () => { + const out = splitCents(100, { rent: 1, food: 1, fun: 1 }); + assert.deepEqual(Object.keys(out), ['rent', 'food', 'fun']); + assert.deepEqual(out, { rent: 34, food: 33, fun: 33 }); + // Integer-like keys come first in Object.keys order, and that order breaks the ties. + const mixed = splitCents(2, { b: 1, a: 1, 10: 1, 2: 1 }); + assert.deepEqual(Object.keys(mixed), ['2', '10', 'b', 'a']); + assert.deepEqual(mixed, { 2: 1, 10: 1, b: 0, a: 0 }); + assert.ok(Object.is(splitCents(-1, { x: 1, y: 1 }).y, 0)); + assert.deepEqual(splitCents(0, { x: 0 }), { x: 0 }); + assert.throws(() => splitCents(1, {}), RangeError); + assert.throws(() => splitCents(1, { x: -1 }), RangeError); + assert.throws(() => splitCents(1, { x: 0, y: 0 }), RangeError); +}); diff --git a/bench/tasks/T11/solution/apply.ts b/bench/tasks/T11/solution/apply.ts new file mode 100644 index 0000000..7e3a493 --- /dev/null +++ b/bench/tasks/T11/solution/apply.ts @@ -0,0 +1,9 @@ +import { writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; +import { filesFrom } from '../../setup.ts'; + +export async function applySolution(workspace: string, _facts: FixtureFacts): Promise { + for (const [file, text] of filesFrom(path.join(import.meta.dirname, 'files'))) await writeFile(path.join(workspace, ...file.split('/')), text); + return 'Implemented splitCents with BigInt largest-remainder allocation.'; +} diff --git a/bench/tasks/T11/solution/files/src/lib/split.js b/bench/tasks/T11/solution/files/src/lib/split.js new file mode 100644 index 0000000..0cae1ff --- /dev/null +++ b/bench/tasks/T11/solution/files/src/lib/split.js @@ -0,0 +1,32 @@ +/** + * Splits an amount of cents into integer shares proportional to weights (see the task for the rules). + * BigInt arithmetic keeps it exact for every safe-integer total. + */ +export function splitCents(totalCents, weights) { + if (weights !== null && typeof weights === 'object' && !Array.isArray(weights)) { + const keys = Object.keys(weights); + if (keys.length === 0) throw new RangeError('weights must not be empty'); + const shares = splitCents(totalCents, keys.map((k) => weights[k])); + return Object.fromEntries(keys.map((k, i) => [k, shares[i]])); + } + if (!Number.isSafeInteger(totalCents)) throw new RangeError('totalCents must be a safe integer'); + if (!Array.isArray(weights) || weights.length === 0) throw new RangeError('weights must be a non-empty array'); + for (const w of weights) if (!Number.isSafeInteger(w) || w < 0) throw new RangeError('weights must be non-negative safe integers'); + const sum = weights.reduce((s, w) => s + BigInt(w), 0n); + if (sum === 0n) { + if (totalCents !== 0) throw new RangeError('cannot split a non-zero amount with all-zero weights'); + return weights.map(() => 0); + } + const abs = BigInt(Math.abs(totalCents)); + const shares = weights.map((w) => (abs * BigInt(w)) / sum); + const rems = weights.map((w, i) => ({ i, rem: (abs * BigInt(w)) % sum })); + let left = abs - shares.reduce((s, v) => s + v, 0n); + rems.sort((a, b) => (a.rem === b.rem ? a.i - b.i : a.rem > b.rem ? -1 : 1)); + for (const { i } of rems) { + if (left === 0n) break; + shares[i] = (shares[i] ?? 0n) + 1n; + left -= 1n; + } + const sign = totalCents < 0 ? -1 : 1; + return shares.map((s) => (s === 0n ? 0 : sign * Number(s))); +} diff --git a/bench/tasks/T11/verify.ts b/bench/tasks/T11/verify.ts new file mode 100644 index 0000000..0da647f --- /dev/null +++ b/bench/tasks/T11/verify.ts @@ -0,0 +1,18 @@ +import path from 'node:path'; +import { checkScope, Checks, failedTests, runHiddenTests, runNodeTests } from '../checks.ts'; +import { filesFrom } from '../setup.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export const T11_FILES = path.join(import.meta.dirname, 'files'); +const HIDDEN = Object.fromEntries(filesFrom(path.join(import.meta.dirname, 'hidden'))); + +/** Hidden tests cover each rule of the prompt: remainders and ties, -0, invalid input, exactness up to MAX_SAFE_INTEGER. */ +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const visible = await runNodeTests(ctx.workspace); + checks.check(visible.ok && visible.fail === 0, `node --test passes (pass ${visible.pass}, fail ${visible.fail})`); + const hidden = await runHiddenTests(ctx.workspace, HIDDEN); + checks.check(hidden.ok && hidden.fail === 0 && hidden.pass > 0, `hidden tests pass (pass ${hidden.pass}, fail ${hidden.fail}${hidden.fail > 0 ? `: ${failedTests(hidden.output).join('; ')}` : ''})`); + await checkScope(checks, ctx.workspace, ctx.initial, (f) => f === 'src/lib/split.js'); + return checks.result(); +} diff --git a/bench/tasks/T12/logs.ts b/bench/tasks/T12/logs.ts new file mode 100644 index 0000000..69f1b04 --- /dev/null +++ b/bench/tasks/T12/logs.ts @@ -0,0 +1,87 @@ +import type { Tree } from '../../fixture/generate.ts'; +import { Rng } from '../../lib/rng.ts'; + +/** + * T12 log set: 5 services x 16 days of plain-text logs (about 1.3 MB). Exactly one ERROR with code + * PAYMENT_TIMEOUT is logged by payments on the target day; the service that sent that request is only + * in the caller's own log (`call=payments req=`). Decoys: the same code as WARN that day, as ERROR + * on other days, and other ERROR codes that day. Deterministic for a seed. + */ + +export const T12_SERVICES = ['api', 'auth', 'inventory', 'payments', 'shipping'] as const; +export const T12_DAY = '2026-03-14'; +const DAYS = Array.from({ length: 16 }, (_v, i) => `2026-03-${String(i + 1).padStart(2, '0')}`); +const CALLERS = ['api', 'inventory', 'shipping'] as const; +const LINES_PER_FILE = 120; + +export interface T12Logs { + readonly files: Tree; + readonly requestId: string; + readonly upstream: string; +} + +interface Line { + readonly ms: number; + readonly text: string; +} + +export function generateLogs(seed: number): T12Logs { + const rng = new Rng(seed * 31 + 12); + const used = new Set(); + const reqId = (): string => { + for (;;) { + const id = `r-${rng.int(0, 0xffffff).toString(16).padStart(6, '0')}${rng.int(0, 0xff).toString(16).padStart(2, '0')}`; + if (!used.has(id)) { + used.add(id); + return id; + } + } + }; + const files: Tree = new Map(); + let requestId = ''; + let upstream = ''; + for (const day of DAYS) { + const logs = new Map(T12_SERVICES.map((s) => [s, []])); + const at = (ms: number): string => `${day}T${new Date(ms).toISOString().slice(11, 23)}Z`; + const push = (service: string, ms: number, level: string, rest: string): void => { + logs.get(service)?.push({ ms, text: `${at(ms)} ${level.padEnd(5)} ${service} ${rest}` }); + }; + const payment = (ms: number, level: string, outcome: string): string => { + const id = reqId(); + const caller = rng.pick(CALLERS); + push(caller, ms, 'INFO', `req=${id} call=payments path=/v1/charges amount=${rng.int(100, 99_999)}`); + push('payments', ms + rng.int(3, 40), level, `req=${id} ${outcome}`); + return `${id} ${caller}`; + }; + // Ordinary traffic until every file has about LINES_PER_FILE lines. + for (let n = 0; n < LINES_PER_FILE * 3; n++) { + const ms = rng.int(0, 86_399_000); + const roll = rng.next(); + if (roll < 0.35) payment(ms, 'INFO', `status=200 ms=${rng.int(20, 900)}`); + else if (roll < 0.55) push('auth', ms, 'INFO', `req=${reqId()} token=refresh user=u${rng.int(1000, 9999)}`); + else if (roll < 0.7) push('inventory', ms, 'INFO', `req=${reqId()} sku=SKU-${rng.pick(['APPLE', 'BREAD', 'EGGS', 'HONEY'])} reserved=${rng.int(1, 9)}`); + else if (roll < 0.85) push('shipping', ms, 'INFO', `req=${reqId()} label=created zone=${rng.pick(['domestic', 'nearby', 'international'])}`); + else push('api', ms, rng.next() < 0.1 ? 'WARN' : 'INFO', `req=${reqId()} route=/orders status=${rng.pick([200, 200, 201, 404])}`); + } + // Decoys every day: other payment errors, and the target code as a retried WARN. + payment(rng.int(0, 86_399_000), 'ERROR', `code=CARD_DECLINED status=402`); + payment(rng.int(0, 86_399_000), 'WARN', `code=PAYMENT_TIMEOUT attempt=1 retrying=true`); + if (day === T12_DAY) { + payment(rng.int(0, 86_399_000), 'ERROR', `code=GATEWAY_UNAVAILABLE status=503`); + payment(rng.int(0, 86_399_000), 'WARN', `code=PAYMENT_TIMEOUT attempt=2 retrying=true`); + const [id, caller] = payment(rng.int(30_000_000, 70_000_000), 'ERROR', `code=PAYMENT_TIMEOUT attempt=3 retrying=false status=504`).split(' '); + requestId = id ?? ''; + upstream = caller ?? ''; + } else if (rng.next() < 0.5) { + payment(rng.int(0, 86_399_000), 'ERROR', `code=PAYMENT_TIMEOUT attempt=3 retrying=false status=504`); + } + for (const [service, lines] of logs) files.set(`logs/${service}/${day}.log`, `${lines.sort((a, b) => a.ms - b.ms).map((l) => l.text).join('\n')}\n`); + } + return { files, requestId, upstream }; +} + +export function addLogs(tree: Tree, seed: number): Tree { + const out = new Map(tree); + for (const [file, text] of generateLogs(seed).files) out.set(file, text); + return out; +} diff --git a/bench/tasks/T12/solution/apply.ts b/bench/tasks/T12/solution/apply.ts new file mode 100644 index 0000000..16894e5 --- /dev/null +++ b/bench/tasks/T12/solution/apply.ts @@ -0,0 +1,7 @@ +import type { FixtureFacts } from '../../../fixture/generate.ts'; +import { generateLogs } from '../logs.ts'; + +export async function applySolution(_workspace: string, facts: FixtureFacts): Promise { + const { requestId, upstream } = generateLogs(facts.seed); + return `grep found the one PAYMENT_TIMEOUT error in logs/payments, then its request id in the caller's log.\nANSWER: ${requestId}, ${upstream}`; +} diff --git a/bench/tasks/T12/verify.ts b/bench/tasks/T12/verify.ts new file mode 100644 index 0000000..5592ddd --- /dev/null +++ b/bench/tasks/T12/verify.ts @@ -0,0 +1,16 @@ +import { answerBlock, checkScope, Checks } from '../checks.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; +import { generateLogs } from './logs.ts'; + +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const { requestId, upstream } = generateLogs(ctx.facts.seed); + const line = answerBlock(ctx.answer, { lastLine: true }); + if (checks.check(line !== undefined, 'reply ends with an `ANSWER: , ` line') && line !== undefined) { + const parts = line.replace(/[`*]/g, '').split(',').map((p) => p.trim().toLowerCase()); + checks.check(parts[0] === requestId, `request id is ${requestId} (got ${parts[0] ?? 'nothing'})`); + checks.check(parts[1] === upstream, `upstream service is ${upstream} (got ${parts[1] ?? 'nothing'})`); + } + await checkScope(checks, ctx.workspace, ctx.initial); + return checks.result(); +} diff --git a/bench/tasks/T9/files/src/billing/discounts.js b/bench/tasks/T9/files/src/billing/discounts.js new file mode 100644 index 0000000..30a6fad --- /dev/null +++ b/bench/tasks/T9/files/src/billing/discounts.js @@ -0,0 +1,14 @@ +import { withUnitPrice } from './lines.js'; + +/** Volume discount: 10% off the unit price of every line with at least VOLUME_MIN_QTY units (rounded to the cent). */ + +export const VOLUME_MIN_QTY = 5; +export const VOLUME_DISCOUNT_PERCENT = 10; + +export function discountedUnitPrice(unitPriceCents) { + return Math.round((unitPriceCents * (100 - VOLUME_DISCOUNT_PERCENT)) / 100); +} + +export function applyVolumeDiscount(lines) { + return lines.map((line) => (line.qty >= VOLUME_MIN_QTY ? withUnitPrice(line, discountedUnitPrice(line.unitPriceCents)) : line)); +} diff --git a/bench/tasks/T9/files/src/billing/invoice.js b/bench/tasks/T9/files/src/billing/invoice.js new file mode 100644 index 0000000..873f359 --- /dev/null +++ b/bench/tasks/T9/files/src/billing/invoice.js @@ -0,0 +1,11 @@ +import { applyVolumeDiscount } from './discounts.js'; +import { lineItems, lineTotal } from './lines.js'; +import { taxCents } from './tax.js'; + +/** Builds the invoice of one order: discounted lines, subtotal, tax and total, all in cents. */ +export function buildInvoice(order, region = 'domestic') { + const lines = applyVolumeDiscount(lineItems(order)); + const subtotalCents = lines.reduce((sum, line) => sum + lineTotal(line), 0); + const tax = taxCents(subtotalCents, region); + return { orderId: order.id, region, lines, subtotalCents, taxCents: tax, totalCents: subtotalCents + tax }; +} diff --git a/bench/tasks/T9/files/src/billing/lines.js b/bench/tasks/T9/files/src/billing/lines.js new file mode 100644 index 0000000..7dbff42 --- /dev/null +++ b/bench/tasks/T9/files/src/billing/lines.js @@ -0,0 +1,18 @@ +import { normalizeSku } from '../lib/sku.js'; + +/** The billable lines of an order, with normalized SKUs. */ +export function lineItems(order) { + return order.items.map((item) => { + item.sku = normalizeSku(item.sku); + return item; + }); +} + +/** The line at another unit price. */ +export function withUnitPrice(line, unitPriceCents) { + return Object.assign(line, { unitPriceCents }); +} + +export function lineTotal(line) { + return line.qty * line.unitPriceCents; +} diff --git a/bench/tasks/T9/files/src/billing/quote.js b/bench/tasks/T9/files/src/billing/quote.js new file mode 100644 index 0000000..53e2dc3 --- /dev/null +++ b/bench/tasks/T9/files/src/billing/quote.js @@ -0,0 +1,9 @@ +import { applyVolumeDiscount } from './discounts.js'; +import { lineTotal } from './lines.js'; +import { taxCents } from './tax.js'; + +/** Total of a cart quote (lines of { sku, qty, unitPriceCents }), tax included. */ +export function quoteTotal(lines, region = 'domestic') { + const subtotal = applyVolumeDiscount(lines).reduce((sum, line) => sum + lineTotal(line), 0); + return subtotal + taxCents(subtotal, region); +} diff --git a/bench/tasks/T9/files/src/billing/statement.js b/bench/tasks/T9/files/src/billing/statement.js new file mode 100644 index 0000000..60b8029 --- /dev/null +++ b/bench/tasks/T9/files/src/billing/statement.js @@ -0,0 +1,18 @@ +import { buildInvoice } from './invoice.js'; + +/** Statements stop before the invoice that would take the running total over this limit. */ +export const CREDIT_LIMIT_CENTS = 500000; + +/** Builds a customer statement: each invoice is checked against the credit limit, then emitted. */ +export function buildStatement(orders, region = 'domestic') { + const invoices = []; + let totalCents = 0; + for (const order of orders) { + const preview = buildInvoice(order, region); + if (totalCents + preview.totalCents > CREDIT_LIMIT_CENTS) break; + const invoice = buildInvoice(order, region); + invoices.push(invoice); + totalCents += invoice.totalCents; + } + return { region, invoices, totalCents }; +} diff --git a/bench/tasks/T9/files/src/billing/tax.js b/bench/tasks/T9/files/src/billing/tax.js new file mode 100644 index 0000000..0d2fb2e --- /dev/null +++ b/bench/tasks/T9/files/src/billing/tax.js @@ -0,0 +1,13 @@ +/** Sales tax by region, in basis points (1/100 of a percent). */ +const RATES_BP = { domestic: 800, nearby: 1000, international: 0 }; + +export function taxRateBp(region) { + const rate = RATES_BP[region]; + if (rate === undefined) throw new Error(`unknown region: ${region}`); + return rate; +} + +/** Tax on a subtotal, rounded half up to the cent (integer arithmetic, no float drift). */ +export function taxCents(subtotalCents, region) { + return Math.floor((subtotalCents * taxRateBp(region) + 5000) / 10000); +} diff --git a/bench/tasks/T9/files/test/billing.test.js b/bench/tasks/T9/files/test/billing.test.js new file mode 100644 index 0000000..186891b --- /dev/null +++ b/bench/tasks/T9/files/test/billing.test.js @@ -0,0 +1,27 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { buildInvoice } from '../src/billing/invoice.js'; +import { quoteTotal } from '../src/billing/quote.js'; +import { buildStatement } from '../src/billing/statement.js'; + +test('invoice applies the volume discount and the regional tax', () => { + const order = { id: 'ORD-1', items: [{ sku: 'SKU-APPLE', qty: 5, unitPriceCents: 155 }, { sku: 'SKU-BREAD', qty: 1, unitPriceCents: 300 }] }; + const invoice = buildInvoice(order, 'nearby'); + assert.equal(invoice.subtotalCents, 5 * 140 + 300); + assert.equal(invoice.taxCents, 100); + assert.equal(invoice.totalCents, 1100); +}); + +test('quote totals a cart', () => { + assert.equal(quoteTotal([{ sku: 'SKU-EGGS', qty: 2, unitPriceCents: 250 }], 'domestic'), 540); +}); + +test('statement lists the invoices of small orders', () => { + const orders = [ + { id: 'ORD-2', items: [{ sku: 'SKU-HONEY', qty: 1, unitPriceCents: 1000 }] }, + { id: 'ORD-3', items: [{ sku: 'SKU-DATES', qty: 2, unitPriceCents: 450 }] }, + ]; + const statement = buildStatement(orders, 'international'); + assert.deepEqual(statement.invoices.map((i) => i.totalCents), [1000, 900]); + assert.equal(statement.totalCents, 1900); +}); diff --git a/bench/tasks/T9/hidden/billing-consistency.test.js b/bench/tasks/T9/hidden/billing-consistency.test.js new file mode 100644 index 0000000..258ad8e --- /dev/null +++ b/bench/tasks/T9/hidden/billing-consistency.test.js @@ -0,0 +1,75 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { applyVolumeDiscount } from '../src/billing/discounts.js'; +import { buildInvoice } from '../src/billing/invoice.js'; +import { quoteTotal } from '../src/billing/quote.js'; +import { buildStatement, CREDIT_LIMIT_CENTS } from '../src/billing/statement.js'; + +const bulk = () => ({ + id: 'ORD-B', + items: [ + { sku: 'SKU-APPLE', qty: 6, unitPriceCents: 1999 }, + { sku: 'SKU-FLOUR', qty: 2, unitPriceCents: 450 }, + { sku: 'SKU-EGGS', qty: 12, unitPriceCents: 35 }, + ], +}); +const small = () => ({ id: 'ORD-S', items: [{ sku: 'SKU-HONEY', qty: 1, unitPriceCents: 1200 }] }); + +test('a bulk invoice has the documented totals', () => { + const inv = buildInvoice(bulk(), 'domestic'); + // 6 * 1799 + 2 * 450 + 12 * 32 = 10794 + 900 + 384 + assert.equal(inv.subtotalCents, 12078); + assert.equal(inv.taxCents, 966); + assert.equal(inv.totalCents, 13044); +}); + +test('building an invoice twice from the same order gives the same invoice', () => { + const order = bulk(); + const first = buildInvoice(order, 'nearby'); + const second = buildInvoice(order, 'nearby'); + assert.equal(second.totalCents, first.totalCents); + assert.deepEqual(second, first); +}); + +test('building an invoice leaves the order unchanged', () => { + const order = bulk(); + const before = structuredClone(order); + buildInvoice(order, 'domestic'); + assert.deepEqual(order, before); +}); + +test('statement invoices match invoices built on their own', () => { + const orders = [bulk(), small(), { ...bulk(), id: 'ORD-C' }]; + const alone = orders.map((o) => buildInvoice(structuredClone(o), 'nearby').totalCents); + const statement = buildStatement(orders, 'nearby'); + assert.deepEqual(statement.invoices.map((i) => i.totalCents), alone); + assert.equal(statement.totalCents, alone.reduce((a, b) => a + b, 0)); + // And an invoice built after the statement is still the same. + assert.equal(buildInvoice(orders[0], 'nearby').totalCents, alone[0]); +}); + +test('statement still stops at the credit limit', () => { + const big = (id) => ({ id, items: [{ sku: 'SKU-CHEESE', qty: 10, unitPriceCents: 20000 }] }); + const one = buildInvoice(big('X'), 'international').totalCents; + assert.equal(one, 180000); + const statement = buildStatement([big('O1'), big('O2'), big('O3'), big('O4')], 'international'); + assert.equal(statement.invoices.length, Math.floor(CREDIT_LIMIT_CENTS / one)); + assert.equal(statement.totalCents, statement.invoices.length * one); +}); + +test('quoting the same cart twice gives the same total and leaves the cart unchanged', () => { + const cart = [{ sku: 'SKU-GRAPES', qty: 5, unitPriceCents: 999 }]; + const before = structuredClone(cart); + const first = quoteTotal(cart, 'domestic'); + assert.equal(first, 5 * 899 + Math.floor((5 * 899 * 800 + 5000) / 10000)); + assert.equal(quoteTotal(cart, 'domestic'), first); + assert.deepEqual(cart, before); +}); + +test('applyVolumeDiscount does not modify the lines it is given', () => { + const lines = [{ sku: 'SKU-APPLE', qty: 5, unitPriceCents: 155 }, { sku: 'SKU-BREAD', qty: 4, unitPriceCents: 300 }]; + const before = structuredClone(lines); + const out = applyVolumeDiscount(lines); + assert.deepEqual(lines, before); + assert.deepEqual(out.map((l) => l.unitPriceCents), [140, 300]); +}); diff --git a/bench/tasks/T9/solution/apply.ts b/bench/tasks/T9/solution/apply.ts new file mode 100644 index 0000000..3268538 --- /dev/null +++ b/bench/tasks/T9/solution/apply.ts @@ -0,0 +1,9 @@ +import { writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; +import { filesFrom } from '../../setup.ts'; + +export async function applySolution(workspace: string, _facts: FixtureFacts): Promise { + for (const [file, text] of filesFrom(path.join(import.meta.dirname, 'files'))) await writeFile(path.join(workspace, ...file.split('/')), text); + return 'withUnitPrice (src/billing/lines.js) wrote the discounted price into the line it was given, so the discount changed the order items and every later invoice of the order was discounted again. It now returns a copy.'; +} diff --git a/bench/tasks/T9/solution/files/src/billing/discounts.js b/bench/tasks/T9/solution/files/src/billing/discounts.js new file mode 100644 index 0000000..30a6fad --- /dev/null +++ b/bench/tasks/T9/solution/files/src/billing/discounts.js @@ -0,0 +1,14 @@ +import { withUnitPrice } from './lines.js'; + +/** Volume discount: 10% off the unit price of every line with at least VOLUME_MIN_QTY units (rounded to the cent). */ + +export const VOLUME_MIN_QTY = 5; +export const VOLUME_DISCOUNT_PERCENT = 10; + +export function discountedUnitPrice(unitPriceCents) { + return Math.round((unitPriceCents * (100 - VOLUME_DISCOUNT_PERCENT)) / 100); +} + +export function applyVolumeDiscount(lines) { + return lines.map((line) => (line.qty >= VOLUME_MIN_QTY ? withUnitPrice(line, discountedUnitPrice(line.unitPriceCents)) : line)); +} diff --git a/bench/tasks/T9/solution/files/src/billing/lines.js b/bench/tasks/T9/solution/files/src/billing/lines.js new file mode 100644 index 0000000..af0adc4 --- /dev/null +++ b/bench/tasks/T9/solution/files/src/billing/lines.js @@ -0,0 +1,18 @@ +import { normalizeSku } from '../lib/sku.js'; + +/** The billable lines of an order, with normalized SKUs. */ +export function lineItems(order) { + return order.items.map((item) => { + item.sku = normalizeSku(item.sku); + return item; + }); +} + +/** The line at another unit price. */ +export function withUnitPrice(line, unitPriceCents) { + return { ...line, unitPriceCents }; +} + +export function lineTotal(line) { + return line.qty * line.unitPriceCents; +} diff --git a/bench/tasks/T9/verify.ts b/bench/tasks/T9/verify.ts new file mode 100644 index 0000000..ffdddc3 --- /dev/null +++ b/bench/tasks/T9/verify.ts @@ -0,0 +1,18 @@ +import path from 'node:path'; +import { checkScope, Checks, failedTests, runHiddenTests, runNodeTests } from '../checks.ts'; +import { filesFrom } from '../setup.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export const T9_FILES = path.join(import.meta.dirname, 'files'); +const HIDDEN = Object.fromEntries(filesFrom(path.join(import.meta.dirname, 'hidden'))); + +/** Hidden tests check consistency across every caller (invoice twice, statement, quote, the discount itself), not just the reported symptom. */ +export async function verify(ctx: VerifyContext): Promise { + const checks = new Checks(); + const visible = await runNodeTests(ctx.workspace); + checks.check(visible.ok && visible.fail === 0, `node --test passes (pass ${visible.pass}, fail ${visible.fail})`); + const hidden = await runHiddenTests(ctx.workspace, HIDDEN); + checks.check(hidden.ok && hidden.fail === 0 && hidden.pass > 0, `hidden tests pass (pass ${hidden.pass}, fail ${hidden.fail}${hidden.fail > 0 ? `: ${failedTests(hidden.output).join('; ')}` : ''})`); + await checkScope(checks, ctx.workspace, ctx.initial, (f) => f.startsWith('src/billing/')); + return checks.result(); +} diff --git a/bench/tasks/checks.ts b/bench/tasks/checks.ts index e258b9c..2c559fe 100644 --- a/bench/tasks/checks.ts +++ b/bench/tasks/checks.ts @@ -1,5 +1,6 @@ import { spawn } from 'node:child_process'; -import { readdir, readFile } from 'node:fs/promises'; +import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; import path from 'node:path'; import type { VerifyResult } from './types.ts'; @@ -61,10 +62,10 @@ export interface NodeTestRun { 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 { +/** Runs `node --test` in the workspace (same Node as the harness), with a timeout; `files` limits it to those test files. */ +export function runNodeTests(workspace: string, timeoutMs = 60_000, files: readonly string[] = []): Promise { return new Promise((resolve) => { - const child = spawn(process.execPath, ['--test', '--test-reporter=spec'], { cwd: workspace, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NODE_OPTIONS: '' } }); + const child = spawn(process.execPath, ['--test', '--test-reporter=spec', ...files], { 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'))); @@ -152,3 +153,30 @@ export async function checkScope(checks: Checks, workspace: string, initial: Rea checks.check(outside.length === 0, outside.length === 0 ? 'no file outside the task changed' : `changed outside the task: ${outside.join(', ')}`); if (c.added.length > 0) checks.check(true, `new files (allowed): ${c.added.join(', ')}`); } + +/** + * Runs hidden tests: tests the agent never saw. The workspace is copied (without `.git`) to a temporary + * directory, the hidden files are added there under `hidden-tests/`, and only they run. The workspace + * itself is never written, so the recorded diff is the agent's alone. + */ +export async function runHiddenTests(workspace: string, hidden: Readonly>, timeoutMs = 60_000): Promise { + const dir = await mkdtemp(path.join(os.tmpdir(), 'acm-hidden-')); + try { + await cp(workspace, dir, { recursive: true, filter: (src) => path.basename(src) !== '.git' }); + await mkdir(path.join(dir, 'hidden-tests'), { recursive: true }); + const files: string[] = []; + for (const [name, text] of Object.entries(hidden)) { + const rel = `hidden-tests/${name}`; + await writeFile(path.join(dir, rel), text); + files.push(rel); + } + return await runNodeTests(dir, timeoutMs, files); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +/** Failing test names from spec-reporter output (lines starting with the cross mark). */ +export function failedTests(output: string): string[] { + return [...new Set([...output.matchAll(/^\s*✖ (.+?)(?: \([\d.]+m?s\))?$/gm)].map((m) => (m[1] ?? '').trim()))].filter((n) => n !== '' && !/^failing tests:?$/.test(n)); +} diff --git a/bench/tasks/index.ts b/bench/tasks/index.ts index 0297985..05eb3ee 100644 --- a/bench/tasks/index.ts +++ b/bench/tasks/index.ts @@ -1,6 +1,6 @@ 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 { addFiles, 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'; @@ -10,6 +10,11 @@ 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 { T9_FILES, verify as verifyT9 } from './T9/verify.ts'; +import { T10_FILES, verify as verifyT10 } from './T10/verify.ts'; +import { T11_FILES, verify as verifyT11 } from './T11/verify.ts'; +import { verify as verifyT12 } from './T12/verify.ts'; +import { addLogs, T12_DAY } from './T12/logs.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'; @@ -18,6 +23,10 @@ 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'; +import { applySolution as solveT9 } from './T9/solution/apply.ts'; +import { applySolution as solveT10 } from './T10/solution/apply.ts'; +import { applySolution as solveT11 } from './T11/solution/apply.ts'; +import { applySolution as solveT12 } from './T12/solution/apply.ts'; const same = (tree: Tree): Tree => tree; @@ -106,6 +115,64 @@ export const TASKS: Readonly> = { verify: verifyT8, solution: solveT8, }, + // T9-T12 add their own files in setup (the shared fixture stays as it is) and T9-T11 grade with hidden + // tests that are never in the workspace: they are meant not to saturate. + T9: { + id: 'T9', + title: 'bug whose cause is two modules away from the symptom', + size: 'debug', + hiddenTests: true, + prompt: () => + 'Support reports that billing totals drift. `buildStatement` (src/billing/statement.js) lists lower invoice totals than `buildInvoice` gives for the same order, but only for orders with bulk lines (qty >= 5); and after a statement has been built, invoices for those orders come out lower too. The discount and tax rules themselves are correct. Find the root cause and fix it there. Keep `node --test` passing and do not edit the tests.', + setup: addFiles(T9_FILES), + protectedHook: false, + verify: verifyT9, + solution: solveT9, + }, + T10: { + id: 'T10', + title: 'multi-file signature refactor with a public contract to keep', + size: 'refactor', + hiddenTests: true, + prompt: () => + "Change `formatPrice` in src/lib/price.js from positional parameters, `formatPrice(cents, currency = 'USD', withSymbol = true)`, to an options object: `formatPrice(cents, { currency = 'USD', symbol = true } = {})`. Update every caller in src/ to the new form so that every output stays exactly the same. src/index.js is the public API and code outside this repository still calls `formatPrice(cents, currency, withSymbol)` through it, so the `formatPrice` exported from src/index.js must keep accepting the old positional form, with the same results, as well as the new options form. Keep `node --test` passing and do not edit the tests.", + setup: addFiles(T10_FILES), + protectedHook: false, + verify: verifyT10, + solution: solveT10, + }, + T11: { + id: 'T11', + title: 'small feature with edge cases', + size: 'feature', + hiddenTests: true, + prompt: () => + [ + 'Implement `splitCents(totalCents, weights)` in src/lib/split.js. Rules:', + '1. It returns an array of integers, one per weight, that sums exactly to totalCents.', + '2. Each share starts at floor(|totalCents| * weight / sum of weights); the cents left over go one each to the shares with the largest fractional remainders, ties going to the lower index.', + '3. A negative totalCents is split as its absolute value and every share negated; a share is never -0.', + '4. totalCents must be a safe integer and weights a non-empty array of non-negative safe integers; anything else throws a RangeError. If every weight is 0, it returns all zeros when totalCents is 0 and throws a RangeError otherwise.', + '5. The result is exact for every safe-integer total, up to Number.MAX_SAFE_INTEGER, with no floating-point error.', + '6. weights may also be a plain object of name to weight. The result is then an object with the same keys, in Object.keys order, and that order is the index order of rule 2. The rules of 4 apply to its values; an object with no keys throws a RangeError.', + 'test/split.test.js covers the basic case. Keep `node --test` passing and do not edit the tests.', + ].join('\n'), + setup: addFiles(T11_FILES), + protectedHook: false, + verify: verifyT11, + solution: solveT11, + }, + T12: { + id: 'T12', + title: 'one fact in 80 log files (reading everything is expensive)', + size: 'long-read', + prompt: () => + `The logs/ directory has one log file per service and day. On ${T12_DAY} the payments service logged exactly one ERROR with code PAYMENT_TIMEOUT. Which request id was it, and which service sent that request to payments? Do not change any file. End your reply with a line \`ANSWER: , \`.`, + setup: (tree, facts) => addLogs(tree, facts.seed), + protectedHook: false, + verify: verifyT12, + solution: solveT12, + }, }; /** Directory of the example PreToolUse hook used by T8. */ diff --git a/bench/tasks/setup.ts b/bench/tasks/setup.ts index f21fc47..f045b8a 100644 --- a/bench/tasks/setup.ts +++ b/bench/tasks/setup.ts @@ -1,3 +1,5 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; import type { Tree } from '../fixture/generate.ts'; import { getFile, replaceOnce } from './checks.ts'; @@ -18,3 +20,26 @@ export function injectBugs(tree: Tree, bugs: readonly { readonly file: string; r for (const b of bugs) out.set(b.file, replaceOnce(getFile(out, b.file), b.fix, b.bug, b.file)); return out; } + +/** Files under `dir`, keyed by POSIX path relative to it (task setup files, hidden tests, solution files). */ +export function filesFrom(dir: string): Map { + const out = new Map(); + for (const e of readdirSync(dir, { recursive: true, withFileTypes: true })) { + if (!e.isFile()) continue; + const abs = path.join(e.parentPath, e.name); + out.set(path.relative(dir, abs).split(path.sep).join('/'), readFileSync(abs, 'utf8')); + } + return new Map([...out.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); +} + +/** A task setup that adds the files of `dir` to the fixture (failing loudly if one already exists). */ +export function addFiles(dir: string): (tree: Tree) => Tree { + return (tree) => { + const out = new Map(tree); + for (const [file, text] of filesFrom(dir)) { + if (out.has(file)) throw new Error(`task file ${file} already exists in the fixture`); + out.set(file, text); + } + return out; + }; +} diff --git a/bench/tasks/types.ts b/bench/tasks/types.ts index 5c8f8f8..99d6849 100644 --- a/bench/tasks/types.ts +++ b/bench/tasks/types.ts @@ -1,7 +1,7 @@ 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 type TaskId = 'T1' | 'T2' | 'T3' | 'T4' | 'T5' | 'T6' | 'T7' | 'T8' | 'T9' | 'T10' | 'T11' | 'T12'; +export const TASK_IDS: readonly TaskId[] = ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12']; export interface VerifyContext { /** Absolute path of the final workspace. */ @@ -32,7 +32,9 @@ export type Solution = (workspace: string, facts: FixtureFacts) => Promise {}, 1000); else { @@ -128,8 +130,8 @@ async function cleanup(h: Harness): Promise { await rm(h.root, { recursive: true, force: true }); } -async function findFile(dir: string, name: string): Promise { - const files = (await readdir(dir, { recursive: true })).filter((f) => path.basename(f) === name); +async function findFile(dir: string, name: string, under?: string): Promise { + const files = (await readdir(dir, { recursive: true })).filter((f) => path.basename(f) === name && (under === undefined || f.split(path.sep).includes(under))); if (files[0] === undefined) throw new Error(`no ${name} under ${dir}`); return readFile(path.join(dir, files[0]), 'utf8'); } @@ -188,7 +190,9 @@ describe.skipIf(!posix)('temporary CODEX_HOME: token refresh on a finished run', expect(await readFile(h.realAuth, 'utf8')).toBe(REFRESHED); expect((await stat(h.realAuth)).mode & 0o777).toBe(0o600); expect(await authFiles(h.work)).toEqual([]); - expect(await findFile(path.join(h.root, 'results'), 'auth.txt')).toBe('auth.json: written-back\n'); + // The warmup run is the one that refreshed; the matrix run after it found nothing to write back. + expect(await findFile(path.join(h.root, 'results'), 'auth.txt', 'warmup')).toBe('auth.json: written-back\n'); + expect(await findFile(path.join(h.root, 'results'), 'auth.txt', 'codex')).toBe('auth.json: unchanged\n'); } finally { await cleanup(h); } @@ -199,7 +203,7 @@ describe.skipIf(!posix)('temporary CODEX_HOME: token refresh on a finished run', try { expect(await readFile(h.realAuth, 'utf8')).toBe(OTHER); expect(h.stderr).toContain('kept the real file'); - expect(await findFile(path.join(h.root, 'results'), 'auth.txt')).toBe('auth.json: conflict-kept-real\n'); + expect(await findFile(path.join(h.root, 'results'), 'auth.txt', 'warmup')).toBe('auth.json: conflict-kept-real\n'); expect(await authFiles(h.work)).toEqual([]); } finally { await cleanup(h); diff --git a/bench/test/parsers.test.ts b/bench/test/parsers.test.ts index 4e8c298..5661d7c 100644 --- a/bench/test/parsers.test.ts +++ b/bench/test/parsers.test.ts @@ -14,6 +14,7 @@ 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.requests).toBe(2); expect(p.hostDurationMs).toBe(2414); expect(p.usage).toEqual({ input: 4, output: 171, cacheCreation: 2187, cacheRead: 12187, reasoning: 0 }); expect(p.hostCostUsd).toBeCloseTo(0.0116847, 10); @@ -236,3 +237,20 @@ describe('Codex transcript parser', () => { expect(codexToolSurface(input)).toEqual(['functions.exec_command', 'functions.apply_patch', 'tool_search']); }); }); + +describe('model requests', () => { + it('counts distinct Claude assistant message ids, not num_turns', () => { + const usage = { input_tokens: 2, output_tokens: 5, cache_creation_input_tokens: 0, cache_read_input_tokens: 10 }; + const lines = [ + { type: 'assistant', message: { id: 'msg_1', usage, content: [{ type: 'tool_use', id: 't1', name: 'Edit', input: {} }] } }, + { type: 'assistant', message: { id: 'msg_1', usage, content: [{ type: 'tool_use', id: 't2', name: 'Edit', input: {} }] } }, + { type: 'assistant', message: { id: 'msg_1', usage, content: [{ type: 'tool_use', id: 't3', name: 'Edit', input: {} }] } }, + { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] } }, + { type: 'assistant', message: { id: 'msg_2', usage, content: [{ type: 'text', text: 'done' }] } }, + { type: 'result', subtype: 'success', is_error: false, num_turns: 4, duration_ms: 10, total_cost_usd: 0.001, result: 'done', usage }, + ]; + const p = parseClaudeTranscript(lines.map((l) => JSON.stringify(l)).join('\n')); + expect(p.turns).toBe(4); + expect(p.requests).toBe(2); + }); +}); diff --git a/bench/test/report.test.ts b/bench/test/report.test.ts index 9fab73e..9bdd1dc 100644 --- a/bench/test/report.test.ts +++ b/bench/test/report.test.ts @@ -3,11 +3,12 @@ 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 { latestResultsDir, markdownTable, summarize, writeReport } from '../report.ts'; +import { pairedBootstrap, passHatK, spread } from '../lib/stats.ts'; +import { compareArms, latestResultsDir, markdownTable, summarize, summarizeArms, writeReport, type Summary } from '../report.ts'; +import { Rng } from '../lib/rng.ts'; -function record(over: Partial & { turns?: number; cost?: number }): RunRecord { - const { turns = 2, cost = 0.01, ...rest } = over; +function record(over: Partial & { turns?: number; cost?: number; pass?: boolean }): RunRecord { + const { turns = 2, cost = 0.01, pass, ...rest } = over; return RunRecordSchema.parse({ schema: 1, id: `claude-T1-A-r${rest.run ?? 1}`, @@ -29,6 +30,7 @@ function record(over: Partial & { turns?: number; cost?: number }): R wallMs: 1000 * turns, parsed: { turns, + requests: turns, hostDurationMs: 100, usage: { input: 10 * turns, output: turns, cacheCreation: 0, cacheRead: 100, reasoning: null }, hostCostUsd: cost, @@ -43,7 +45,7 @@ function record(over: Partial & { turns?: number; cost?: number }): R parseError: null, costUsd: cost, costSource: 'host', - verify: { pass: true, details: ['ok'] }, + verify: pass === false ? { pass: false, details: ['FAIL x'] } : { pass: true, details: ['ok'] }, fallback: false, valid: true, invalidReasons: [], @@ -52,6 +54,10 @@ function record(over: Partial & { turns?: number; cost?: number }): R }); } +function emptySummary(over: Partial): Summary { + return { generatedAt: '', dryRun: false, environment: null, groups: [], arms: [], comparisons: [], bootstrap: { seed: 1, iterations: 1, method: '' }, warmup: { runs: 0, costUsd: 0, runIds: [] }, ...over }; +} + describe('stats', () => { it('computes median, min and max', () => { expect(spread([5, 2, 3])).toEqual({ median: 3, min: 2, max: 5, n: 3 }); @@ -87,7 +93,7 @@ describe('report', () => { it('never pools runs made with different configs', () => { const groups = summarize([record({ run: 1, turns: 2 }), record({ run: 2, turns: 50, configHash: 'bbbbbbbbbbbb', config: { model: 'claude-haiku-5-5' } })]); expect(groups.map((g) => [g.configHash, g.turns?.median])).toEqual([['aaaaaaaaaaaa', 2], ['bbbbbbbbbbbb', 50]]); - expect(markdownTable({ generatedAt: '', dryRun: false, environment: null, groups })).toContain('different configs'); + expect(markdownTable(emptySummary({ groups }))).toContain('different configs'); }); it('bench:report defaults to the newest date directory', async () => { @@ -114,7 +120,7 @@ describe('report', () => { 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 | aaaaaaaaaaaa | 100% | 3 (2–7) |'); + expect(markdown).toContain('| claude | T1 | A native tools | aaaaaaaaaaaa | 100% | 100% | 3 (2–7) | 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'); @@ -123,3 +129,97 @@ describe('report', () => { } }); }); + +describe('pass^k and bootstrap', () => { + it('pass^k is C(c,k)/C(n,k) and refuses k above the runs', () => { + expect(passHatK(3, 3, 3)).toBe(1); + expect(passHatK(2, 3, 3)).toBe(0); + expect(passHatK(2, 3, 1)).toBeCloseTo(2 / 3, 12); + expect(passHatK(3, 4, 2)).toBeCloseTo(3 / 6, 12); + expect(passHatK(0, 5, 1)).toBe(0); + expect(() => passHatK(3, 3, 4)).toThrow(RangeError); + }); + + it('a constant per-task difference gives a zero-width interval at that value', () => { + const tasks = [0.01, 0.02, 0.05].map((base) => ({ a: [base, base + 0.002], b: [base + 0.003, base + 0.005] })); + const ci = pairedBootstrap(tasks, { seed: 1, iterations: 2000 }); + expect(ci?.estimate).toBeCloseTo(0.003, 12); + expect(ci?.lo).toBeCloseTo(0.003, 12); + expect(ci?.hi).toBeCloseTo(0.003, 12); + expect(ci?.crossesZero).toBe(false); + }); + + it('two tasks with differences 0 and 1: the bootstrap distribution is {0, .5, 1} with 1/4, 1/2, 1/4', () => { + const ci = pairedBootstrap([{ a: [0], b: [0] }, { a: [0], b: [1] }], { seed: 3, iterations: 20_000 }); + expect(ci?.estimate).toBe(0.5); + expect(ci?.lo).toBe(0); + expect(ci?.hi).toBe(1); + expect(ci?.crossesZero).toBe(true); + }); + + it('matches the normal-theory interval of a mean on many tasks', () => { + const rng = new Rng(11); + // Per-task differences uniform on [0, 1): mean 0.5, sd 1/sqrt(12); 400 tasks -> half-width 1.96 * 0.2887 / 20. + const diffs = Array.from({ length: 400 }, () => rng.next()); + const tasks = diffs.map((d) => ({ a: [1], b: [1 + d] })); + const ci = pairedBootstrap(tasks, { seed: 5, iterations: 4000 }); + const m = diffs.reduce((s, d) => s + d, 0) / diffs.length; + const sd = Math.sqrt(diffs.reduce((s, d) => s + (d - m) ** 2, 0) / (diffs.length - 1)); + const half = (1.96 * sd) / Math.sqrt(diffs.length); + expect(ci?.estimate).toBeCloseTo(m, 12); + expect(Math.abs((ci?.lo ?? 0) - (m - half))).toBeLessThan(0.004); + expect(Math.abs((ci?.hi ?? 0) - (m + half))).toBeLessThan(0.004); + }); + + it('is deterministic for a seed, weighs tasks equally and needs two tasks', () => { + const tasks = [{ a: [1, 2, 3], b: [2] }, { a: [5], b: [4, 4, 4, 4] }, { a: [0], b: [3] }]; + expect(pairedBootstrap(tasks, { seed: 9 })).toEqual(pairedBootstrap(tasks, { seed: 9 })); + expect(pairedBootstrap(tasks, { seed: 9 })?.estimate).toBeCloseTo((0 + -1 + 3) / 3, 12); + expect(pairedBootstrap([{ a: [1], b: [2] }], { seed: 1 })).toBeNull(); + }); +}); + +describe('quality metrics', () => { + const cell = (task: string, arm: 'A' | 'B', passes: boolean[], cost: number) => + passes.map((pass, i) => record({ id: `claude-${task}-${arm}-r${i + 1}`, task, arm, run: i + 1, pass, cost, configHash: arm === 'A' ? 'aaaaaaaaaaaa' : 'bbbbbbbbbbbb', config: { model: 'm', task, arm } })); + + it('cost per solved task charges the failed runs too', () => { + const [g] = summarize(cell('T9', 'A', [true, false, true, false], 0.05)); + expect(g?.passRate).toBe(0.5); + expect(g?.passAll).toBe(0); + expect(g?.costPerSolvedUsd).toBeCloseTo(0.2 / 2, 12); + expect(summarize(cell('T9', 'A', [false, false], 0.05))[0]?.costPerSolvedUsd).toBeNull(); + }); + + it('aggregates arms per cohort with one k, and compares arms paired by task', () => { + const records = [ + ...cell('T9', 'A', [true, true, false], 0.04), + ...cell('T9', 'B', [true, true, true], 0.03), + ...cell('T10', 'A', [false, false, false], 0.06), + ...cell('T10', 'B', [true, false, true], 0.05), + ...cell('T11', 'A', [true, true, true], 0.02), + ...cell('T11', 'B', [true, true, true], 0.01), + record({ id: 'warmup-claude-T1-A-r1', warmup: true, cost: 5 }), + ]; + const arms = summarizeArms(records); + expect(arms.map((a) => a.arm)).toEqual(['A', 'B']); + const [a, b] = arms; + expect(new Set(arms.map((x) => x.cohort)).size).toBe(1); + expect(a?.tasks).toBe(3); + expect(a?.pass1).toBeCloseTo((2 / 3 + 0 + 1) / 3, 12); + expect(a?.passHatK).toEqual({ k: 3, value: (0 + 0 + 1) / 3 }); + expect(b?.passHatK).toEqual({ k: 3, value: (1 + 0 + 1) / 3 }); + expect(a?.costPerSolvedUsd).toBeCloseTo((0.12 + 0.18 + 0.06) / 5, 12); + expect(b?.costPerRunUsd).toBeCloseTo(0.03, 12); + const [cmp] = compareArms(records, 1, 2000); + expect(cmp).toMatchObject({ arm: 'B', reference: 'A', tasks: ['T10', 'T11', 'T9'] }); + expect(cmp?.costUsd).toMatchObject({ lo: expect.closeTo(-0.01, 12), hi: expect.closeTo(-0.01, 12), crossesZero: false }); + expect(cmp?.pass?.estimate).toBeCloseTo((1 / 3 + 2 / 3 + 0) / 3, 12); + const md = markdownTable(emptySummary({ groups: summarize(records), arms, comparisons: compareArms(records, 1, 2000), warmup: { runs: 1, costUsd: 5, runIds: [] } })); + expect(md).toContain('| claude | ' + (a?.cohort ?? '') + ' | B vs A | 3 | +33.3 pp ['); + expect(md).toMatch(/B vs A \| 3 \| [^|]*CI crosses 0[^|]*\| -\$0\.0100 \[-\$0\.0100, -\$0\.0100\] \|/); + expect(md).toContain('Warmup: 1 run(s), $5.0000'); + // The warmup record never enters a group. + expect(summarize(records).some((g) => g.task === 'T1')).toBe(false); + }); +}); diff --git a/bench/test/run.test.ts b/bench/test/run.test.ts index e866b21..bc43306 100644 --- a/bench/test/run.test.ts +++ b/bench/test/run.test.ts @@ -1,10 +1,13 @@ -import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } 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'; +import { assertWorkspaceIsolated, defaultWorkDir, insideRepo, main, parseOptions, planRuns, planWarmup, REPO_ROOT, resolveBaseline, WARMUP_TASK, type PlannedRun } from '../run.ts'; +import { Rng } from '../lib/rng.ts'; +import { TASK_IDS, type TaskId } from '../tasks/types.ts'; describe('options', () => { it('has the documented defaults', () => { @@ -14,21 +17,89 @@ describe('options', () => { 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(['--tasks', 'T99'])).toThrow(); + expect(parseOptions(['--arms', 'A,B0']).arms).toEqual(['A', 'B0']); + expect(() => parseOptions(['--acm-ref', 'HEAD', '--acm-dist', 'x'])).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); +/** Splits a plan into its maximal runs of consecutive entries with the same round, host and task. */ +function blocks(plan: readonly PlannedRun[]): PlannedRun[][] { + const out: PlannedRun[][] = []; + for (const p of plan) { + const last = out.at(-1); + const head = last?.[0]; + if (last !== undefined && head !== undefined && head.round === p.round && head.host === p.host && head.task === p.task) last.push(p); + else out.push([p]); + } + return out; +} + +describe('paired schedule', () => { + const cases: { hosts: ('claude' | 'codex')[]; tasks: TaskId[]; runs: number; seed: number; baseline: boolean }[] = []; + const rng = new Rng(99); + for (let i = 0; i < 60; i++) { + const hosts = rng.pick([['claude'], ['codex'], ['claude', 'codex']] as ('claude' | 'codex')[][]); + const tasks = rng.shuffle(TASK_IDS).slice(0, rng.int(1, 6)); + cases.push({ hosts, tasks, runs: rng.int(1, 9), seed: rng.int(0, 2 ** 31), baseline: rng.next() < 0.5 }); + } + + it('keeps every arm of a host x task together in each round, each arm exactly once', () => { + for (const c of cases) { + const plan = planRuns(c.hosts, c.tasks, undefined, c.runs, c.seed, c.baseline); + const bs = blocks(plan); + // One block per round x host x task: the arms of a task never get split by another task's run. + expect(bs).toHaveLength(c.runs * c.hosts.length * c.tasks.length); + for (const b of bs) { + const host = b[0]?.host ?? 'claude'; + const expected = host === 'claude' ? (c.baseline ? ['A', 'B', 'B0'] : ['A', 'B']) : c.baseline ? ['A', 'B', 'C', 'C0'] : ['A', 'B', 'C']; + expect(b.map((p) => p.arm).sort()).toEqual(expected); + expect(b.map((p) => p.position)).toEqual(expected.map((_a, i) => i)); + } + expect(plan.map((p) => p.orderIndex)).toEqual(plan.map((_p, i) => i)); + expect(plan.every((p) => p.run === p.round)).toBe(true); + } + }); + + it('balances the order: each arm takes each position equally often, within one, over the rounds', () => { + for (const c of cases) { + const plan = planRuns(c.hosts, c.tasks, undefined, c.runs, c.seed, c.baseline); + const counts = new Map(); + for (const p of plan) { + const key = `${p.host}|${p.task}|${p.arm}`; + const k = plan.filter((q) => q.host === p.host && q.task === p.task && q.round === p.round).length; + const row = counts.get(key) ?? Array.from({ length: k }, () => 0); + row[p.position] = (row[p.position] ?? 0) + 1; + counts.set(key, row); + } + for (const row of counts.values()) { + expect(Math.max(...row) - Math.min(...row)).toBeLessThanOrEqual(1); + if (c.runs % row.length === 0) expect(new Set(row).size).toBe(1); + } + // Two arms: the order alternates between rounds. + if (c.hosts.includes('claude') && !c.baseline && c.runs >= 2) { + const first = (r: number) => plan.find((p) => p.host === 'claude' && p.task === c.tasks[0] && p.round === r && p.position === 0)?.arm; + expect(first(1)).not.toBe(first(2)); + } + } + }); + + it('is fixed by the seed, and the seed changes it', () => { + const a = planRuns(['claude', 'codex'], ['T1', 'T2', 'T3'], undefined, 4, 42); + expect(planRuns(['claude', 'codex'], ['T1', 'T2', 'T3'], undefined, 4, 42)).toEqual(a); + const orders = new Set([1, 2, 3, 4, 5, 6].map((seed) => planRuns(['claude', 'codex'], ['T1', 'T2', 'T3'], undefined, 4, seed).map((p) => `${p.host}${p.task}${p.arm}`).join())); + expect(orders.size).toBeGreaterThan(1); expect(planRuns(['claude'], ['T1'], ['C'], 1, 1)).toEqual([]); + expect(planRuns(['claude'], ['T1'], ['A', 'B0'], 2, 1, true).map((p) => p.arm).sort()).toEqual(['A', 'A', 'B0', 'B0']); + }); + + it('warms every host x arm of the plan once, on the warmup task', () => { + const plan = planRuns(['claude', 'codex'], ['T5', 'T9'], undefined, 3, 7, true); + const warm = planWarmup(plan, 7); + expect(warm.map((p) => `${p.host}${p.arm}`).sort()).toEqual(['claudeA', 'claudeB', 'claudeB0', 'codexA', 'codexB', 'codexC', 'codexC0']); + expect(warm.every((p) => p.task === WARMUP_TASK && p.warmup === true)).toBe(true); }); }); @@ -129,14 +200,142 @@ describe('dry run', () => { process.stdout.write = orig; } const text = writes.join(''); - expect(text.match(/: pass, valid/g)).toHaveLength(10); + expect(text.match(/^(claude|codex) T\d+ \w+ r1: pass, valid/gm)).toHaveLength(10); + // One warmup per host x arm before the matrix; none on the resume, which has nothing left to run. + expect(text.match(/^warmup (claude|codex) T1 \w+ r1: pass, valid/gm)).toHaveLength(5); 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); + expect(summary.warmup.runs).toBe(5); + expect(text).toMatch(/Warmup: 5 run\(s\)/); // 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); }); + +describe('baseline build arm', () => { + it('runs B0 next to B in the same matrix and compares them', async () => { + const work = await mkdtemp(path.join(os.tmpdir(), 'acm-base-')); + const out = path.join(work, 'results'); + const dist = path.join(work, 'old-dist'); + await mkdir(dist, { recursive: true }); + await writeFile(path.join(dist, 'cli.js'), '// a stand-in build\n'); + const args = ['--dry-run', '--host', 'claude', '--tasks', 'T1,T2,T3', '--runs', '2', '--seed', '5', '--work-dir', work, '--out', out, '--date', '2026-01-04']; + try { + expect((await quiet(() => main([...args, '--arms', 'B0']))).value).toBe(2); + const r = await quiet(() => main([...args, '--acm-dist', dist])); + expect(r.value).toBe(0); + expect(r.text.match(/^claude T\d B0 r\d: pass, valid/gm)).toHaveLength(6); + const summary = JSON.parse(await readFile(path.join(out, '2026-01-04', 'summary.json'), 'utf8')); + const builds = new Set(summary.groups.filter((g: { arm: string }) => g.arm !== 'A').map((g: { arm: string; config: { acmBuild: string } }) => `${g.arm}:${g.config.acmBuild}`)); + expect([...builds].sort()).toEqual(expect.arrayContaining(['B:checkout', expect.stringMatching(/^B0:dist:[0-9a-f]{12}$/)])); + expect(summary.comparisons.map((c: { arm: string; reference: string }) => `${c.arm}-${c.reference}`).sort()).toEqual(['B-A', 'B-B0', 'B0-A']); + // Canned transcripts: B and B0 are identical, so the cost difference is exactly 0 and the interval says so. + const bb0 = summary.comparisons.find((c: { arm: string; reference: string }) => c.arm === 'B' && c.reference === 'B0'); + expect(bb0.costUsd).toMatchObject({ estimate: 0, lo: 0, hi: 0, crossesZero: true, tasks: 3 }); + expect(r.text).toMatch(/\| B vs B0 \| 3 \|.*CI crosses 0/); + } finally { + await rm(work, { recursive: true, force: true }); + } + }, 120_000); + + it('resolves --acm-ref to a commit of this repository', async () => { + const work = await mkdtemp(path.join(os.tmpdir(), 'acm-ref-')); + try { + const r = await quiet(() => main(['--dry-run', '--host', 'claude', '--arms', 'B0', '--tasks', 'T1', '--runs', '1', '--seed', '1', '--work-dir', work, '--out', path.join(work, 'r'), '--date', '2026-01-05', '--acm-ref', 'HEAD'])); + expect(r.value).toBe(0); + const env = JSON.parse(await readFile(path.join(work, 'r', '2026-01-05', 'env.json'), 'utf8')); + expect(env.invocations[0].baseline.id).toMatch(/^ref:[0-9a-f]{12}$/); + expect((await quiet(() => main(['--dry-run', '--host', 'claude', '--tasks', 'T1', '--runs', '1', '--work-dir', work, '--acm-ref', 'no-such-ref-xyz']))).value).toBe(2); + } finally { + await rm(work, { recursive: true, force: true }); + } + }, 120_000); +}); + +/** Every directory from `dir` up to the filesystem root. */ +function ancestors(dir: string): string[] { + const out = [dir]; + while (path.dirname(out.at(-1) as string) !== out.at(-1)) out.push(path.dirname(out.at(-1) as string)); + return out; +} + +describe('workspace isolation from the checkout', () => { + it('defaults the work dir to outside the repository', () => { + expect(insideRepo(defaultWorkDir())).toBe(false); + expect(parseOptions([]).workDir).toBe(defaultWorkDir()); + expect(insideRepo(path.join(REPO_ROOT, 'bench', '.work'))).toBe(true); + expect(insideRepo(REPO_ROOT)).toBe(true); + }); + + it('refuses a --work-dir inside the checkout, also through a symlink', async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), 'acm-link-')); + try { + await symlink(path.join(REPO_ROOT, 'bench'), path.join(tmp, 'bench-link')); + for (const dir of [path.join(REPO_ROOT, 'bench', '.work'), REPO_ROOT, path.join(tmp, 'bench-link', 'work')]) { + const errs: string[] = []; + const orig = process.stderr.write.bind(process.stderr); + process.stderr.write = ((c: string | Uint8Array) => (errs.push(String(c)), true)) as typeof process.stderr.write; + try { + expect(await main(['--dry-run', '--tasks', 'T1', '--runs', '1', '--work-dir', dir])).toBe(2); + } finally { + process.stderr.write = orig; + } + expect(errs.join('')).toMatch(/--work-dir .* is inside the repository checkout/); + } + } finally { + await rm(tmp, { recursive: true, force: true }); + } + }); + + it('rejects a workspace with bench/tasks in any directory above it', async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), 'acm-anc-')); + try { + await mkdir(path.join(tmp, 'bench', 'tasks'), { recursive: true }); + expect(() => assertWorkspaceIsolated(path.join(tmp, 'a', 'b', 'ws'))).toThrow(/bench\/tasks above it/); + expect(() => assertWorkspaceIsolated(path.join(REPO_ROOT, 'x', 'ws'))).toThrow(/inside the repository checkout/); + } finally { + await rm(tmp, { recursive: true, force: true }); + } + }); + + it('no run workspace has an ancestor holding bench/tasks, and both hosts are pointed only at it', async () => { + const work = await mkdtemp(path.join(os.tmpdir(), 'acm-iso-ws-')); + const out = path.join(work, 'results'); + try { + expect((await quiet(() => main(['--dry-run', '--tasks', 'T9,T10', '--runs', '1', '--seed', '2', '--work-dir', work, '--out', out, '--date', '2026-01-06']))).value).toBe(0); + const wss = (await readdir(path.join(work, 'runs'), { recursive: true })).filter((f) => path.basename(f) === 'ws').map((f) => path.join(work, 'runs', f)); + expect(wss.length).toBe(2 * 2 + 2 * 3 + 5); // matrix + warmups + for (const ws of wss) { + expect(insideRepo(ws)).toBe(false); + for (const dir of ancestors(ws)) expect(existsSync(path.join(dir, 'bench', 'tasks')), dir).toBe(false); + } + // Codex is given the workspace and nothing else (`-C `); arm C's MCP server inherits that cwd. + const commands = (await readdir(out, { recursive: true })).filter((f) => path.basename(f) === 'command.txt'); + for (const f of commands.filter((c) => c.includes('codex'))) expect(await readFile(path.join(out, f), 'utf8')).toMatch(/ -C /); + // Claude is started in the workspace: its init cwd, which is also the MCP root of arm B, is the workspace. + for (const f of commands.filter((c) => c.includes('claude'))) expect(await readFile(path.join(out, f), 'utf8')).not.toContain('--add-dir'); + const records = (await readdir(out, { recursive: true })).filter((f) => path.basename(f) === 'record.json'); + for (const f of records) expect(await readFile(path.join(out, f), 'utf8')).not.toContain('/bench/tasks'); + } finally { + await rm(work, { recursive: true, force: true }); + } + }, 120_000); + + it('the --acm-ref build has no bench/ or test/ next to the run workspaces', async () => { + const work = await mkdtemp(path.join(os.tmpdir(), 'acm-build-')); + try { + const build = await resolveBaseline({ acmRef: 'HEAD', acmDist: undefined, dryRun: false }, work); + const dir = path.dirname(path.dirname(build?.entry ?? '')); + expect(existsSync(build?.entry ?? '')).toBe(true); + expect(existsSync(path.join(dir, 'bench'))).toBe(false); + expect(existsSync(path.join(dir, 'test'))).toBe(false); + expect(existsSync(path.join(dir, 'src'))).toBe(true); + } finally { + await rm(work, { recursive: true, force: true }); + } + }, 600_000); +}); diff --git a/bench/test/verifiers.test.ts b/bench/test/verifiers.test.ts index d816bad..79310fa 100644 --- a/bench/test/verifiers.test.ts +++ b/bench/test/verifiers.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { afterAll, describe, expect, it } from 'vitest'; @@ -182,3 +182,76 @@ describe('verifier edge cases', () => { expect(c.initial.has('.claude/settings.json')).toBe(false); }); }); + +describe('hidden-test tasks', () => { + const write = (dir: string, rel: string, text: string) => writeFile(path.join(dir, ...rel.split('/')), text); + + it('T9 rejects a fix at the symptom (statement builds each invoice once) and accepts the root-cause fix', async () => { + const ws = await workspace('T9'); + const file = path.join(ws.dir, 'src', 'billing', 'statement.js'); + const text = await readFile(file, 'utf8'); + await writeFile(file, text.replace('const invoice = buildInvoice(order, region);', 'const invoice = preview;')); + const symptom = await TASKS.T9.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(symptom.pass).toBe(false); + expect(symptom.details.join('\n')).toMatch(/FAIL hidden tests pass/); + }); + + it('T9-T11 never leave hidden tests in the workspace', async () => { + for (const id of ['T9', 'T10', 'T11'] as const) { + const ws = await workspace(id); + await TASKS[id].verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(await readdir(ws.dir)).not.toContain('hidden-tests'); + for (const f of ws.initial.keys()) expect(f.startsWith('hidden-tests/')).toBe(false); + } + }); + + it('T10 fails when one caller keeps the positional form or the public API drops it', async () => { + const ws = await workspace('T10'); + await TASKS.T10.solution(ws.dir, ws.fixture.facts); + // Same output, old form: caught by the static check. + await write(ws.dir, 'src/catalog/export.js', "import { formatPrice } from '../lib/price.js';\nexport function csvRow(item) {\n return [item.sku, item.name, formatPrice(item.cents, { symbol: false })].join(',');\n}\nexport function csv(items) {\n return ['sku,name,price', ...items.map(csvRow)].join('\\n');\n}\nexport const legacy = (c) => formatPrice(c, 'USD', false);\n"); + const positional = await TASKS.T10.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(positional.details.join('\n')).toMatch(/FAIL positional formatPrice calls left: src\/catalog\/export\.js/); + const ws2 = await workspace('T10'); + await TASKS.T10.solution(ws2.dir, ws2.fixture.facts); + await write(ws2.dir, 'src/index.js', "export { formatPrice } from './lib/price.js';\nexport { priceLabel, plainLabel } from './catalog/labels.js';\nexport { csv, csvRow } from './catalog/export.js';\nexport { priceTable, priceDelta } from './catalog/table.js';\nexport { summaryLine, totalsByCurrency } from './catalog/summary.js';\n"); + const noCompat = await TASKS.T10.verify({ workspace: ws2.dir, answer: '', facts: ws2.fixture.facts, initial: ws2.initial }); + expect(noCompat.pass).toBe(false); + }); + + it('T11 fails a floating-point implementation that is right on small inputs', async () => { + const ws = await workspace('T11'); + await write( + ws.dir, + 'src/lib/split.js', + `export function splitCents(totalCents, weights) { + if (!Number.isSafeInteger(totalCents) || !Array.isArray(weights) || weights.length === 0) throw new RangeError('bad'); + if (weights.some((w) => !Number.isSafeInteger(w) || w < 0)) throw new RangeError('bad'); + const sum = weights.reduce((a, b) => a + b, 0); + if (sum === 0) { if (totalCents !== 0) throw new RangeError('bad'); return weights.map(() => 0); } + const abs = Math.abs(totalCents); + const raw = weights.map((w) => (abs * w) / sum); + const shares = raw.map(Math.floor); + let left = abs - shares.reduce((a, b) => a + b, 0); + const order = raw.map((r, i) => ({ i, f: r - Math.floor(r) })).sort((a, b) => b.f - a.f || a.i - b.i); + for (const { i } of order) { if (left <= 0) break; shares[i] += 1; left -= 1; } + return shares.map((s) => (s === 0 ? 0 : totalCents < 0 ? -s : s)); +} +`, + ); + const result = await TASKS.T11.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(result.details[0]).toMatch(/^ok node --test passes/); + expect(result.details.join("\n")).toMatch(/FAIL hidden tests pass \(pass \d+, fail \d+: [^)]*exact for the largest safe totals/); + }); + + it('T12 checks both the request id and the caller, and is deterministic for the fixture seed', async () => { + const ws = await workspace('T12'); + const answer = await TASKS.T12.solution(ws.dir, ws.fixture.facts); + const [, id, service] = /ANSWER: (\S+), (\S+)/.exec(answer) ?? []; + expect(id).toMatch(/^r-[0-9a-f]{8}$/); + const wrong = answer.replace(`, ${service}`, service === 'api' ? ', shipping' : ', api'); + expect((await TASKS.T12.verify({ workspace: ws.dir, answer: wrong, facts: ws.fixture.facts, initial: ws.initial })).pass).toBe(false); + const again = await workspace('T12'); + expect([...again.initial.entries()].filter(([f]) => f.startsWith('logs/'))).toEqual([...ws.initial.entries()].filter(([f]) => f.startsWith('logs/'))); + }); +}); From 2ccb7bd3ffd735c1b3bfc47219794c26ca8461bf Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:00:17 -0300 Subject: [PATCH 04/13] Expand relative globs for pure readers; close brace, tilde and multi-byte bypasses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cat/head/tail/wc/ls with a relative glob and a known option set have the glob expanded at prepare time: every match is resolved inside the working directories, checked against Read deny/ask rules, written into the command as a quoted literal list after --, and its identity (dev, ino, type) is checked again right before spawn. Hooks and rules see the command that runs. Fixes in the shell analysis, each with a bash-oracle test and an attack test: - Claude: brace expansion ({/outside,x}) let an allowed reader open a file outside the workspace; brace, ~user, shopt and bash -O now make the command uncertain. - Claude: words were sliced by UTF-16 index from byte offsets, so text such as 'echo é; rm -rf x' hid rm from a deny rule; slicing is now by byte. - Codex: {rm,-f,x} and $"rm" escaped a forbidden rule; words bash rewrites are marked inexact and a rule that may match them asks (denied). Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + src/core/output.test.ts | 17 ++ src/core/output.ts | 26 +- src/core/types.ts | 68 +++++ src/hosts/claude/adapter.test.ts | 38 ++- src/hosts/claude/adapter.ts | 74 ++++- src/hosts/claude/bash.test.ts | 114 ++++++++ src/hosts/claude/bash.ts | 217 ++++++++++++-- src/hosts/claude/expand.test.ts | 264 +++++++++++++++++ src/hosts/claude/expand.ts | 410 +++++++++++++++++++++++++++ src/hosts/codex/adapter.ts | 31 +- src/hosts/codex/shell.test.ts | 90 ++++++ src/hosts/codex/shell.ts | 79 +++++- src/tools/bash.ts | 164 ++++++++++- src/tools/runtime.ts | 16 +- test/attack/bash-globs.test.ts | 173 +++++++++++ test/attack/shell-expansions.test.ts | 107 +++++++ 17 files changed, 1825 insertions(+), 64 deletions(-) create mode 100644 src/hosts/claude/bash.test.ts create mode 100644 src/hosts/claude/expand.test.ts create mode 100644 src/hosts/claude/expand.ts create mode 100644 src/hosts/codex/shell.test.ts create mode 100644 test/attack/bash-globs.test.ts create mode 100644 test/attack/shell-expansions.test.ts diff --git a/README.md b/README.md index 522b7eb..950647a 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ Semantics: - **`ask` is denied.** The server has no way to prompt you. When the host would ask, the call is refused with source `ask-unavailable`. Allow what the script needs with your usual rules or permission mode. - **Auto mode (Claude).** Claude's classifier reviews the whole `run` call once. Deny and ask rules still apply to every inner call. If an allow rule approves `run` itself, the classifier never saw the script, so inner calls no rule decides follow auto mode's fallback: reads and edits inside the working directories pass, everything else asks. - **Paths.** Calls are confined to the session cwd, the client's roots and the host's additional directories. Symlinks leading out are refused. Host policy files (`.claude/settings*.json`, `.claude/hooks/`, `.mcp.json`, `.codex/`, `~/.claude/`, `$CODEX_HOME`, the server state dir) cannot be written. `grep` and `glob` drop files your Read rules deny and count them in `filtered`. +- **Globs in `bash` (Claude).** A relative glob read by `cat`, `head`, `tail`, `wc` or `ls` (with options from a fixed list, no `ls -R`, no redirection, no `..`, `~`, `$VAR`, `$(...)` or backticks) is expanded before authorization, and the command names each match literally, single-quoted after `--`: `wc -l src/*` becomes `wc -l -- 'src/a.js' 'src/b.js'`. Rules, hooks and the result (`command`) see that command. Matches are sorted by byte value, like bash in the C locale. Each match must resolve inside the workspace and be a regular file (or a directory for `ls`, whose listed children must pass your Read rules); otherwise the call fails. A glob that matches nothing, or any other command, stays as written. Right before the command starts, every match is checked again (device, inode and type, of the link and of what it points to); if one changed, nothing runs. What remains is the moment between that check and the reader opening the file, a few milliseconds in which a process that can write the workspace could swap a file. Native Claude Code checks a command's paths and then runs it with no second check at all, so that window is larger there. - **`bash` containment** mirrors the host. When Claude's sandbox is enabled, or Codex runs `read-only`/`workspace-write`, commands run in an OS sandbox (bubblewrap on Linux, Seatbelt on macOS) with the host's writable roots. If that cannot be enforced, the call is refused, never run unconfined. - **Overlapping transactions.** Within one server, a transactional run may not write a file that another unfinished transactional run already changed: that write fails, so both runs can still roll back to the true original. - **Rollback covers files only.** Effects of `bash` (processes, network, files a command wrote) are never undone; the result warns when a rolled-back run had committed `bash` calls. diff --git a/src/core/output.test.ts b/src/core/output.test.ts index f318160..9d1bb8d 100644 --- a/src/core/output.test.ts +++ b/src/core/output.test.ts @@ -69,6 +69,23 @@ describe('summarizeCalls', () => { }); }); + it('does not repeat the run error in the reason of the call that raised it', () => { + const message = 'host would ask the user and no interactive channel exists: Bash needs approval in default mode'; + const calls: CallLogEntry[] = [ + { id: 'c1', tool: 'bash', summary: 'bash node -v', decision: 'denied', reason: `ask-unavailable: ${message}`, durationMs: 1 }, + { id: 'c2', tool: 'read', summary: 'read x', decision: 'denied', reason: message, durationMs: 1 }, + { id: 'c3', tool: 'read', summary: 'read y', decision: 'denied', reason: 'rule: another reason', durationMs: 1 }, + ]; + expect(summarizeCalls(calls, message).denied).toEqual([ + { id: 'c1', tool: 'bash', summary: 'bash node -v', reason: 'ask-unavailable (see error)' }, + { id: 'c2', tool: 'read', summary: 'read x' }, + { id: 'c3', tool: 'read', summary: 'read y', reason: 'rule: another reason' }, + ]); + const view = json(formatRunResult({ ...base, ok: false, error: { name: 'PermissionDenied', message, kind: 'error' }, calls })); + expect(all(formatRunResult({ ...base, ok: false, error: { name: 'PermissionDenied', message, kind: 'error' }, calls })).split(message)).toHaveLength(2); + expect(view['error']).toMatchObject({ message }); + }); + it('D1: lists every denied call, however many', () => { const out = formatRunResult({ ...base, result: 'caught all', calls: Array.from({ length: 25 }, (_, i) => deniedCall(i + 1)) }); const calls = json(out)['calls']; diff --git a/src/core/output.ts b/src/core/output.ts index bcffe1c..639a951 100644 --- a/src/core/output.ts +++ b/src/core/output.ts @@ -61,12 +61,30 @@ export function safeStringify(value: unknown): string { type FailedCall = Pick & { readonly reason?: string }; -/** The call log as counts plus every denied and failed call (without the duration). */ -export function summarizeCalls(calls: readonly CallLogEntry[]): { total: number; byTool: Record; denied?: FailedCall[]; errors?: FailedCall[] } { +/** + * The call log as counts plus every denied and failed call (without the + * duration). A reason that repeats `errorMessage` (the run's error, already in + * the result) is cut to what it adds: its source prefix, or nothing. + */ +export function summarizeCalls( + calls: readonly CallLogEntry[], + errorMessage?: string, +): { total: number; byTool: Record; denied?: FailedCall[]; errors?: FailedCall[] } { const byTool: Record = {}; for (const c of calls) byTool[c.tool] = (byTool[c.tool] ?? 0) + 1; + const shown = (reason: string | undefined): string | undefined => { + if (reason === undefined || errorMessage === undefined || errorMessage === '') return reason; + if (reason === errorMessage) return undefined; + if (reason.endsWith(`: ${errorMessage}`)) return `${reason.slice(0, -errorMessage.length - 2)} (see error)`; + return reason; + }; const failed = (decision: CallLogEntry['decision']): FailedCall[] => - calls.filter((c) => c.decision === decision).map(({ id, tool, summary, reason }) => ({ id, tool, summary, ...(reason === undefined ? {} : { reason }) })); + calls + .filter((c) => c.decision === decision) + .map(({ id, tool, summary, reason }) => { + const r = shown(reason); + return { id, tool, summary, ...(r === undefined ? {} : { reason: r }) }; + }); const denied = failed('denied'); const errors = failed('error'); return { total: calls.length, byTool, ...(denied.length > 0 ? { denied } : {}), ...(errors.length > 0 ? { errors } : {}) }; @@ -143,7 +161,7 @@ export function runResultView(result: RunResult, verbose = false): { readonly vi const view: Record = { ...rest, ...(logs.length > 0 ? { logs } : {}), - calls: verbose ? calls : summarizeCalls(calls), + calls: verbose ? calls : summarizeCalls(calls, result.error?.message), ...(changedFiles.length > 0 ? { changedFiles } : {}), ...(diff === '' ? {} : bigDiff ? { diffStat: diffStat(diff) } : { diff }), ...(warnings.length > 0 ? { warnings } : {}), diff --git a/src/core/types.ts b/src/core/types.ts index 729cca3..9c30691 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -130,6 +130,12 @@ export interface BashResult { readonly truncated: boolean; /** True when the command hit its timeout and was killed. */ readonly timedOut: boolean; + /** + * The command that ran, present only when it is not the one the script + * passed: its globs were expanded to the literal list of files before it was + * authorized (see `BashEffect.expansion`). + */ + readonly command?: string; } /** Result of `read`. */ @@ -272,8 +278,63 @@ export interface BashEffect { readonly timeoutMs: number; /** Containment the tool runtime will enforce; must equal the policy's `bashContainment`. */ readonly containment: BashContainment; + /** + * Present when globs of the command were expanded at prepare (see + * `PolicySnapshot.planBashExpansion`): `command` then names every file + * literally, and commit refuses to run it unless each entry still has the + * identity recorded here. + */ + readonly expansion?: BashExpansion; +} + +/** What a glob expansion of a `bash` command replaced and the entries it named. */ +export interface BashExpansion { + /** The command as it would have run without the expansion. */ + readonly original: string; + /** Every file or directory the globs expanded to, in command order. */ + readonly entries: readonly BashExpandedEntry[]; +} + +/** One expanded entry and its identity at prepare. */ +export interface BashExpandedEntry { + /** Absolute path as named in the command (its last component not resolved). */ + readonly path: string; + /** `dev:ino:type` of the entry itself (lstat, a symbolic link is not followed). */ + readonly identity: string; + /** `dev:ino:type` of what the command opens (stat, symbolic links followed). */ + readonly targetIdentity: string; +} + +/** + * Where a host can expand the globs of a `bash` command (built by the host + * adapter, which owns the shell parser; the tool runtime does the I/O). + * `globs` lists each glob word to expand; `render` returns the command with + * the i-th glob replaced by `matches[i]` (paths relative to the command's cwd, + * in the order given). + */ +export interface BashGlobPlan { + readonly globs: readonly BashGlob[]; + render(matches: readonly (readonly string[])[]): string; +} + +/** One glob word of a `bash` command, split at `/`. */ +export interface BashGlob { + /** The word as written. */ + readonly raw: string; + readonly segments: readonly BashGlobSegment[]; + /** Whether a match may be a directory (`ls`); otherwise only regular files. */ + readonly directories: boolean; } +/** A path segment of a glob: literal text, or a name pattern. */ +export type BashGlobSegment = + | { readonly kind: 'literal'; readonly text: string } + | { + readonly kind: 'pattern'; + /** Whether the name matches the pattern (bash glob semantics, C locale). */ + readonly matches: (name: string) => boolean; + }; + /** Effect of a `read` call. */ export interface ReadEffect { readonly absPath: string; @@ -460,6 +521,13 @@ export interface PolicySnapshot

{ * path inside the workspace is readable. */ readonly readFilter?: (realAbsPath: string) => boolean; + /** + * Plans the expansion of globs in a `bash` command (relative patterns read + * by a known pure reader such as `cat` or `wc`). Undefined, or a result of + * undefined, leaves the command as written. The tool runtime expands the + * plan at prepare against the command's cwd and validates every match. + */ + readonly planBashExpansion?: (command: string) => BashGlobPlan | undefined; readonly payload: P; } diff --git a/src/hosts/claude/adapter.test.ts b/src/hosts/claude/adapter.test.ts index cbae8a6..eae2e91 100644 --- a/src/hosts/claude/adapter.test.ts +++ b/src/hosts/claude/adapter.test.ts @@ -178,13 +178,28 @@ describe('Bash rules', () => { it('says why an allow-all Bash rule did not approve a command that names files at run time', async () => { const s = await setup({ user: { permissions: { allow: ['Bash'] } } }); expect(check(s, bash('wc -l src/a.ts', s.project))).toBe('allow'); - for (const command of ['wc -l src/*', 'head -c 9 src/$(ls src | head -1)']) { + // A glob the rules would approve once its files are named literally gets the hint. + for (const command of ['wc -l src/*', 'sort src/*.ts']) { const decision = s.adapter.checkStatic(bash(command, s.project), s.ctx, s.policy); expect(decision).toMatchObject({ kind: 'ask', reason: `Bash needs approval in default mode: ${RUNTIME_FILES_HINT}` }); } + // A substitution or a glob outside the working directories: naming the files would not help, so no hint. + for (const command of ['head -c 9 src/$(ls src | head -1)', 'cat /etc/*.conf', 'cat ../*']) { + const decision = s.adapter.checkStatic(bash(command, s.project), s.ctx, s.policy); + expect(decision.kind).not.toBe('allow'); + expect('reason' in decision ? decision.reason : '').not.toContain('name each file literally'); + } // Without files named at run time the reason stays as it was. const none = await setup({}); expect(none.adapter.checkStatic(bash('wc -l src/a.ts', none.project), none.ctx, none.policy)).toEqual({ kind: 'ask', reason: 'Bash needs approval in default mode' }); + // No rule covers the command: the hint would not help either. + expect(none.adapter.checkStatic(bash('cat src/*', none.project), none.ctx, none.policy)).toEqual({ kind: 'ask', reason: 'Bash needs approval in default mode' }); + // One subcommand no rule covers: naming the files leaves it denied. + const catOnly = await setup({ user: { permissions: { allow: ['Bash(cat:*)'] } } }); + const mixed = catOnly.adapter.checkStatic(bash('cat src/* && node -v', catOnly.project), catOnly.ctx, catOnly.policy); + expect('reason' in mixed ? mixed.reason : '').not.toContain('name each file literally'); + const catGlob = catOnly.adapter.checkStatic(bash('cat src/*', catOnly.project), catOnly.ctx, catOnly.policy); + expect('reason' in catGlob ? catGlob.reason : '').toContain('name each file literally'); }); it('checks redirect and file-reader targets against Read/Edit rules', async () => { @@ -199,6 +214,27 @@ describe('Bash rules', () => { expect(check(s, bash('echo x > notes.txt', s.project))).toBe('allow'); expect(check(s, bash('cat README.md 2>/dev/null', s.project))).toBe('allow'); }); + + it('treats every word after `--` as a file, even one that looks like an option or a count', async () => { + const s = await setup({ user: { permissions: { deny: ['Read(./5)', 'Read(./-n)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash("head -n 5 a.txt", s.project))).toBe('allow'); // `5` is the count here + expect(check(s, bash("cat -- '5'", s.project))).toBe('deny'); + expect(check(s, bash("wc -l -- a.txt '-n'", s.project))).toBe('deny'); + }); + + it('matches Bash deny rules against the command as written and without the inserted `--`', async () => { + const s = await setup({ user: { permissions: { deny: ['Bash(cat secret*)', 'Bash(wc -l [ab].log)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash("cat -- 'secret.txt'", s.project))).toBe('deny'); + // An expanded call: the expanded form escapes the rule written against the glob, the original does not. + const expanded: PreparedCall = { + id: 'c1', + tool: 'bash', + args: { command: "wc -l -- 'a.log'", timeoutMs: 120_000 }, + effect: { command: "wc -l -- 'a.log'", cwd: s.project, timeoutMs: 120_000, containment, expansion: { original: 'wc -l [ab].log', entries: [] } }, + }; + expect(check(s, expanded)).toBe('deny'); + expect(check(s, bash("wc -l -- 'a.log'", s.project))).toBe('allow'); + }); }); describe('path rules', () => { diff --git a/src/hosts/claude/adapter.ts b/src/hosts/claude/adapter.ts index 9ca9a46..7c69924 100644 --- a/src/hosts/claude/adapter.ts +++ b/src/hosts/claude/adapter.ts @@ -14,6 +14,7 @@ import type { ToolResult, } from '../../core/types.js'; import { BashAnalyzer, type BashAnalysis } from './bash.js'; +import { planGlobExpansion } from './expand.js'; import { NATIVE_TOOL, combineOutcomes, @@ -154,7 +155,14 @@ interface CallView { readonly paths: readonly string[]; readonly analysis: BashAnalysis | undefined; /** Resolved file targets of a bash command; undefined path = only known at run time. */ - readonly bashFiles: readonly { readonly access: 'read' | 'write'; readonly path: string | undefined }[]; + readonly bashFiles: readonly BashFile[]; +} + +interface BashFile { + readonly access: 'read' | 'write'; + readonly path: string | undefined; + /** For a glob target: the glob as written, before expansion. */ + readonly pattern?: string; } function pathRuleVerdict(patterns: readonly PathPattern[], paths: readonly string[], kind: RuleKind): Verdict { @@ -192,7 +200,7 @@ function restrictVerdict(rule: Rule, view: CallView): Verdict { let verdict: Verdict = fileVerdict; for (const cmd of view.analysis.commands) { if (cmd.denyForms.some((form) => matchesBashSpec(spec, form))) return 'match'; - if (cmd.dynamic && cmd.staticPrefixes.some((prefix) => bashSpecMayMatchDynamic(spec, prefix))) verdict = 'maybe'; + if ((cmd.dynamic || cmd.globbed) && cmd.staticPrefixes.some((prefix) => bashSpecMayMatchDynamic(spec, prefix))) verdict = 'maybe'; } return verdict; } @@ -245,6 +253,31 @@ function allowedByRule(view: CallView, rules: readonly Rule[], policy: ClaudePol export const RUNTIME_FILES_HINT = 'the command names files only known at run time (a glob, variable or substitution), which no allow rule covers; name each file literally, or find and read files with glob(), read() and grep()'; +/** + * Whether the allow rules would approve the command if each glob it names + * were written as the files it matches: every subcommand has an approved + * allow form, every literal file is inside the working directories, and so is + * the literal directory each glob starts from. A file named by a variable or + * a substitution has no such directory, so this is false then. + */ +function literalFormAllowed(view: CallView, policy: ClaudePolicy): boolean { + if (view.prepared.tool !== 'bash' || !view.analysis) return false; + const files: BashFile[] = []; + for (const f of view.bashFiles) { + if (f.path !== undefined) { + files.push(f); + continue; + } + if (f.pattern === undefined || view.analysis.changesDirectory) return false; + const segments = f.pattern.split('/'); + if (segments.includes('..')) return false; + const at = segments.findIndex((seg) => /[*?[]/.test(seg)); + const dir = at === 0 ? '.' : segments.slice(0, at).join('/') || '/'; + files.push({ access: f.access, path: resolveCommandPath(dir, view.prepared.effect.cwd, policy.home) }); + } + return allowedByRule({ ...view, bashFiles: files }, policy.rules.allow, policy); +} + /** What the permission mode does with a call that no rule decided. */ function modeDecision(view: CallView, policy: ClaudePolicy): Decision { const { prepared } = view; @@ -541,6 +574,7 @@ export class ClaudeHostAdapter implements HostAdapter { protectedPaths, additionalRoots: [...additionalRoots], readFilter: (realAbsPath: string): boolean => !isReadDenied(realAbsPath), + planBashExpansion: planGlobExpansion, payload: { projectRoot, cwd: ctx.cwd, @@ -562,9 +596,9 @@ export class ClaudeHostAdapter implements HostAdapter { const native = nativeCall(prepared); const paths = callPaths(prepared, policy.cwd, policy.home); if (prepared.tool !== 'bash') return { prepared, native, paths, analysis: undefined, bashFiles: [] }; - const analysis = BashAnalyzer.analyze(prepared.effect.command); - const bashFiles = analysis.files.map((f) => { - if (f.path === undefined) return { access: f.access, path: undefined }; + const analysis = BashAnalyzer.analyze(prepared.effect.command, { home: policy.home }); + const bashFiles = analysis.files.map((f): BashFile => { + if (f.path === undefined) return { access: f.access, path: undefined, ...(f.pattern === undefined ? {} : { pattern: f.pattern }) }; const relative = !(f.path.startsWith('/') || f.path.startsWith('~') || path.isAbsolute(f.path)); // After a `cd`, a relative target cannot be resolved statically. if (relative && analysis.changesDirectory) return { access: f.access, path: undefined }; @@ -573,6 +607,30 @@ export class ClaudeHostAdapter implements HostAdapter { return { prepared, native, paths, analysis, bashFiles }; } + /** + * Bash deny and ask rules against the command as the script wrote it, before + * its globs were expanded: a rule written against the glob form still + * applies. File rules are left to the expanded command, which names every + * file literally. Undefined when no expansion took place or no rule decides. + */ + #originalRestrictions(prepared: PreparedCall, policy: ClaudePolicy): Decision | undefined { + if (prepared.tool !== 'bash' || prepared.effect.expansion === undefined) return undefined; + const command = prepared.effect.expansion.original; + const original: PreparedCall = { ...prepared, args: { ...prepared.args, command }, effect: { ...prepared.effect, command } }; + // Only a rule that matches the glob form itself: what the globs may match is checked, literally, on the expanded command. + const view = { ...this.#view(original, policy), bashFiles: [] }; + for (const rule of policy.rules.deny) { + if (restrictVerdict(rule, view) === 'match') return { kind: 'deny', source: 'rule', reason: `denied by ${describe(rule)}` }; + } + for (const rule of policy.rules.ask) { + if (restrictVerdict(rule, view) === 'match') { + const reason = `${describe(rule)} matches`; + return policy.mode === 'dontAsk' ? { kind: 'deny', source: 'rule', reason: `dontAsk mode denies what would ask: ${reason}` } : { kind: 'ask', reason }; + } + } + return undefined; + } + /** Deny and ask rules. Undefined when none decides. */ #restrictions(view: CallView, policy: ClaudePolicy): Decision | undefined { const askOrDeny = (reason: string): Decision => @@ -597,7 +655,7 @@ export class ClaudeHostAdapter implements HostAdapter { const view = this.#view(prepared, policy); const askOrDeny = (reason: string): Decision => policy.mode === 'dontAsk' ? { kind: 'deny', source: 'rule', reason: `dontAsk mode denies what would ask: ${reason}` } : { kind: 'ask', reason }; - const restricted = this.#restrictions(view, policy); + const restricted = this.#restrictions(view, policy) ?? this.#originalRestrictions(prepared, policy); if (restricted) return restricted; if (view.analysis && view.analysis.uncertain.length > 0) { return askOrDeny(`the command cannot be checked statically (${view.analysis.uncertain.join('; ')})`); @@ -606,8 +664,8 @@ export class ClaudeHostAdapter implements HostAdapter { if (critical !== undefined) return askOrDeny(`${critical}; no rule or mode approves it`); if (allowedByRule(view, policy.rules.allow, policy)) return { kind: 'allow' }; const decision = modeDecision(view, policy); - // Same decision, with the cause the script can act on: allow rules never cover files named at run time. - if (decision.kind !== 'allow' && view.bashFiles.some((f) => f.path === undefined)) { + // Same decision, with the cause the script can act on, when acting on it would get the command approved. + if (decision.kind !== 'allow' && view.bashFiles.some((f) => f.path === undefined) && literalFormAllowed(view, policy)) { return { ...decision, reason: `${decision.reason}: ${RUNTIME_FILES_HINT}` }; } return decision; diff --git a/src/hosts/claude/bash.test.ts b/src/hosts/claude/bash.test.ts new file mode 100644 index 0000000..58f0dd9 --- /dev/null +++ b/src/hosts/claude/bash.test.ts @@ -0,0 +1,114 @@ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { BashAnalyzer } from './bash.js'; + +/** + * Oracle: bash itself. For every generated word, either the analyzer reports + * the command as uncertain (it is then asked, so denied without a prompt), or + * marks the word as only known at run time or as a glob (rules then treat it + * as "may match"), or the value it matches rules against is exactly the word + * bash hands the command. + */ + +const posix = process.platform !== 'win32'; +const HOME = os.homedir(); +const SEED = Number(process.env["ACM_SEED"] ?? 42); + +/** Pieces a word is built from: one per expansion bash may apply, plus plain text. */ +const PIECES = [ + 'a', 'b.txt', '-n', '=', ':', '/', 'é', '😀', '!x', '#', + '{a,b}', '{1..3}', '{}', 'a{b}c', '{,}', 'x{a,{b,c}}', "'{a,b}'", '"{a,b}"', '\\{a,b}', '{a\\,b}', '{"a,b"}', + '~', '~/', '~/x', '~root', '~+', '~-', '~nobody/z', "'~'", '"~"', '\\~', 'a~b', 'a=~/x', 'A_1=x:~/y', '--f=~/x', 'x:~/y', '"a"=~/x', 'a=~root', + "$'\\x41'", "$'\\n'", "$'a\\tb'", "$'\\''", "$'\\101'", '$"hi"', '$((1+2))', '$((x))', '<(true)', '>(true)', + '\\a', '\\\\', '"a\\b"', '"a\\"b"', "'a\\b'", '\\ ', '"$HOME"', '$HOME', '${HOME}', '$(echo x)', '`echo x`', + '*', '?', '[ab]', '*.txt', '"*"', '\\*', '"a b"', "'it'\\''s'", +]; + +function rng(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** The words bash passes to `X` for each line of `lines`, run in `cwd`. */ +function bashWords(lines: readonly string[], cwd: string): (string[] | undefined)[] { + const script = ['X() { printf "\\2"; for a in "$@"; do printf "%s\\0" "$a"; done; printf "\\1"; }', ...lines.map((l) => `${l}\nprintf "\\3"`)].join('\n'); + const r = spawnSync('bash', ['-c', script], { cwd, env: { PATH: process.env['PATH'] ?? '', HOME, LC_ALL: 'C' }, encoding: 'utf8' }); + const chunks = r.stdout.split('\x03'); + return lines.map((_, i) => { + const chunk = chunks[i] ?? ''; + const start = chunk.indexOf('\x02'); + const end = chunk.indexOf('\x01'); + if (start === -1 || end === -1) return undefined; + return chunk.slice(start + 1, end).split('\0').slice(0, -1); + }); +} + +describe.runIf(posix)('BashAnalyzer word values against bash', () => { + const dir = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-words-'))); + for (const f of ['a.txt', 'b.txt', 'ab']) writeFileSync(path.join(dir, f), ''); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + it('matches rules against the word bash runs, or does not treat it as known', () => { + const r = rng(SEED); + const words: string[] = [...PIECES]; + for (let i = 0; i < 600; i++) { + const n = 1 + Math.floor(r() * 3); + words.push(Array.from({ length: n }, () => PIECES[Math.floor(r() * PIECES.length)] ?? '').join('')); + } + const lines = words.map((w) => `X ${w}`); + const fromBash = bashWords(lines, dir); + let exact = 0; + let refused = 0; + for (let i = 0; i < lines.length; i++) { + const line = lines[i] ?? ''; + const analysis = BashAnalyzer.analyze(line, { home: HOME }); + if (analysis.uncertain.length > 0) { + refused++; + continue; + } + const cmd = analysis.commands.find((c) => c.words[0]?.value === 'X'); + const got = fromBash[i]; + if (!cmd) { + // Nothing to match (a comment); bash runs `X` without arguments. + expect(got, line).toEqual([]); + continue; + } + const args = cmd.words.slice(1); + if (args.some((w) => w.value === undefined || w.glob)) { + expect(cmd.dynamic || cmd.globbed, line).toBe(true); + continue; + } + expect(got, line).toEqual(args.map((w) => w.value)); + exact++; + } + expect(exact).toBeGreaterThan(150); + expect(refused).toBeGreaterThan(50); + }); + + it('reports brace expansion, `~user` and `shopt` as uncertain, and expands `~` to the home', () => { + for (const line of ['cat {/etc/passwd,x}', 'cat x{,}', 'cat {1..3}', 'cat ~root/.bashrc', 'cat ~+/../x', 'cat a=~nobody', 'shopt -s extglob\ncat @(x)', "bash -O extglob -c 'cat x'"]) { + expect(BashAnalyzer.analyze(line, { home: HOME }).uncertain.length, line).toBeGreaterThan(0); + } + expect(BashAnalyzer.analyze('cat ~/x').uncertain.length).toBeGreaterThan(0); // no home known + const files = BashAnalyzer.analyze('cat ~/x a=~/y "~/z" {} a{b}c', { home: '/h' }).commands[0]?.words.map((w) => w.value); + expect(files).toEqual(['cat', '/h/x', 'a=/h/y', '~/z', '{}', 'a{b}c']); + }); + + it('cuts command text by bytes, so forms after multi-byte text are right', () => { + for (const ch of ['é', '€', '😀']) { + const a = BashAnalyzer.analyze(`echo ${ch}${ch}; rm -rf 'x y' "$Z"`); + const rm = a.commands.find((c) => c.words[0]?.value === 'rm'); + expect(rm?.raw).toBe(`rm -rf 'x y' "$Z"`); + expect(rm?.words.map((w) => w.raw)).toEqual(['rm', '-rf', "'x y'", '"$Z"']); + } + }); +}); diff --git a/src/hosts/claude/bash.ts b/src/hosts/claude/bash.ts index 41686ff..86755f4 100644 --- a/src/hosts/claude/bash.ts +++ b/src/hosts/claude/bash.ts @@ -45,6 +45,10 @@ export interface SimpleCommand { readonly staticPrefixes: readonly string[]; /** True when some word's value is only known at run time. */ readonly dynamic: boolean; + /** True when some word is an unquoted glob, so bash may hand the command other words. */ + readonly globbed: boolean; + /** The command's words as matching sees them (value undefined: only known at run time). */ + readonly words: readonly Operand[]; } /** A file a command reads or writes by name (redirection or `tee`). */ @@ -52,6 +56,8 @@ export interface FileTarget { readonly access: 'read' | 'write'; /** The path as written, or undefined when it is only known at run time. */ readonly path: string | undefined; + /** For a glob (path undefined): the pattern as bash sees it, before expansion. */ + readonly pattern?: string; } export interface BashAnalysis { @@ -211,15 +217,142 @@ function partsValue(parts: readonly WordPart[], quoted: boolean): { value: strin return { value, glob }; } +/** Source being analyzed. sh-syntax positions are byte offsets into its UTF-8 form. */ +interface Ctx { + readonly source: string; + readonly bytes: Buffer; + readonly depth: number; +} + +/** One character of a static word and whether quoting (or a backslash) made it literal. */ +interface WordChar { + readonly c: string; + readonly quoted: boolean; +} + +/** + * The characters of a word, or undefined when part of it is only known at + * run time. `opaque` parts (substitutions) are kept as a placeholder so brace + * detection still sees the unquoted text around them. + */ +function wordChars(parts: readonly WordPart[]): { chars: WordChar[]; static: boolean } { + const chars: WordChar[] = []; + let isStatic = true; + const push = (text: string, quoted: boolean): void => { + for (const c of text) chars.push({ c, quoted }); + }; + for (const part of parts) { + switch (part.type) { + case 'Lit': { + const lit = part.value; + for (let i = 0; i < lit.length; i++) { + const c = lit[i] ?? ''; + if (c === '\\' && i + 1 < lit.length) { + const next = lit[i + 1] ?? ''; + i++; + if (next !== '\n') chars.push({ c: next, quoted: true }); + continue; + } + chars.push({ c, quoted: false }); + } + break; + } + case 'SglQuoted': { + const v = part.dollar ? decodeAnsi(part.value) : part.value; + if (v === undefined) { + isStatic = false; + chars.push({ c: '\0', quoted: true }); + } else push(v, true); + break; + } + case 'DblQuoted': { + const inner = part.dollar ? undefined : partsValue(part.parts, true).value; + if (inner === undefined) { + isStatic = false; + chars.push({ c: '\0', quoted: true }); + } else push(inner, true); + break; + } + default: + isStatic = false; + chars.push({ c: '\0', quoted: true }); + } + } + return { chars, static: isStatic }; +} + +/** Whether bash may brace-expand the word (`{a,b}`, `{1..3}`, `x{,}`); `{}` and `a{b}c` stay as written. */ +function hasBraceExpansion(chars: readonly WordChar[]): boolean { + // Any unquoted `{`, then a `,` or `..`, then a `}`: a superset of what bash expands (its pairing rules are subtle). + let stage = 0; + for (let i = 0; i < chars.length; i++) { + const ch = chars[i]; + if (!ch || ch.quoted) continue; + if (stage === 0 && ch.c === '{') stage = 1; + else if (stage === 1 && (ch.c === ',' || (ch.c === '.' && chars[i + 1]?.c === '.' && chars[i + 1]?.quoted === false))) stage = 2; + else if (stage === 2 && ch.c === '}') return true; + } + return false; +} + +const ASSIGNMENT_LIKE = /^[A-Za-z_][A-Za-z0-9_]*=/; + +/** + * Applies bash's tilde expansion to a static word: a leading unquoted `~`, + * and in a word that looks like an assignment (`a=~/x`, `PATH=a:~/b`) a `~` + * after the `=` or an unquoted `:`. `~` and `~/...` become `home`; any other + * tilde prefix (`~user`, `~+`, `~-`, `~1`) is reported as unknown. + */ +function expandTilde(chars: readonly WordChar[], home: string | undefined): { value: string } | { unknown: string } | undefined { + const starts: number[] = []; + if (chars[0]?.c === '~' && !chars[0].quoted) starts.push(0); + const unquotedHead = chars.slice(0, chars.findIndex((c) => c.c === '=') + 1); + const assignment = unquotedHead.length > 0 && unquotedHead.every((c) => !c.quoted) && ASSIGNMENT_LIKE.test(unquotedHead.map((c) => c.c).join('')); + if (assignment) { + for (let i = unquotedHead.length - 1; i < chars.length; i++) { + const ch = chars[i]; + if (ch && !ch.quoted && (ch.c === '=' ? i === unquotedHead.length - 1 : ch.c === ':') && chars[i + 1]?.c === '~' && chars[i + 1]?.quoted === false) starts.push(i + 1); + } + } + if (starts.length === 0) return undefined; + let out = ''; + let from = 0; + for (const at of starts) { + let end = at + 1; + while (end < chars.length) { + const ch = chars[end]; + if (!ch || (!ch.quoted && (ch.c === '/' || (assignment && ch.c === ':')))) break; + end++; + } + const prefix = chars.slice(at + 1, end); + if (prefix.some((c) => c.quoted)) continue; // a quoted tilde-prefix is not expanded + if (prefix.length > 0) return { unknown: `~${prefix.map((c) => c.c).join('')}` }; + if (home === undefined) return { unknown: '~' }; + out += chars.slice(from, at).map((c) => c.c).join('') + home; + from = at + 1; + } + return { value: out + chars.slice(from).map((c) => c.c).join('') }; +} + +export interface AnalyzeOptions { + /** Home directory bash expands `~` to; without it a `~` word is uncertain. */ + readonly home?: string; +} + export class BashAnalyzer { readonly #commands: SimpleCommand[] = []; + readonly #home: string | undefined; readonly #files: FileTarget[] = []; readonly #uncertain: string[] = []; #changesDirectory = false; readonly #removals: Removal[] = []; - static analyze(command: string): BashAnalysis { - const analyzer = new BashAnalyzer(); + private constructor(home: string | undefined) { + this.#home = home; + } + + static analyze(command: string, opts: AnalyzeOptions = {}): BashAnalysis { + const analyzer = new BashAnalyzer(opts.home); analyzer.#analyzeSource(command, 0); return { commands: analyzer.#commands, @@ -246,7 +379,7 @@ export class BashAnalyzer { this.#uncertain.push(`command could not be parsed: ${err instanceof Error ? err.message : String(err)}`); return; } - const ctx = { source, depth }; + const ctx: Ctx = { source, bytes: Buffer.from(source, 'utf8'), depth }; walk(file, (node) => { switch (node.type) { case 'CallExpr': @@ -270,24 +403,40 @@ export class BashAnalyzer { }); } - #text(node: Node, ctx: { source: string }): string { - return ctx.source.slice(node.start, node.end); + #text(node: Node, ctx: Ctx): string { + return ctx.bytes.subarray(node.start, node.end).toString('utf8'); } - #word(word: Word, ctx: { source: string }): WordValue { - const { value, glob } = partsValue(word.parts, false); - return { value, raw: this.#text(word, ctx), glob }; + /** + * The word as the command receives it. Expansions bash applies to text + * that looks static are resolved exactly (backslashes, quotes, `~` and + * `~/` with the known home) or reported as uncertain (brace expansion, + * `~user`, `~+`, `~-`): the rules must never check a word bash would change. + */ + #word(word: Word, ctx: Ctx): WordValue { + const parsed = partsValue(word.parts, false); + const raw = this.#text(word, ctx); + const { chars, static: isStatic } = wordChars(word.parts); + if (hasBraceExpansion(chars)) this.#uncertain.push(`${JSON.stringify(raw)} uses brace expansion, which turns one word into several`); + if (!isStatic || parsed.value === undefined) return { value: parsed.value, raw, glob: parsed.glob }; + const tilde = expandTilde(chars, this.#home); + if (tilde === undefined) return { value: parsed.value, raw, glob: parsed.glob }; + if ('unknown' in tilde) { + this.#uncertain.push(`${JSON.stringify(raw)} uses the tilde expansion ${tilde.unknown}, only known at run time`); + return { value: undefined, raw, glob: parsed.glob }; + } + return { value: tilde.value, raw, glob: parsed.glob }; } - #declClause(decl: DeclClause, ctx: { source: string; depth: number }): void { + #declClause(decl: DeclClause, ctx: Ctx): void { // `export`, `declare`, `local`, `readonly`, `typeset`, `nameref`: their own // words are assignments; nested substitutions are walked generically. const name = decl.variant?.value ?? 'declare'; const raw = this.#text(decl, ctx); - this.#commands.push({ raw, denyForms: [raw, name], allowForm: undefined, staticPrefixes: [name], dynamic: true }); + this.#commands.push({ raw, denyForms: [raw, name], allowForm: undefined, staticPrefixes: [name], dynamic: true, globbed: false, words: [] }); } - #redirect(redir: Redirect, ctx: { source: string; depth: number }): void { + #redirect(redir: Redirect, ctx: Ctx): void { if (REDIR_HDOC.has(redir.op)) { const body = redir.hdoc; if (body && body.parts.some((p) => p.type !== 'Lit')) { @@ -299,16 +448,17 @@ export class BashAnalyzer { const target = this.#word(redir.word, ctx); const path = target.value !== undefined && !target.glob ? target.value : undefined; if (path === '/dev/null' || path === '/dev/stdout' || path === '/dev/stderr') return; - if (REDIR_OUT.has(redir.op)) this.#files.push({ access: 'write', path }); - else if (REDIR_IN.has(redir.op)) this.#files.push({ access: 'read', path }); + const pattern = target.glob && target.value !== undefined ? { pattern: target.value } : {}; + if (REDIR_OUT.has(redir.op)) this.#files.push({ access: 'write', path, ...pattern }); + else if (REDIR_IN.has(redir.op)) this.#files.push({ access: 'read', path, ...pattern }); else if (REDIR_INOUT.has(redir.op)) { - this.#files.push({ access: 'read', path }); - this.#files.push({ access: 'write', path }); + this.#files.push({ access: 'read', path, ...pattern }); + this.#files.push({ access: 'write', path, ...pattern }); } // Here-strings (`<<<`) carry no file. } - #callExpr(call: CallExpr, ctx: { source: string; depth: number }): void { + #callExpr(call: CallExpr, ctx: Ctx): void { const raw = this.#text(call, ctx); const words = call.args.map((w) => this.#word(w, ctx)); if (words.length === 0) return; // pure assignment, e.g. `A=$(rm x)`: nested commands are walked @@ -320,12 +470,18 @@ export class BashAnalyzer { let writes = FILE_WRITERS.has(base) || FILE_COPIERS.has(base); if (base === 'sed' && operands.some((o) => o.value !== undefined && (o.value === '-i' || o.value.startsWith('--in-place') || /^-[a-zA-Z]*i/.test(o.value)))) writes = true; if (!reads && !writes) return; + let endOfOptions = false; for (let k = 0; k < operands.length; k++) { const operand = operands[k]; if (!operand) continue; if (operand.raw.startsWith('<(') || operand.raw.startsWith('>(')) continue; let value = operand.value; - if (value !== undefined && value.startsWith('-')) { + if (!endOfOptions && value === '--') { + // Every later word is an operand, even `-n` or `5`. + endOfOptions = true; + continue; + } + if (!endOfOptions && value !== undefined && value.startsWith('-')) { // `-n 5`: skip a numeric option value; `--file=x`, `-fX`: the value may be a file. const next = operands[k + 1]?.value; if (next !== undefined && /^\d+$/.test(next)) k++; @@ -339,22 +495,28 @@ export class BashAnalyzer { value = m[2]; } const path = value !== undefined && !operand.glob ? value : undefined; - if (reads) this.#files.push({ access: 'read', path }); - if (writes) this.#files.push({ access: 'write', path }); + const pattern = operand.glob && value !== undefined ? { pattern: value } : {}; + if (reads) this.#files.push({ access: 'read', path, ...pattern }); + if (writes) this.#files.push({ access: 'write', path, ...pattern }); } } - #addCommand(raw: string, words: readonly WordValue[], hasAssigns: boolean, ctx: { source: string; depth: number }): void { + #addCommand(raw: string, words: readonly WordValue[], hasAssigns: boolean, ctx: Ctx): void { const denyForms = new Set([raw]); const staticPrefixes = new Set(); const dynamic = words.some((w) => w.value === undefined); + const globbed = words.some((w) => w.glob); const text = (ws: readonly WordValue[]): string => ws.map((w) => w.value ?? w.raw).join(' '); + // Words before the first one bash may change at run time (a substitution or a glob). const prefix = (ws: readonly WordValue[]): string => { - const i = ws.findIndex((w) => w.value === undefined); + const i = ws.findIndex((w) => w.value === undefined || w.glob); return (i === -1 ? ws : ws.slice(0, i)).map((w) => w.value ?? '').join(' '); }; const addForm = (ws: readonly WordValue[]): void => { denyForms.add(text(ws)); + // `cat -- x` is matched as `cat x` too (deny/ask only: the marker does not change what is read). + const marker = ws.findIndex((w, i) => i > 0 && w.value === '--'); + if (marker !== -1) denyForms.add(text([...ws.slice(0, marker), ...ws.slice(marker + 1)])); staticPrefixes.add(prefix(ws)); const head = ws[0]; if (head?.value !== undefined) { @@ -390,6 +552,7 @@ export class BashAnalyzer { const operands = current.slice(1); if (base === 'cd' || base === 'pushd' || base === 'popd') this.#changesDirectory = true; if (CODE_EVALUATORS.has(base)) this.#uncertain.push(`\`${base}\` runs code that is only known at run time`); + if (base === 'shopt') this.#uncertain.push('`shopt` changes how bash expands later words (extglob, globstar, dotglob ...)'); if (NAME_REBINDERS.has(base) && operands.length > 0) this.#uncertain.push(`\`${base}\` rebinds command names, so later commands cannot be matched by name`); this.#fileOperands(base, operands); if (base === 'rm' || base === 'rmdir') { @@ -423,14 +586,14 @@ export class BashAnalyzer { } const allowForm = allowStripped !== undefined && !dynamic ? text(allowStripped) : undefined; - this.#commands.push({ raw, denyForms: [...denyForms], allowForm, staticPrefixes: [...staticPrefixes], dynamic }); + this.#commands.push({ raw, denyForms: [...denyForms], allowForm, staticPrefixes: [...staticPrefixes], dynamic, globbed, words }); } /** * `env -S 'cmd args'` / `env --split-string=...`: the string is split into a * command line. Returns true when the invocation had one (it was analyzed). */ - #envSplitString(words: readonly WordValue[], ctx: { source: string; depth: number }): boolean { + #envSplitString(words: readonly WordValue[], ctx: Ctx): boolean { for (let i = 1; i < words.length; i++) { const w = words[i]; if (!w) break; @@ -465,7 +628,7 @@ export class BashAnalyzer { return false; } - #shell(words: readonly WordValue[], ctx: { source: string; depth: number }): void { + #shell(words: readonly WordValue[], ctx: Ctx): void { // Find `-c