diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..0377465 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# Bench task fixtures and recorded parser inputs are read byte for byte (hidden tests compare trap files +# exactly, the verifier tests edit exact snippets): keep them LF on every OS, whatever core.autocrlf says. +bench/tasks/** text eol=lf +bench/parser-fixtures/** text eol=lf +# Shell scripts (test hook fixtures, e2e scripts) run under bash, which rejects CRLF. +*.sh text eol=lf diff --git a/README.md b/README.md index cb348b3..1b594d4 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,11 @@ npx -y agent-code-mode install --host claude --scope project User scope prints the registration command and the companion hook for `~/.claude/settings.json`: ```sh -claude mcp add --scope user agent-code-mode -- npx -y agent-code-mode serve --host claude +claude mcp add --scope user agent-code-mode -- npx -y agent-code-mode serve --host claude --hybrid ``` +Install uses `--hybrid` by default because Claude Code keeps its native file and shell tools enabled next to `run`: the tool description then says when to batch calls with `run` and when a native tool is enough. Drop `--hybrid` only if you turn the native tools off and the model works through `run` alone. + ```json { "hooks": { @@ -58,11 +60,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 +73,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`). `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 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. Denied and failed calls are never cut by entry: when they do not fit whole, they are grouped by tool and reason as `{tool, reason, count, first}` (`first` is the summary of the first call), so every distinct reason shows with its exact count. Only with thousands of distinct reasons is each reason cut to 200 characters and, if that is still too much, the last groups replaced by a `…[N more reasons (M calls)]` marker. With `verbose: true`, a call log above the cap keeps its first entries and the compact calls come beside it as `callSummary`. 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. @@ -92,6 +95,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. The matches and their order come from the same bash, in the same environment and locale, with startup files (`BASH_ENV`) left out so expanding runs no code; on Windows (Git Bash) globs are not expanded. 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. @@ -110,7 +114,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/.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 0dbe773..d8fade5 100644 --- a/bench/lib/claude.ts +++ b/bench/lib/claude.ts @@ -1,10 +1,11 @@ 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. */ +/** Native file and shell tools of Claude Code. Using one of them in the strict agent-code-mode arm is a fallback. */ export const CLAUDE_NATIVE_TOOLS = ['Bash', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep', 'NotebookEdit']; export const CLAUDE_RUN_TOOL = 'mcp__agent-code-mode__run'; -/** Native tool names allowed by rule in both arms (in arm B they only reach the model through `run`). */ +/** Native tool names allowed by rule in every arm (in arm B they only reach the model through `run`). */ export const CLAUDE_INNER_ALLOWED = ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep']; /** Agents Claude Code 2.1.325 ships; anything else in the init event came from the user's config. */ export const CLAUDE_BUILTIN_AGENTS = ['claude', 'Explore', 'general-purpose', 'Plan', 'statusline-setup']; @@ -39,17 +40,23 @@ export function claudeArgs(o: ClaudeCommandOptions): string[] { // Arm A: the native tools, allowed by rule. Arm B: no built-in tools at all (`--tools ""` removes them // without denying them: a CLI deny rule would also deny the same tool inside agent-code-mode, by // parity), and the same native names allowed by rule so the inner calls are allowed exactly as in A. - // Both arms see no other built-in tool (no Task, ToolSearch, web...), so they differ only in native + // Arm C (hybrid): the native tools of A and `run`, all allowed by rule; the model picks per call. + // No arm sees any other built-in tool (no Task, ToolSearch, web...), so they differ only in native // file/shell tools vs `run`. if (o.arm === 'A') args.push('--tools', CLAUDE_INNER_ALLOWED.join(','), '--allowedTools', CLAUDE_INNER_ALLOWED.join(',')); - else args.push('--tools', '', '--allowedTools', [CLAUDE_RUN_TOOL, ...CLAUDE_INNER_ALLOWED].join(',')); + else if (o.arm === 'B') args.push('--tools', '', '--allowedTools', [CLAUDE_RUN_TOOL, ...CLAUDE_INNER_ALLOWED].join(',')); + else args.push('--tools', CLAUDE_INNER_ALLOWED.join(','), '--allowedTools', [CLAUDE_RUN_TOOL, ...CLAUDE_INNER_ALLOWED].join(',')); return args; } -/** The `--mcp-config` content for an arm: no servers for A, the agent-code-mode server for B. */ +/** + * The `--mcp-config` content for an arm: no servers for A, the agent-code-mode server for B and, started + * with `--hybrid` (the `run` description then says when to batch and when to use a native tool), for C. + */ export function claudeMcpConfig(arm: ArmId, serverEntry: string): unknown { if (arm === 'A') return { mcpServers: {} }; - return { mcpServers: { 'agent-code-mode': { type: 'stdio', command: process.execPath, args: [serverEntry, 'serve', '--host', 'claude'] } } }; + const args = [serverEntry, 'serve', '--host', 'claude', ...(arm === 'C' ? ['--hybrid'] : [])]; + return { mcpServers: { 'agent-code-mode': { type: 'stdio', command: process.execPath, args } } }; } const UsageEvent = z.object({ @@ -78,6 +85,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'), @@ -99,11 +108,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)) { @@ -146,7 +150,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; @@ -169,6 +174,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) { @@ -190,14 +200,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); } } @@ -208,6 +216,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 6583577..c36456a 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') { @@ -341,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..75953d6 100644 --- a/bench/lib/record.ts +++ b/bench/lib/record.ts @@ -1,12 +1,47 @@ 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; +/** + * Arms per host. Claude: A native, B agent-code-mode strict, C agent-code-mode hybrid (native tools and + * `run`, the server started with `--hybrid`). Codex: A native, B Codex code mode, C agent-code-mode strict. + */ +export const HOST_ARMS = { claude: ['A', 'B', 'C'], 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 strict 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 strict agent-code-mode arm). + * `C0` is Codex only: `planRuns` never pairs it with Claude, whose `C` is the hybrid 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 (Claude B and C, Codex C). */ +export function isAcmArm(host: 'claude' | 'codex', arm: BenchArm): boolean { + const s = surfaceArm(arm); + return host === 'claude' ? s === 'B' || s === 'C' : s === 'C'; +} + +/** True for the arm where the model may mix native tools and `run` (Claude C). */ +export function isHybridArm(host: 'claude' | 'codex', arm: ArmId): boolean { + return host === 'claude' && arm === '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)', C: 'agent-code-mode hybrid (native + run, batching guidance)', 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 +71,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 +111,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(), @@ -89,7 +131,7 @@ export const RunRecordSchema = z.object({ costUsd: z.number().nonnegative().nullable(), costSource: z.enum(['host', 'pricing.json', 'none']), verify: z.object({ pass: z.boolean(), details: z.array(z.string()) }), - /** An agent-code-mode arm where the model also made native file/shell tool calls. In the strict arms this also makes the run invalid. */ + /** A strict agent-code-mode arm where the model also made native file/shell tool calls, which also makes the run invalid. Never set in the hybrid arm, where native calls are part of the arm. */ fallback: z.boolean(), /** False when the observed tool usage does not match the arm label, or the run did not complete. */ valid: z.boolean(), @@ -107,11 +149,17 @@ export interface ArmCheck { export function checkArm(host: 'claude' | 'codex', arm: ArmId, calls: ToolCalls): ArmCheck { const reasons: string[] = []; const total = calls.native + calls.run + calls.codeMode + calls.other; + if (isHybridArm(host, arm)) { + // The model picks per call: native only, run only and any mix are all the arm as labeled. + if (calls.codeMode > 0) reasons.push('hybrid agent-code-mode arm used Codex code mode'); + if (calls.other > 0) reasons.push(`hybrid agent-code-mode arm made ${calls.other} call(s) to tools outside its surface`); + return { fallback: false, reasons }; + } const acm = (host === 'claude' && arm === 'B') || (host === 'codex' && arm === 'C'); if (acm) { if (calls.run === 0) reasons.push('agent-code-mode arm made no run call'); if (calls.codeMode > 0) reasons.push('agent-code-mode arm used Codex code mode'); - // Both agent-code-mode arms are strict: a native file/shell call means the arm did not run as labeled. + // These agent-code-mode arms are strict: a native file/shell call means the arm did not run as labeled. if (calls.native > 0) reasons.push(`strict agent-code-mode arm made ${calls.native} native file/shell tool call(s)`); return { fallback: calls.native > 0, reasons }; } @@ -127,9 +175,10 @@ export function checkArm(host: 'claude' | 'codex', arm: ArmId, calls: ToolCalls) /** The exact tool set each Claude arm must see in its `system/init` event. */ -export const CLAUDE_ARM_SURFACE: Readonly> = { +export const CLAUDE_ARM_SURFACE: Readonly> = { A: ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep'], B: ['mcp__agent-code-mode__run'], + C: ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'mcp__agent-code-mode__run'], }; /** * Non-file tools every Codex arm must reach, and nothing else: the arms differ only in how files and the @@ -154,7 +203,7 @@ function sameSet(a: readonly string[], b: readonly string[]): boolean { export function checkSurface(host: 'claude' | 'codex', arm: ArmId, tools: readonly string[]): string[] { const reasons: string[] = []; if (host === 'claude') { - const expected = arm === 'B' ? CLAUDE_ARM_SURFACE.B : CLAUDE_ARM_SURFACE.A; + const expected = CLAUDE_ARM_SURFACE[arm]; if (!sameSet(tools, expected)) reasons.push(`Claude arm ${arm} tools are [${[...tools].sort().join(', ')}], expected exactly [${[...expected].sort().join(', ')}]`); return reasons; } diff --git a/bench/lib/run-result.ts b/bench/lib/run-result.ts new file mode 100644 index 0000000..a0374b6 --- /dev/null +++ b/bench/lib/run-result.ts @@ -0,0 +1,74 @@ +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. 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({ + 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); + +/** 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 { + return JSON.parse(text); + } catch { + 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; + 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/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/parser-fixtures/claude-C.jsonl b/bench/parser-fixtures/claude-C.jsonl new file mode 100644 index 0000000..bdb61ed --- /dev/null +++ b/bench/parser-fixtures/claude-C.jsonl @@ -0,0 +1,8 @@ +{"type": "bench_note", "note": "Synthetic canned transcript (hand-written, not a model run) for --dry-run and parser tests: the hybrid arm, one native call and one run call."} +{"type": "system", "subtype": "init", "cwd": "", "session_id": "00000000-0000-4000-8000-000000000002", "tools": ["Bash", "Edit", "Glob", "Grep", "Read", "Write", "mcp__agent-code-mode__run"], "mcp_servers": [{"name": "agent-code-mode", "status": "connected"}], "model": "claude-sonnet-5-5", "permissionMode": "default"} +{"type": "assistant", "message": {"id": "msg_1", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {"file_path": "/config/app.json"}}], "usage": {"input_tokens": 3, "output_tokens": 20, "cache_creation_input_tokens": 16000, "cache_read_input_tokens": 11000}}, "session_id": "00000000-0000-4000-8000-000000000002"} +{"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "1\t{\n2\t \"service\": {\n3\t \"retryLimit\": 7\n4\t }\n5\t}\n"}]}, "session_id": "00000000-0000-4000-8000-000000000002"} +{"type": "assistant", "message": {"id": "msg_2", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_2", "name": "mcp__agent-code-mode__run", "input": {"code": "const hits = await grep({pattern: 'retryLimit', path: 'config'});\nconst regions = await read({path: 'config/regions.json'});\nconst flags = await read({path: 'config/flags.json'});\nreturn {hits: hits.count, regions: regions.totalLines, flags: flags.totalLines};"}}], "usage": {"input_tokens": 2, "output_tokens": 70, "cache_creation_input_tokens": 300, "cache_read_input_tokens": 27000}}, "session_id": "00000000-0000-4000-8000-000000000002"} +{"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_2", "content": [{"type": "text", "text": "{\"ok\": true, \"result\": {\"hits\": 1, \"regions\": 12, \"flags\": 9}, \"calls\": {\"total\": 3, \"byTool\": {\"grep\": 1, \"read\": 2}}}"}]}]}, "session_id": "00000000-0000-4000-8000-000000000002"} +{"type": "assistant", "message": {"id": "msg_3", "role": "assistant", "content": [{"type": "text", "text": "service.retryLimit is 7.\n\nANSWER: 7"}], "usage": {"input_tokens": 2, "output_tokens": 12, "cache_creation_input_tokens": 400, "cache_read_input_tokens": 27300}}, "session_id": "00000000-0000-4000-8000-000000000002"} +{"type": "result", "subtype": "success", "is_error": false, "duration_ms": 6100, "duration_api_ms": 4900, "num_turns": 3, "result": "service.retryLimit is 7.\n\nANSWER: 7", "session_id": "00000000-0000-4000-8000-000000000002", "total_cost_usd": 0.0587, "usage": {"input_tokens": 7, "cache_creation_input_tokens": 16700, "cache_read_input_tokens": 65300, "output_tokens": 102, "output_tokens_details": {"thinking_tokens": 0}}, "modelUsage": {"claude-sonnet-5-5": {"inputTokens": 7, "outputTokens": 102}}, "permission_denials": []} 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..b4ee9d4 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,18 +12,21 @@ 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'; /** - * Benchmark runner: `npm run bench -- --host claude --arms A,B --tasks T1,T5 --runs 3`. + * Benchmark runner: `npm run bench -- --host claude --arms A,B,C --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; +} + +/** 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)); } -/** 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 }[] = []; +/** + * 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,102 @@ 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 }); + // Only what the build needs: no bench/ (hidden tests, solutions) next to the run workspaces. The archive + // is written into the build dir and unpacked there by a relative name: a GNU tar on Windows reads a + // drive letter (`D:\\...`) as a remote host, the system bsdtar does not care. + const tar = path.join(dir, 'source.tar'); + execFileSync('git', ['archive', '--format=tar', '-o', tar, commit, '--', '.', ':(exclude)bench', ':(exclude)test'], { cwd: REPO_ROOT, stdio: 'ignore' }); + execFileSync('tar', ['-xf', 'source.tar'], { cwd: 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 `); + } + // A junction on Windows: a directory symlink there needs a privilege the user may not have. + await symlink(path.join(REPO_ROOT, 'node_modules'), path.join(dir, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir'); + const npm = npmCommand(); + execFileSync(npm.command, [...npm.args, '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; +} + +/** + * How to run npm without a shell: this Node with npm's own `npm-cli.js` (`npm` is a `.cmd` shim on + * Windows, which `execFile` cannot start). Found from `npm_execpath` when run under npm, else next to the + * Node binary (Windows: `/node_modules/npm`, POSIX: `/lib/node_modules/npm`); plain + * `npm` as the last resort. + */ +export function npmCommand(env: NodeJS.ProcessEnv = process.env, execPath: string = process.execPath): { command: string; args: string[] } { + const nodeDir = path.dirname(execPath); + const candidates = [ + env['npm_execpath'], + path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'), + path.join(nodeDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'), + ]; + for (const c of candidates) if (c !== undefined && c !== '' && /npm-cli\.js$/.test(c) && existsSync(c)) return { command: execPath, args: [c] }; + return { command: 'npm', args: [] }; } function stableJson(value: unknown): string { @@ -237,20 +420,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 +457,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 +532,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 +575,9 @@ export async function executeRun(ctx: Context, p: PlannedRun): Promise' }, @@ -463,6 +656,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 +767,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 +835,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 +853,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/T13/files/src/jobs/clock.js b/bench/tasks/T13/files/src/jobs/clock.js new file mode 100644 index 0000000..847a8ee --- /dev/null +++ b/bench/tasks/T13/files/src/jobs/clock.js @@ -0,0 +1,6 @@ +/** Timer source of the queue. Tests pass their own object with the same `setTimeout(fn, ms)` method. */ +export const systemClock = { + setTimeout(fn, ms) { + globalThis.setTimeout(fn, ms); + }, +}; diff --git a/bench/tasks/T13/files/src/jobs/queue.js b/bench/tasks/T13/files/src/jobs/queue.js new file mode 100644 index 0000000..6eea7dc --- /dev/null +++ b/bench/tasks/T13/files/src/jobs/queue.js @@ -0,0 +1,74 @@ +/** + * Job queue: bounded concurrency, retry with backoff, de-duplication by key. + * + * const queue = createQueue({ concurrency, maxAttempts, backoff: { baseMs, factor, maxMs }, clock }); + * const result = await queue.add(key, fn); + * + * Contract: + * 1. Concurrency. At most `concurrency` job functions are running at any moment. A job function is + * called as `fn(attempt)`, with attempt = 1, 2, ...; it may return a value or a promise, and a + * synchronous throw is a failed attempt like a rejection. Jobs waiting for a slot start in the + * order in which they began to wait. + * 2. Retry. A failed attempt is retried until `maxAttempts` attempts have been made. The wait before + * attempt n + 1 is min(maxMs, baseMs * factor ** (n - 1)) milliseconds, scheduled with one + * `clock.setTimeout(fn, ms)` call and with nothing else (no real timers). + * 3. Backoff does not hold a slot. While a job waits out its backoff its slot is free for other + * jobs. When the wait ends the job queues for a slot like a newly added job, behind the jobs + * that are already waiting. + * 4. Giving up. When attempt number `maxAttempts` fails, the promise rejects with the error of that + * last attempt and the job function is not called again. + * 5. De-duplication. While a job is pending (waiting for a slot, running or in backoff), `add` with + * the same key does not call the new function: it returns the promise of the pending job (the + * same object). + * 6. Key reuse. A key is free again as soon as its job settles, whether it resolved or rejected: + * the next `add` with that key runs its function as a new job, with attempts counted from 1. + * Nothing is cached. The key is already free when the handlers of the promise run, so a `then` + * or `catch` handler may add the same key again. + * 7. `stats()` returns `{ running, waiting, delayed }`: the jobs whose function is running, the jobs + * waiting for a slot and the jobs in backoff. + */ +import { systemClock } from './clock.js'; +import { createRegistry } from './registry.js'; +import { handleFailure } from './retry.js'; +import { createSlots } from './slots.js'; + +export function createQueue({ concurrency = 4, maxAttempts = 3, backoff = {}, clock = systemClock } = {}) { + if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer'); + if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new RangeError('maxAttempts must be a positive integer'); + const policy = { maxAttempts, baseMs: backoff.baseMs ?? 100, factor: backoff.factor ?? 2, maxMs: backoff.maxMs ?? 30_000 }; + const slots = createSlots(concurrency); + const keys = createRegistry(); + const counters = { delayed: 0 }; + + async function run(job) { + const release = await slots.acquire(); + job.attempt += 1; + try { + const value = await job.fn(job.attempt); + keys.release(job.key); + job.resolve(value); + } catch (err) { + handleFailure(job, err, { policy, clock, counters, release, requeue: run }); + } finally { + release(); + } + } + + function add(key, fn) { + const pending = keys.get(key); + if (pending) return pending; + const job = { key, fn, attempt: 0, resolve: null, reject: null }; + const promise = new Promise((resolve, reject) => { + job.resolve = resolve; + job.reject = reject; + }); + keys.hold(key, promise); + void run(job); + return promise; + } + + return { + add, + stats: () => ({ running: slots.active, waiting: slots.waiting, delayed: counters.delayed }), + }; +} diff --git a/bench/tasks/T13/files/src/jobs/registry.js b/bench/tasks/T13/files/src/jobs/registry.js new file mode 100644 index 0000000..2c04bbc --- /dev/null +++ b/bench/tasks/T13/files/src/jobs/registry.js @@ -0,0 +1,15 @@ +/** Keys of the jobs that have not settled yet, each with the promise handed to its callers. */ +export function createRegistry() { + const pending = new Map(); + return { + get(key) { + return pending.get(key); + }, + hold(key, promise) { + pending.set(key, promise); + }, + release(key) { + pending.delete(key); + }, + }; +} diff --git a/bench/tasks/T13/files/src/jobs/retry.js b/bench/tasks/T13/files/src/jobs/retry.js new file mode 100644 index 0000000..d9579c5 --- /dev/null +++ b/bench/tasks/T13/files/src/jobs/retry.js @@ -0,0 +1,22 @@ +/** Wait before the next attempt, after `failedAttempts` failed attempts. */ +export function backoffDelay(policy, failedAttempts) { + return Math.min(policy.maxMs, policy.baseMs * policy.factor ** (failedAttempts - 1)); +} + +/** + * Called when an attempt of `job` failed: gives up when the attempts are spent, otherwise parks the + * job for its backoff and puts it back in line afterwards. + */ +export function handleFailure(job, err, { policy, clock, counters, release, requeue }) { + if (job.attempt >= policy.maxAttempts) { + job.reject(err); + return; + } + // The backoff must not hold the slot: free it before the wait starts. + release(); + counters.delayed += 1; + clock.setTimeout(() => { + counters.delayed -= 1; + requeue(job); + }, backoffDelay(policy, job.attempt)); +} diff --git a/bench/tasks/T13/files/src/jobs/slots.js b/bench/tasks/T13/files/src/jobs/slots.js new file mode 100644 index 0000000..ab1799e --- /dev/null +++ b/bench/tasks/T13/files/src/jobs/slots.js @@ -0,0 +1,28 @@ +/** Counting semaphore: at most `limit` holders at a time; waiters are served first come, first served. */ +export function createSlots(limit) { + let active = 0; + const waiters = []; + + const release = () => { + const next = waiters.shift(); + if (next) next(release); // the slot goes straight to the next waiter + else active -= 1; + }; + + return { + /** Resolves with the function that gives the slot back. */ + acquire() { + if (active < limit) { + active += 1; + return Promise.resolve(release); + } + return new Promise((resolve) => waiters.push(resolve)); + }, + get active() { + return active; + }, + get waiting() { + return waiters.length; + }, + }; +} diff --git a/bench/tasks/T13/files/test/jobs.test.js b/bench/tasks/T13/files/test/jobs.test.js new file mode 100644 index 0000000..79d38ee --- /dev/null +++ b/bench/tasks/T13/files/test/jobs.test.js @@ -0,0 +1,57 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createQueue } from '../src/jobs/queue.js'; +import { backoffDelay } from '../src/jobs/retry.js'; + +// A clock whose timers fire at once, so the tests never sleep. +const instantClock = { setTimeout: (fn) => queueMicrotask(fn) }; +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +test('runs a job and resolves with its value', async () => { + const queue = createQueue({ clock: instantClock }); + assert.equal(await queue.add('a', async () => 42), 42); +}); + +test('never runs more than `concurrency` jobs at once', async () => { + const queue = createQueue({ concurrency: 2, clock: instantClock }); + let running = 0; + let max = 0; + const work = async () => { + running += 1; + max = Math.max(max, running); + await tick(); + running -= 1; + }; + await Promise.all(['a', 'b', 'c', 'd', 'e'].map((key) => queue.add(key, work))); + assert.equal(max, 2); +}); + +test('retries a failing job', async () => { + const queue = createQueue({ concurrency: 1, maxAttempts: 3, clock: instantClock }); + const attempts = []; + const value = await queue.add('flaky', async (attempt) => { + attempts.push(attempt); + if (attempt < 3) throw new Error('not yet'); + return 'done'; + }); + assert.equal(value, 'done'); + assert.deepEqual(attempts, [1, 2, 3]); +}); + +test('rejects when the attempts are spent', async () => { + const queue = createQueue({ maxAttempts: 2, clock: instantClock }); + await assert.rejects(queue.add('bad', async () => { throw new Error('boom'); }), /boom/); +}); + +test('returns the promise of a pending job for the same key', async () => { + const queue = createQueue({ clock: instantClock }); + const first = queue.add('k', async () => 'first'); + const second = queue.add('k', async () => 'second'); + assert.equal(first, second); + assert.equal(await second, 'first'); +}); + +test('backoff grows by the factor up to the cap', () => { + const policy = { baseMs: 100, factor: 2, maxMs: 500 }; + assert.deepEqual([1, 2, 3, 4].map((n) => backoffDelay(policy, n)), [100, 200, 400, 500]); +}); diff --git a/bench/tasks/T13/hidden/queue-contract.test.js b/bench/tasks/T13/hidden/queue-contract.test.js new file mode 100644 index 0000000..064229b --- /dev/null +++ b/bench/tasks/T13/hidden/queue-contract.test.js @@ -0,0 +1,354 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createQueue } from '../src/jobs/queue.js'; + +// Everything is driven by hand: job functions return promises the test settles, and the clock only +// moves when the test advances it. `flush` lets every pending promise reaction run. +const flush = () => new Promise((resolve) => setImmediate(resolve)); + +function fakeClock() { + let now = 0; + let seq = 0; + const timers = []; + const delays = []; + const clock = { + delays, + setTimeout(fn, ms) { + delays.push(ms); + seq += 1; + timers.push({ at: now + ms, seq, fn }); + return seq; + }, + pending: () => timers.length, + nextDelay: () => Math.min(...timers.map((t) => t.at)) - now, + async advance(ms) { + const target = now + ms; + for (;;) { + await flush(); + const due = timers.filter((t) => t.at <= target).sort((a, b) => a.at - b.at || a.seq - b.seq)[0]; + if (!due) break; + timers.splice(timers.indexOf(due), 1); + now = due.at; + due.fn(); + } + now = target; + await flush(); + }, + }; + return clock; +} + +/** Job functions that stay running until the test settles them, with a count of how many run at once. */ +function tracker() { + const t = { running: 0, max: 0, open: [], started: [] }; + t.job = (name) => (attempt) => { + t.running += 1; + t.max = Math.max(t.max, t.running); + t.started.push(`${name}#${attempt}`); + return new Promise((resolve, reject) => { + const done = (settle) => (value) => { + t.running -= 1; + settle(value); + }; + t.open.push({ name, attempt, ok: done(resolve), fail: done(reject) }); + }); + }; + t.take = (name) => { + const i = t.open.findIndex((o) => o.name === name); + assert.notEqual(i, -1, `${name} should be running; running: ${t.open.map((o) => o.name).join(', ') || 'nothing'}`); + return t.open.splice(i, 1)[0]; + }; + return t; +} + +const quiet = (promise) => { + promise.catch(() => {}); + return promise; +}; + +function mulberry32(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let x = a; + x = Math.imul(x ^ (x >>> 15), x | 1); + x ^= x + Math.imul(x ^ (x >>> 7), x | 61); + return ((x ^ (x >>> 14)) >>> 0) / 4294967296; + }; +} + +test('rule 3: a job in backoff frees exactly one slot', async () => { + const clock = fakeClock(); + const t = tracker(); + const queue = createQueue({ concurrency: 1, maxAttempts: 3, backoff: { baseMs: 100 }, clock }); + const a = queue.add('a', t.job('a')); + const b = queue.add('b', t.job('b')); + const c = queue.add('c', t.job('c')); + await flush(); + assert.deepEqual(t.started, ['a#1']); + assert.deepEqual(queue.stats(), { running: 1, waiting: 2, delayed: 0 }); + + t.take('a').fail(new Error('a1')); + await flush(); + assert.deepEqual(t.started, ['a#1', 'b#1'], 'the freed slot goes to b, and only to b'); + assert.equal(t.running, 1); + assert.deepEqual(queue.stats(), { running: 1, waiting: 1, delayed: 1 }); + + t.take('b').ok('B'); + await flush(); + assert.deepEqual(t.started, ['a#1', 'b#1', 'c#1']); + await clock.advance(100); + assert.deepEqual(queue.stats(), { running: 1, waiting: 1, delayed: 0 }); + t.take('c').ok('C'); + await flush(); + assert.deepEqual(t.started, ['a#1', 'b#1', 'c#1', 'a#2']); + t.take('a').ok('A'); + assert.deepEqual(await Promise.all([a, b, c]), ['A', 'B', 'C']); + assert.equal(t.max, 1); + assert.deepEqual(queue.stats(), { running: 0, waiting: 0, delayed: 0 }); +}); + +test('rule 1: the limit holds for jobs added after a retry, with nobody waiting at the failure', async () => { + const clock = fakeClock(); + const t = tracker(); + const queue = createQueue({ concurrency: 2, maxAttempts: 2, backoff: { baseMs: 50 }, clock }); + const a = queue.add('a', t.job('a')); + queue.add('b', t.job('b')); + await flush(); + t.take('a').fail(new Error('a1')); + await flush(); + assert.deepEqual(queue.stats(), { running: 1, waiting: 0, delayed: 1 }); + queue.add('c', t.job('c')); + queue.add('d', t.job('d')); + await flush(); + assert.equal(t.running, 2, 'b and c run, d waits'); + assert.deepEqual(t.started, ['a#1', 'b#1', 'c#1']); + assert.deepEqual(queue.stats(), { running: 2, waiting: 1, delayed: 1 }); + await clock.advance(50); + assert.equal(t.running, 2); + assert.deepEqual(queue.stats(), { running: 2, waiting: 2, delayed: 0 }); + t.take('b').ok(); + await flush(); + t.take('c').ok(); + await flush(); + assert.deepEqual(t.started, ['a#1', 'b#1', 'c#1', 'd#1', 'a#2']); + t.take('a').ok('A'); + assert.equal(await a, 'A'); + assert.equal(t.max, 2); +}); + +test('rules 1 and 4: the limit holds after a job has given up', async () => { + const clock = fakeClock(); + const t = tracker(); + const queue = createQueue({ concurrency: 1, maxAttempts: 2, backoff: { baseMs: 10 }, clock }); + const a = quiet(queue.add('a', t.job('a'))); + await flush(); + t.take('a').fail(new Error('a1')); + await clock.advance(10); + t.take('a').fail(new Error('a2')); + await assert.rejects(a, /a2/); + await flush(); + assert.deepEqual(queue.stats(), { running: 0, waiting: 0, delayed: 0 }); + const rest = ['b', 'c', 'd'].map((k) => queue.add(k, t.job(k))); + await flush(); + assert.equal(t.running, 1); + assert.deepEqual(queue.stats(), { running: 1, waiting: 2, delayed: 0 }); + for (const k of ['b', 'c', 'd']) { + t.take(k).ok(k); + await flush(); + } + assert.deepEqual(await Promise.all(rest), ['b', 'c', 'd']); + assert.equal(t.max, 1); +}); + +test('rule 3: a retry queues behind the jobs that are already waiting', async () => { + const clock = fakeClock(); + const t = tracker(); + const queue = createQueue({ concurrency: 1, maxAttempts: 2, backoff: { baseMs: 100 }, clock }); + for (const k of ['a', 'b', 'c', 'd']) queue.add(k, t.job(k)); + await flush(); + t.take('a').fail(new Error('a1')); + await clock.advance(100); // b runs, c and d wait, a joins the line behind them + queue.add('e', t.job('e')); + for (const k of ['b', 'c', 'd', 'a', 'e']) { + await flush(); + t.take(k).ok(); + } + await flush(); + assert.deepEqual(t.started, ['a#1', 'b#1', 'c#1', 'd#1', 'a#2', 'e#1']); +}); + +test('rules 2 and 4: backoff delays, the cap, and rejection with the last error', async () => { + const clock = fakeClock(); + const queue = createQueue({ concurrency: 2, maxAttempts: 5, backoff: { baseMs: 100, factor: 2, maxMs: 500 }, clock }); + const attempts = []; + const p = quiet(queue.add('k', (attempt) => { + attempts.push(attempt); + if (attempt % 2 === 0) throw new Error(`sync ${attempt}`); // a synchronous throw is a failed attempt + return Promise.reject(new Error(`async ${attempt}`)); + })); + await flush(); + assert.deepEqual(attempts, [1]); + await clock.advance(99); + assert.deepEqual(attempts, [1], 'no retry before the delay has passed'); + await clock.advance(1); + assert.deepEqual(attempts, [1, 2]); + await clock.advance(10_000); + assert.deepEqual(attempts, [1, 2, 3, 4, 5]); + assert.deepEqual(clock.delays, [100, 200, 400, 500]); + await assert.rejects(p, /^Error: async 5$/); + assert.equal(clock.pending(), 0); + assert.deepEqual(queue.stats(), { running: 0, waiting: 0, delayed: 0 }); +}); + +test('rule 5: a pending key is de-duplicated while waiting, running and in backoff', async () => { + const clock = fakeClock(); + const t = tracker(); + const queue = createQueue({ concurrency: 1, maxAttempts: 2, backoff: { baseMs: 100 }, clock }); + let extra = 0; + const never = () => { + extra += 1; + return 'duplicate'; + }; + const a = queue.add('a', t.job('a')); + const b = queue.add('b', t.job('b')); + await flush(); + assert.equal(queue.add('b', never), b, 'b is waiting for a slot'); + assert.equal(queue.add('a', never), a, 'a is running'); + t.take('a').fail(new Error('a1')); + await flush(); + assert.deepEqual(queue.stats(), { running: 1, waiting: 0, delayed: 1 }); + assert.equal(queue.add('a', never), a, 'a is in backoff'); + await clock.advance(100); + assert.equal(queue.add('a', never), a, 'a waits for a slot again'); + t.take('b').ok('B'); + await flush(); + assert.equal(queue.add('a', never), a, 'a runs its second attempt'); + t.take('a').ok('A'); + assert.equal(await a, 'A'); + assert.equal(await b, 'B'); + await flush(); + assert.equal(extra, 0); + assert.deepEqual(t.started, ['a#1', 'b#1', 'a#2']); +}); + +test('rule 6: a key that resolved runs again as a new job', async () => { + const clock = fakeClock(); + const queue = createQueue({ clock }); + const calls = []; + const fn = (value) => (attempt) => { + calls.push(`${value}#${attempt}`); + return value; + }; + const first = queue.add('k', fn('one')); + assert.equal(await first, 'one'); + const second = queue.add('k', fn('two')); + assert.notEqual(second, first); + assert.equal(await second, 'two'); + assert.deepEqual(calls, ['one#1', 'two#1']); +}); + +test('rule 6: a key that gave up is free again and starts from attempt 1', async () => { + const clock = fakeClock(); + const queue = createQueue({ concurrency: 1, maxAttempts: 2, backoff: { baseMs: 10 }, clock }); + const calls = []; + const failing = quiet(queue.add('k', (attempt) => { + calls.push(`bad#${attempt}`); + throw new Error(`bad ${attempt}`); + })); + await clock.advance(10); + await assert.rejects(failing, /bad 2/); + await flush(); + + const again = queue.add('k', (attempt) => { + calls.push(`flaky#${attempt}`); + if (attempt === 1) throw new Error('flaky 1'); + return 'recovered'; + }); + assert.notEqual(again, failing); + await clock.advance(10); + assert.equal(await again, 'recovered'); + assert.deepEqual(calls, ['bad#1', 'bad#2', 'flaky#1', 'flaky#2']); + + const third = queue.add('k', () => 'third'); + assert.equal(await third, 'third'); +}); + +test('rule 6: the key is already free inside the handlers of the promise', async () => { + const clock = fakeClock(); + const queue = createQueue({ concurrency: 2, maxAttempts: 1, clock }); + const order = []; + const fromCatch = queue.add('k', () => Promise.reject(new Error('first'))).catch((err) => { + order.push(`caught ${err.message}`); + return queue.add('k', () => { + order.push('second ran'); + return 'second'; + }); + }); + assert.equal(await fromCatch, 'second'); + const fromThen = queue.add('ok', () => 'v1').then((v) => { + order.push(`got ${v}`); + return queue.add('ok', () => 'v2'); + }); + assert.equal(await fromThen, 'v2'); + assert.deepEqual(order, ['caught first', 'second ran', 'got v1']); +}); + +test('rules 1 to 7 together: seeded mix of failures never exceeds the limit or stalls', async () => { + for (const seed of [1, 2, 3, 4, 5, 6]) { + const random = mulberry32(seed); + const limit = 1 + (seed % 3); + const maxAttempts = 3; + const clock = fakeClock(); + const t = tracker(); + const queue = createQueue({ concurrency: limit, maxAttempts, backoff: { baseMs: 10, factor: 3, maxMs: 40 }, clock }); + const names = Array.from({ length: 14 }, (_, i) => `j${i}`); + const expected = new Map(); + const results = new Map(); + const add = (name) => { + queue.add(name, t.job(name)).then( + (v) => results.set(name, `ok ${v}`), + (e) => results.set(name, `fail ${e.message}`), + ); + }; + names.slice(0, 8).forEach(add); + let next = 8; + for (let step = 0; results.size < names.length; step += 1) { + assert.ok(step < 500, `seed ${seed}: the queue stalled with ${results.size} of ${names.length} jobs settled`); + await flush(); + if (results.size === names.length) break; + const where = `seed ${seed}, step ${step}`; + assert.ok(t.running <= limit, `${where}: ${t.running} jobs running, limit ${limit}`); + const stats = queue.stats(); + assert.equal(stats.running, t.running, `${where}: stats().running`); + assert.equal(stats.delayed, clock.pending(), `${where}: stats().delayed`); + if (stats.waiting > 0) assert.equal(t.running, limit, `${where}: jobs wait while a slot is free`); + if (next < names.length && random() < 0.3) { + add(names[next]); + next += 1; + continue; + } + if (t.open.length === 0) { + if (clock.pending() > 0) await clock.advance(clock.nextDelay()); + else if (next < names.length) { + add(names[next]); + next += 1; + } else assert.fail(`${where}: nothing is running or scheduled, but ${names.length - results.size} jobs never settled`); + continue; + } + const job = t.open.splice(Math.floor(random() * t.open.length), 1)[0]; + if (random() < 0.45) { + if (job.attempt === maxAttempts) expected.set(job.name, `fail ${job.name} failed ${job.attempt}`); + job.fail(new Error(`${job.name} failed ${job.attempt}`)); + } else { + expected.set(job.name, `ok ${job.name}@${job.attempt}`); + job.ok(`${job.name}@${job.attempt}`); + } + if (random() < 0.3 && clock.pending() > 0) await clock.advance(clock.nextDelay()); + } + await flush(); + assert.deepEqual([...results].sort(), [...expected].sort(), `seed ${seed}`); + assert.deepEqual(queue.stats(), { running: 0, waiting: 0, delayed: 0 }, `seed ${seed}`); + assert.ok(clock.delays.every((ms) => [10, 30].includes(ms)), `seed ${seed}: delays ${clock.delays}`); + } +}); diff --git a/bench/tasks/T13/solution/apply.ts b/bench/tasks/T13/solution/apply.ts new file mode 100644 index 0000000..6683c9e --- /dev/null +++ b/bench/tasks/T13/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 'Two root causes. handleFailure (src/jobs/retry.js) released the slot before the backoff and the runner released it again, so every retry freed two slots. And only the success path freed the key: a job that gave up kept its rejected promise registered. Settling now frees the key on every path, and the slot is released once, by the runner.'; +} diff --git a/bench/tasks/T13/solution/files/src/jobs/queue.js b/bench/tasks/T13/solution/files/src/jobs/queue.js new file mode 100644 index 0000000..a8b9d38 --- /dev/null +++ b/bench/tasks/T13/solution/files/src/jobs/queue.js @@ -0,0 +1,79 @@ +/** + * Job queue: bounded concurrency, retry with backoff, de-duplication by key. + * + * const queue = createQueue({ concurrency, maxAttempts, backoff: { baseMs, factor, maxMs }, clock }); + * const result = await queue.add(key, fn); + * + * Contract: + * 1. Concurrency. At most `concurrency` job functions are running at any moment. A job function is + * called as `fn(attempt)`, with attempt = 1, 2, ...; it may return a value or a promise, and a + * synchronous throw is a failed attempt like a rejection. Jobs waiting for a slot start in the + * order in which they began to wait. + * 2. Retry. A failed attempt is retried until `maxAttempts` attempts have been made. The wait before + * attempt n + 1 is min(maxMs, baseMs * factor ** (n - 1)) milliseconds, scheduled with one + * `clock.setTimeout(fn, ms)` call and with nothing else (no real timers). + * 3. Backoff does not hold a slot. While a job waits out its backoff its slot is free for other + * jobs. When the wait ends the job queues for a slot like a newly added job, behind the jobs + * that are already waiting. + * 4. Giving up. When attempt number `maxAttempts` fails, the promise rejects with the error of that + * last attempt and the job function is not called again. + * 5. De-duplication. While a job is pending (waiting for a slot, running or in backoff), `add` with + * the same key does not call the new function: it returns the promise of the pending job (the + * same object). + * 6. Key reuse. A key is free again as soon as its job settles, whether it resolved or rejected: + * the next `add` with that key runs its function as a new job, with attempts counted from 1. + * Nothing is cached. The key is already free when the handlers of the promise run, so a `then` + * or `catch` handler may add the same key again. + * 7. `stats()` returns `{ running, waiting, delayed }`: the jobs whose function is running, the jobs + * waiting for a slot and the jobs in backoff. + */ +import { systemClock } from './clock.js'; +import { createRegistry } from './registry.js'; +import { handleFailure } from './retry.js'; +import { createSlots } from './slots.js'; + +export function createQueue({ concurrency = 4, maxAttempts = 3, backoff = {}, clock = systemClock } = {}) { + if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer'); + if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new RangeError('maxAttempts must be a positive integer'); + const policy = { maxAttempts, baseMs: backoff.baseMs ?? 100, factor: backoff.factor ?? 2, maxMs: backoff.maxMs ?? 30_000 }; + const slots = createSlots(concurrency); + const keys = createRegistry(); + const counters = { delayed: 0 }; + + async function run(job) { + const release = await slots.acquire(); + job.attempt += 1; + try { + job.resolve(await job.fn(job.attempt)); + } catch (err) { + handleFailure(job, err, { policy, clock, counters, requeue: run }); + } finally { + release(); + } + } + + function add(key, fn) { + const pending = keys.get(key); + if (pending) return pending; + const job = { key, fn, attempt: 0, resolve: null, reject: null }; + const promise = new Promise((resolve, reject) => { + // Settling is what frees the key, on every path: success here, giving up in retry.js. + job.resolve = (value) => { + keys.release(key); + resolve(value); + }; + job.reject = (err) => { + keys.release(key); + reject(err); + }; + }); + keys.hold(key, promise); + void run(job); + return promise; + } + + return { + add, + stats: () => ({ running: slots.active, waiting: slots.waiting, delayed: counters.delayed }), + }; +} diff --git a/bench/tasks/T13/solution/files/src/jobs/retry.js b/bench/tasks/T13/solution/files/src/jobs/retry.js new file mode 100644 index 0000000..17e2871 --- /dev/null +++ b/bench/tasks/T13/solution/files/src/jobs/retry.js @@ -0,0 +1,21 @@ +/** Wait before the next attempt, after `failedAttempts` failed attempts. */ +export function backoffDelay(policy, failedAttempts) { + return Math.min(policy.maxMs, policy.baseMs * policy.factor ** (failedAttempts - 1)); +} + +/** + * Called when an attempt of `job` failed: gives up when the attempts are spent, otherwise parks the + * job for its backoff and puts it back in line afterwards. + */ +export function handleFailure(job, err, { policy, clock, counters, requeue }) { + if (job.attempt >= policy.maxAttempts) { + job.reject(err); + return; + } + // The slot is given back by the runner as soon as this returns, so the backoff does not hold it. + counters.delayed += 1; + clock.setTimeout(() => { + counters.delayed -= 1; + requeue(job); + }, backoffDelay(policy, job.attempt)); +} diff --git a/bench/tasks/T13/verify.ts b/bench/tasks/T13/verify.ts new file mode 100644 index 0000000..5c9003b --- /dev/null +++ b/bench/tasks/T13/verify.ts @@ -0,0 +1,18 @@ +import path from 'node:path'; +import { checkScope, Checks, runHiddenTests, runNodeTests } from '../checks.ts'; +import { filesFrom } from '../setup.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export const T13_FILES = path.join(import.meta.dirname, 'files'); +const HIDDEN = Object.fromEntries(filesFrom(path.join(import.meta.dirname, 'hidden'))); + +/** Hidden tests check every rule of the contract in src/jobs/queue.js with a fake clock, not just the two reported symptoms. */ +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 ? `: ${hidden.failed.join('; ')}` : ''})`); + await checkScope(checks, ctx.workspace, ctx.initial, (f) => f.startsWith('src/jobs/')); + return checks.result(); +} diff --git a/bench/tasks/T14/files/src/lib/csv.js b/bench/tasks/T14/files/src/lib/csv.js new file mode 100644 index 0000000..ec0e6b2 --- /dev/null +++ b/bench/tasks/T14/files/src/lib/csv.js @@ -0,0 +1,18 @@ +/** Thrown for invalid CSV and for calls on a parser that has failed or ended. */ +export class CsvError extends Error { + constructor(message) { + super(message); + this.name = 'CsvError'; + } +} + +/** Returns a streaming parser: `{ push(chunk), end() }`. */ +export function createCsvParser() { + throw new Error('not implemented'); +} + +/** Parses a complete input and returns all its records. */ +export function parseCsv(text) { + const parser = createCsvParser(); + return [...parser.push(text), ...parser.end()]; +} diff --git a/bench/tasks/T14/files/test/csv.test.js b/bench/tasks/T14/files/test/csv.test.js new file mode 100644 index 0000000..3d4a7ca --- /dev/null +++ b/bench/tasks/T14/files/test/csv.test.js @@ -0,0 +1,14 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createCsvParser, parseCsv } from '../src/lib/csv.js'; + +test('parses plain and quoted fields', () => { + assert.deepEqual(parseCsv('id,name\r\n1,"Doe, Jane"\r\n'), [['id', 'name'], ['1', 'Doe, Jane']]); +}); + +test('push returns the records each chunk completes', () => { + const parser = createCsvParser(); + assert.deepEqual(parser.push('a,b\nc'), [['a', 'b']]); + assert.deepEqual(parser.push(',d'), []); + assert.deepEqual(parser.end(), [['c', 'd']]); +}); diff --git a/bench/tasks/T14/hidden/csv-rules.test.js b/bench/tasks/T14/hidden/csv-rules.test.js new file mode 100644 index 0000000..8231994 --- /dev/null +++ b/bench/tasks/T14/hidden/csv-rules.test.js @@ -0,0 +1,311 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createCsvParser, CsvError, parseCsv } from '../src/lib/csv.js'; + +/** Feeds the chunks and returns what each call returned: `{ pushes: [...], end }`, or `'CsvError'` in place of a call that threw one. */ +function feed(chunks) { + const parser = createCsvParser(); + const call = (fn) => { + try { + return fn(); + } catch (err) { + if (err instanceof CsvError) return 'CsvError'; + throw err; + } + }; + const pushes = chunks.map((chunk) => call(() => parser.push(chunk))); + return { pushes, end: call(() => parser.end()) }; +} + +const show = (value) => JSON.stringify(value); + +test('rule 2: fields, record ends and empty lines', () => { + assert.deepEqual(parseCsv('a,b,c\n1,2,3\n'), [['a', 'b', 'c'], ['1', '2', '3']]); + assert.deepEqual(parseCsv('a,b\r\nc,d\r\n'), [['a', 'b'], ['c', 'd']]); + assert.deepEqual(parseCsv('a\r\nb\nc\r\n'), [['a'], ['b'], ['c']]); + assert.deepEqual(parseCsv('a\n\nb\n'), [['a'], [''], ['b']]); + assert.deepEqual(parseCsv('\n'), [['']]); + assert.deepEqual(parseCsv('\r\n\r\n'), [[''], ['']]); + assert.deepEqual(parseCsv(',\n,,\n'), [['', ''], ['', '', '']]); + assert.deepEqual(parseCsv('a,b,c\nd\ne,f\n'), [['a', 'b', 'c'], ['d'], ['e', 'f']]); +}); + +test('rule 1: nothing is trimmed and no other character is special', () => { + assert.deepEqual(parseCsv(' a , b\t\n'), [[' a ', ' b\t']]); + assert.deepEqual(parseCsv('id,x\n'), [['id', 'x']]); + assert.deepEqual(parseCsv("it's;a|b\\n,'q'\n"), [["it's;a|b\\n", "'q'"]]); + assert.deepEqual(parseCsv('a,\u{1F600}é\0\n'), [['a', '\u{1F600}é\0']]); +}); + +test('rule 3: quoted fields', () => { + assert.deepEqual(parseCsv('"a","b"\n'), [['a', 'b']]); + assert.deepEqual(parseCsv('"a,b",c\n'), [['a,b', 'c']]); + assert.deepEqual(parseCsv('"say ""hi""",x\n'), [['say "hi"', 'x']]); + assert.deepEqual(parseCsv('""""\n'), [['"']]); + assert.deepEqual(parseCsv('"""",""""""\n'), [['"', '""']]); + assert.deepEqual(parseCsv('"line 1\nline 2","cr\rlf\r\nend"\r\n'), [['line 1\nline 2', 'cr\rlf\r\nend']]); + assert.deepEqual(parseCsv('"",""\n""\n'), [['', ''], ['']]); + assert.deepEqual(parseCsv('a,"",b\n'), [['a', '', 'b']]); + assert.deepEqual(parseCsv('" a "\n'), [[' a ']]); + assert.deepEqual(parseCsv('"a"\r\n"b"'), [['a'], ['b']]); +}); + +test('rule 4: push returns the records completed by the chunk', () => { + assert.deepEqual(feed(['a,b\nc,d\ne', ',f\n', 'g']), { pushes: [[['a', 'b'], ['c', 'd']], [['e', 'f']], []], end: [['g']] }); + assert.deepEqual(feed(['', 'a', '', '\n', '']), { pushes: [[], [], [], [['a']], []], end: [] }); + assert.deepEqual(feed(['a\r', '\n']), { pushes: [[], [['a']]], end: [] }, 'the record is completed by the line feed'); + assert.deepEqual(feed(['"a"', '\n']), { pushes: [[], [['a']]], end: [] }); + assert.deepEqual(feed(['"a\n', 'b"\n']), { pushes: [[], [['a\nb']]], end: [] }, 'a line feed inside quotes ends nothing'); + const parser = createCsvParser(); + const first = parser.push('a\n'); + first[0].push('changed'); + assert.deepEqual(parser.push('b\n'), [['b']]); +}); + +test('rule 1: a chunk may end anywhere', () => { + assert.deepEqual(feed(['"a"', '"b"\n']), { pushes: [[], [['a"b']]], end: [] }, 'between the two quotes of ""'); + assert.deepEqual(feed(['"', '"', '"', '"', '\n']), { pushes: [[], [], [], [], [['"']]], end: [] }); + assert.deepEqual(feed(['"a"', ',b\n']), { pushes: [[], [['a', 'b']]], end: [] }); + assert.deepEqual(feed(['a\r', '\nb\r', '\n']), { pushes: [[], [['a']], [['b']]], end: [] }, 'between \\r and \\n'); + assert.deepEqual(feed(['"a"\r', '\n']), { pushes: [[], [['a']]], end: [] }); + assert.deepEqual(feed(['"a\r', '\nb"', '\r', '\n']), { pushes: [[], [], [], [['a\r\nb']]], end: [] }); + assert.deepEqual(feed(['x\uD83D', '\uDE00y\n']), { pushes: [[], [['x\u{1F600}y']]], end: [] }, 'inside a surrogate pair'); + assert.deepEqual(feed(['a,', '', 'b', ',', '\n']), { pushes: [[], [], [], [], [['a', 'b', '']]], end: [] }); + const text = 'id,"na""me"\r\n1,"x\r\ny"\r\n,\n"",z'; + const whole = parseCsv(text); + assert.deepEqual(whole, [['id', 'na"me'], ['1', 'x\r\ny'], ['', ''], ['', 'z']]); + const byChar = feed([...text].flatMap((c) => c.split(''))); + assert.deepEqual([...byChar.pushes.flat(), ...byChar.end], whole); +}); + +test('rule 5: end returns the unterminated last record, and a final newline adds nothing', () => { + assert.deepEqual(feed([]), { pushes: [], end: [] }); + assert.deepEqual(feed(['']), { pushes: [[]], end: [] }); + assert.deepEqual(parseCsv(''), []); + assert.deepEqual(feed(['a,b\n']), { pushes: [[['a', 'b']]], end: [] }); + assert.deepEqual(feed(['a,b\r\n']), { pushes: [[['a', 'b']]], end: [] }); + assert.deepEqual(feed(['a,b']), { pushes: [[]], end: [['a', 'b']] }); + assert.deepEqual(feed(['a,']), { pushes: [[]], end: [['a', '']] }); + assert.deepEqual(feed([',']), { pushes: [[]], end: [['', '']] }); + assert.deepEqual(feed(['a\n""']), { pushes: [[['a']]], end: [['']] }); + assert.deepEqual(feed(['a\n"b"']), { pushes: [[['a']]], end: [['b']] }); + assert.deepEqual(feed(['a\n\n']), { pushes: [[['a'], ['']]], end: [] }); + assert.deepEqual(feed(['"a\n"']), { pushes: [[]], end: [['a\n']] }); +}); + +test('rule 6: invalid input throws CsvError from the call that receives the offending character', () => { + assert.deepEqual(feed(['a"b\n']), { pushes: ['CsvError'], end: 'CsvError' }, '(a)'); + assert.deepEqual(feed(['x\na', '"', 'b']), { pushes: [[['x']], 'CsvError', 'CsvError'], end: 'CsvError' }, '(a)'); + assert.deepEqual(feed([' "a"\n']), { pushes: ['CsvError'], end: 'CsvError' }, '(a) a space before the quote makes the field unquoted'); + assert.deepEqual(feed(['a,b"']), { pushes: ['CsvError'], end: 'CsvError' }, '(a)'); + assert.deepEqual(feed(['"a"b\n']), { pushes: ['CsvError'], end: 'CsvError' }, '(b)'); + assert.deepEqual(feed(['"a"', ' ', ',b\n']), { pushes: [[], 'CsvError', 'CsvError'], end: 'CsvError' }, '(b)'); + assert.deepEqual(feed(['"a""', '"x']), { pushes: [[], 'CsvError'], end: 'CsvError' }, '(b) "a"" then " closes the field, x follows'); + assert.deepEqual(feed(['a\rb\n']), { pushes: ['CsvError'], end: 'CsvError' }, '(c)'); + assert.deepEqual(feed(['a\r', 'b']), { pushes: [[], 'CsvError'], end: 'CsvError' }, '(c) the character after the \\r is the offending one'); + assert.deepEqual(feed(['a\r', '\r\n']), { pushes: [[], 'CsvError'], end: 'CsvError' }, '(c)'); + assert.deepEqual(feed(['"a"\r', ',']), { pushes: [[], 'CsvError'], end: 'CsvError' }, '(c)'); + assert.deepEqual(feed(['a\n', 'b\r']), { pushes: [[['a']], []], end: 'CsvError' }, '(c) at the end of the input'); + assert.deepEqual(feed(['\r']), { pushes: [[]], end: 'CsvError' }, '(c)'); + assert.deepEqual(feed(['a\n"b']), { pushes: [[['a']]], end: 'CsvError' }, '(d)'); + assert.deepEqual(feed(['"']), { pushes: [[]], end: 'CsvError' }, '(d)'); + assert.deepEqual(feed(['"a""']), { pushes: [[]], end: 'CsvError' }, '(d) the last two quotes are an escaped quote'); + assert.deepEqual(feed(['"a,b\n', 'c\n']), { pushes: [[], []], end: 'CsvError' }, '(d)'); + assert.throws(() => parseCsv('a,"b'), CsvError); + assert.throws(() => parseCsv('a,b\n"c"d'), CsvError); + assert.ok(new CsvError('x') instanceof Error); +}); + +test('rule 7: a failed or ended parser, and chunks that are not strings', () => { + const failed = createCsvParser(); + assert.throws(() => failed.push('a"'), CsvError); + assert.throws(() => failed.push('ok\n'), CsvError); + assert.throws(() => failed.push(''), CsvError); + assert.throws(() => failed.end(), CsvError); + assert.throws(() => failed.end(), CsvError); + + const ended = createCsvParser(); + assert.deepEqual(ended.push('a\n'), [['a']]); + assert.deepEqual(ended.end(), []); + assert.throws(() => ended.push('b\n'), CsvError); + assert.throws(() => ended.push(''), CsvError); + assert.throws(() => ended.end(), CsvError); + + const endFailed = createCsvParser(); + endFailed.push('"open'); + assert.throws(() => endFailed.end(), CsvError); + assert.throws(() => endFailed.push('"'), CsvError); + assert.throws(() => endFailed.end(), CsvError); + + const parser = createCsvParser(); + assert.deepEqual(parser.push('a,"b'), []); + for (const bad of [undefined, null, 1, ['x'], { length: 1, 0: 'x' }, Buffer.from('x'), new String('x')]) { + assert.throws(() => parser.push(bad), (err) => err instanceof TypeError && !(err instanceof CsvError), `push(${show(bad)})`); + } + assert.deepEqual(parser.push('"\n'), [['a', 'b']], 'the parser is as it was before the bad chunks'); + assert.deepEqual(parser.end(), []); +}); + +test('rule 8: parseCsv is one push and end', () => { + assert.deepEqual(parseCsv('a,b\n"c\n""d""",e'), [['a', 'b'], ['c\n"d"', 'e']]); + assert.throws(() => parseCsv('a\r'), CsvError); +}); + +// ---- Seeded fuzz ---- + +function mulberry32(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let x = a; + x = Math.imul(x ^ (x >>> 15), x | 1); + x ^= x + Math.imul(x ^ (x >>> 7), x | 61); + return ((x ^ (x >>> 14)) >>> 0) / 4294967296; + }; +} +const int = (random, min, max) => min + Math.floor(random() * (max - min + 1)); +const pick = (random, items) => items[int(random, 0, items.length - 1)]; + +/** Cuts `text` into chunks at random UTF-16 offsets; some chunks are empty. */ +function cut(random, text) { + const style = random(); + if (style < 0.15) return text.split(''); + const chunks = []; + let i = 0; + while (i < text.length) { + const size = random() < 0.15 ? 0 : int(random, 1, style < 0.6 ? 3 : 9); + chunks.push(text.slice(i, i + size)); + i += size; + } + if (random() < 0.2) chunks.push(''); + return chunks; +} + +/** + * Reference reading of the rules over the whole text at once, by searching for delimiters instead + * of stepping through states. Returns the records, each with the offset just past its record end + * (or 'end' for an unterminated last record), and where the input is invalid: the offset of the + * offending character, 'end' when only the end of the input reveals it, or null. + */ +function wholeText(text) { + const records = []; + const n = text.length; + const plain = /[^,"\r\n]*/y; + let i = 0; + while (i < n) { + const fields = []; + for (;;) { + let value = ''; + if (text[i] === '"') { + let from = i + 1; + for (;;) { + const quote = text.indexOf('"', from); + if (quote === -1) return { records, error: 'end' }; + value += text.slice(from, quote); + if (text[quote + 1] !== '"') { + i = quote + 1; + break; + } + value += '"'; + from = quote + 2; + } + if (i < n && text[i] !== ',' && text[i] !== '\r' && text[i] !== '\n') return { records, error: i }; + } else { + plain.lastIndex = i; + value = plain.exec(text)[0]; + i += value.length; + if (text[i] === '"') return { records, error: i }; + } + fields.push(value); + if (i >= n) { + records.push({ fields, end: 'end' }); + return { records, error: null }; + } + if (text[i] === ',') { + i += 1; + continue; + } + if (text[i] === '\r') { + if (i + 1 >= n) return { records, error: 'end' }; + if (text[i + 1] !== '\n') return { records, error: i + 1 }; + i += 1; + } + i += 1; + break; + } + records.push({ fields, end: i }); + } + return { records, error: null }; +} + +/** What each call must return for these chunks, from the whole-text reading. */ +function expectedCalls(chunks) { + const { records, error } = wholeText(chunks.join('')); + let start = 0; + let failed = false; + const pushes = chunks.map((chunk) => { + const stop = start + chunk.length; + if (failed || (typeof error === 'number' && error >= start && error < stop)) { + failed = true; + start = stop; + return 'CsvError'; + } + const done = records.filter((r) => r.end !== 'end' && r.end > start && r.end <= stop).map((r) => r.fields); + start = stop; + return done; + }); + const end = failed || error === 'end' ? 'CsvError' : records.filter((r) => r.end === 'end').map((r) => r.fields); + return { pushes, end }; +} + +test('the whole-text reading used by the fuzz agrees with the rules', () => { + assert.deepEqual(wholeText('a,"b""c"\r\n\n,x'), { records: [{ fields: ['a', 'b"c'], end: 10 }, { fields: [''], end: 11 }, { fields: ['', 'x'], end: 'end' }], error: null }); + assert.equal(wholeText('a\n"b"c').error, 5); + assert.equal(wholeText('ab"').error, 2); + assert.equal(wholeText('a\rb').error, 2); + assert.equal(wholeText('a\r').error, 'end'); + assert.equal(wholeText('"a').error, 'end'); +}); + +test('fuzz: built records, serialized with random quoting and record ends, in random chunks', () => { + const random = mulberry32(0x5eed01); + const pieces = ['a', 'b', 'xyz', ' ', ',', '"', '""', '\r', '\n', '\r\n', 'é', '\u{1F600}', '\t', "'"]; + for (let round = 0; round < 1500; round += 1) { + const records = Array.from({ length: int(random, 0, 5) }, () => + Array.from({ length: int(random, 1, 4) }, () => Array.from({ length: int(random, 0, 4) }, () => pick(random, pieces)).join('')), + ); + const terminated = random() < 0.5; + let text = ''; + records.forEach((fields, r) => { + const last = r === records.length - 1; + const loneEmpty = fields.length === 1 && fields[0] === ''; + text += fields.map((f) => (/[,"\r\n]/.test(f) || random() < 0.25 || (loneEmpty && last && !terminated) ? `"${f.replaceAll('"', '""')}"` : f)).join(','); + if (!last || terminated) text += random() < 0.5 ? '\r\n' : '\n'; + }); + const chunks = cut(random, text); + const got = feed(chunks); + const where = `round ${round}, chunks ${show(chunks)}`; + assert.ok(got.end !== 'CsvError' && !got.pushes.includes('CsvError'), `${where}: valid input threw CsvError`); + assert.deepEqual([...got.pushes.flat(), ...got.end], records, where); + assert.deepEqual(got, expectedCalls(chunks), `${where}: records per call`); + assert.deepEqual(parseCsv(text), records, `round ${round}, text ${show(text)}`); + } +}); + +test('fuzz: random text, valid or not, in random chunks', () => { + const random = mulberry32(0x5eed02); + const pieces = ['a', 'b', ',', ',', '"', '"', '""', '\r', '\n', '\n', '\r\n', '\r\n', ' ', '\u{1F600}']; + let invalid = 0; + for (let round = 0; round < 4000; round += 1) { + const text = Array.from({ length: int(random, 0, 12) }, () => pick(random, pieces)).join(''); + const whole = wholeText(text); + if (whole.error !== null) invalid += 1; + for (let variant = 0; variant < 2; variant += 1) { + const chunks = variant === 0 ? [text] : cut(random, text); + assert.deepEqual(feed(chunks), expectedCalls(chunks), `round ${round}, chunks ${show(chunks)}`); + } + if (whole.error === null) assert.deepEqual(parseCsv(text), whole.records.map((r) => r.fields), `round ${round}, text ${show(text)}`); + else assert.throws(() => parseCsv(text), CsvError, `round ${round}, text ${show(text)}`); + } + assert.ok(invalid > 500 && invalid < 3500, `the fuzz mixes valid and invalid inputs (invalid: ${invalid})`); +}); diff --git a/bench/tasks/T14/solution/apply.ts b/bench/tasks/T14/solution/apply.ts new file mode 100644 index 0000000..ef1c2a3 --- /dev/null +++ b/bench/tasks/T14/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 the streaming CSV parser as a character state machine that keeps a pending quote or carriage return across chunks.'; +} diff --git a/bench/tasks/T14/solution/files/src/lib/csv.js b/bench/tasks/T14/solution/files/src/lib/csv.js new file mode 100644 index 0000000..059ed6c --- /dev/null +++ b/bench/tasks/T14/solution/files/src/lib/csv.js @@ -0,0 +1,113 @@ +/** Thrown for invalid CSV and for calls on a parser that has failed or ended. */ +export class CsvError extends Error { + constructor(message) { + super(message); + this.name = 'CsvError'; + } +} + +// Where the parser stands between two characters. QUOTE and CR are the two states that need the +// next character to be decided, so they are what survives a chunk boundary. +const RECORD_START = 0; // nothing of the current record has been read +const FIELD_START = 1; // right after a comma +const UNQUOTED = 2; +const QUOTED = 3; +const QUOTE = 4; // a quote inside a quoted field: the closing quote, or the first half of "" +const CR = 5; // a carriage return outside quotes: must be followed by a line feed +const DEAD = 6; // failed or ended + +/** Returns a streaming parser: `{ push(chunk), end() }`. */ +export function createCsvParser() { + let state = RECORD_START; + let field = ''; + let record = []; + + const fail = (message) => { + state = DEAD; + throw new CsvError(message); + }; + const endField = () => { + record.push(field); + field = ''; + }; + + function push(chunk) { + if (typeof chunk !== 'string') throw new TypeError('chunk must be a string'); + if (state === DEAD) throw new CsvError('the parser has failed or ended'); + const out = []; + const endRecord = () => { + out.push(record); + record = []; + state = RECORD_START; + }; + for (let i = 0; i < chunk.length; i += 1) { + const c = chunk[i]; + switch (state) { + case RECORD_START: + case FIELD_START: + case UNQUOTED: + if (c === ',') { + endField(); + state = FIELD_START; + } else if (c === '\n') { + endField(); + endRecord(); + } else if (c === '\r') { + endField(); + state = CR; + } else if (c === '"') { + if (state === UNQUOTED) fail('quote inside an unquoted field'); + state = QUOTED; + } else { + field += c; + state = UNQUOTED; + } + break; + case QUOTED: + if (c === '"') state = QUOTE; + else field += c; + break; + case QUOTE: + if (c === '"') { + field += '"'; + state = QUOTED; + } else if (c === ',') { + endField(); + state = FIELD_START; + } else if (c === '\n') { + endField(); + endRecord(); + } else if (c === '\r') { + endField(); + state = CR; + } else fail('unexpected character after a closing quote'); + break; + default: // CR + if (c === '\n') endRecord(); + else fail('carriage return without a line feed'); + } + } + return out; + } + + function end() { + if (state === DEAD) throw new CsvError('the parser has failed or ended'); + if (state === QUOTED) fail('the input ends inside a quoted field'); + if (state === CR) fail('carriage return without a line feed'); + const out = []; + if (state !== RECORD_START) { + endField(); + out.push(record); + } + state = DEAD; + return out; + } + + return { push, end }; +} + +/** Parses a complete input and returns all its records. */ +export function parseCsv(text) { + const parser = createCsvParser(); + return [...parser.push(text), ...parser.end()]; +} diff --git a/bench/tasks/T14/verify.ts b/bench/tasks/T14/verify.ts new file mode 100644 index 0000000..52c6016 --- /dev/null +++ b/bench/tasks/T14/verify.ts @@ -0,0 +1,18 @@ +import path from 'node:path'; +import { checkScope, Checks, runHiddenTests, runNodeTests } from '../checks.ts'; +import { filesFrom } from '../setup.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export const T14_FILES = path.join(import.meta.dirname, 'files'); +const HIDDEN = Object.fromEntries(filesFrom(path.join(import.meta.dirname, 'hidden'))); + +/** Hidden tests have hand-written cases for each rule of the prompt and a seeded fuzz with random chunk cuts against an independent oracle. */ +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 ? `: ${hidden.failed.join('; ')}` : ''})`); + await checkScope(checks, ctx.workspace, ctx.initial, (f) => f === 'src/lib/csv.js'); + return checks.result(); +} diff --git a/bench/tasks/T15/files/src/lib/http.js b/bench/tasks/T15/files/src/lib/http.js new file mode 100644 index 0000000..f21d46a --- /dev/null +++ b/bench/tasks/T15/files/src/lib/http.js @@ -0,0 +1,77 @@ +/** + * HTTP client of the services. This is the only supported way to call another system. + * + * `request(options)` returns a promise of `{ status, headers, body }`. + * + * Options (an unknown option rejects with a TypeError): + * - `url`: required string. + * - `method`: 'GET' (default), 'POST', 'PUT', 'PATCH' or 'DELETE', in upper case. Anything else, + * lower case included, rejects with a TypeError. + * - `headers`: object of header name to value. Names are lower-cased before they are sent. + * - `query`: object of query parameters. Entries whose value is undefined or null are dropped, the + * other values are sent as strings. + * - `body`: the payload, sent as it is. No content-type header is added for it. + * - `timeoutMs`: a positive finite number of milliseconds. Left out (or undefined) it is 30000. + * Anything else (0, NaN, a string) rejects with a TypeError. + * + * A response whose status is 400 or above rejects with an `HttpError` that carries `status` and + * `body`. Every other failure (a TypeError for bad options, an error thrown by the transport) is + * not an `HttpError`. + * + * The transport is the function that performs the call. Tests replace it with `setTransport(fn)`: + * `fn` gets `{ method, url, headers, query, body, timeoutMs }` after the rules above were applied + * and returns (a promise of) `{ status, headers, body }`. + */ + +const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']); +const OPTIONS = new Set(['url', 'method', 'headers', 'query', 'body', 'timeoutMs']); +const DEFAULT_TIMEOUT_MS = 30000; + +export class HttpError extends Error { + constructor(status, body) { + super(`HTTP ${status}`); + this.name = 'HttpError'; + this.status = status; + this.body = body; + } +} + +let transport = async () => { + throw new Error('no HTTP transport is configured'); +}; + +/** Replaces the transport and returns the previous one. */ +export function setTransport(fn) { + const previous = transport; + transport = fn; + return previous; +} + +function lowerCased(headers) { + const out = {}; + for (const [name, value] of Object.entries(headers)) out[name.toLowerCase()] = value; + return out; +} + +function withoutEmpty(query) { + const out = {}; + for (const [name, value] of Object.entries(query)) { + if (value !== undefined && value !== null) out[name] = String(value); + } + return out; +} + +export async function request(options) { + if (options === null || typeof options !== 'object') throw new TypeError('request takes an options object'); + for (const name of Object.keys(options)) { + if (!OPTIONS.has(name)) throw new TypeError(`unknown request option: ${name}`); + } + const { url, method = 'GET', headers = {}, query = {}, body, timeoutMs = DEFAULT_TIMEOUT_MS } = options; + if (typeof url !== 'string' || url === '') throw new TypeError('request needs a url'); + if (!METHODS.has(method)) throw new TypeError(`unsupported method: ${String(method)}`); + if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new TypeError('timeoutMs must be a positive number'); + const response = await transport({ method, url, headers: lowerCased(headers), query: withoutEmpty(query), body, timeoutMs }); + const result = { status: response.status, headers: response.headers ?? {}, body: response.body }; + if (result.status >= 400) throw new HttpError(result.status, result.body); + return result; +} diff --git a/bench/tasks/T15/files/src/lib/legacy-http.js b/bench/tasks/T15/files/src/lib/legacy-http.js new file mode 100644 index 0000000..93b7b85 --- /dev/null +++ b/bench/tasks/T15/files/src/lib/legacy-http.js @@ -0,0 +1,68 @@ +/** + * DEPRECATED. The old HTTP helpers, kept only until their last caller is gone. They are now a thin + * layer over `request` (src/lib/http.js). + * + * MIGRATION: every caller moves to `request` and then this file is deleted. Each caller imports + * `request` from src/lib/http.js and calls it directly; do not recreate `legacyFetch`, `legacyJson` + * or a wrapper like them anywhere. A caller must behave exactly as before, with the two intended + * exceptions noted below (both about error statuses the caller never handled). + * + * `legacyFetch(url, opts)` resolves to `{ status, data }` for every status; it never rejects + * because of a status. In terms of `request`: + * - `url` (positional) -> `url`. + * - `opts.method` -> `method`. The old helper took any letter case ('post', 'Delete') and + * defaulted to GET; `request` takes upper case only. + * - `opts.qs` -> `query`. + * - `opts.json` -> `body` (the value itself, not a string) plus the header + * 'content-type': 'application/json'. + * - `opts.body` -> `body`, with no header added. + * - `opts.headers` -> `headers`. + * - `opts.timeout` -> `timeoutMs`. The old value is in SECONDS: `timeoutMs` is `timeout * 1000`. + * No timeout (left out or undefined) means the default of 30 s, which is + * also the default of `request`: leave `timeoutMs` out then. + * - result `data` -> result `body`. `status` is the same. + * - Status 400 or above: `request` rejects with an `HttpError`, the old helper resolved. + * - A caller that reads `res.status` anywhere (compares it, returns it) handles error statuses: + * it must catch the `HttpError` and go on with `err.status` and `err.body` in place of + * `res.status` and `res.data`, so that it returns what it returned before for every status. + * Catch only `HttpError`: any other error must still propagate. + * - A caller that never reads `res.status` never handled error statuses (it went on with the + * error payload as if it were data, which was a bug): let the `HttpError` propagate. + * + * `legacyJson(url, opts)` takes the same options, resolves to the data alone, and rejects with + * `new Error('HTTP ')` for a status of 400 or above. Its callers become + * `(await request(...)).body`. They now reject with the `HttpError` of + * `request` instead of that plain Error. Let it propagate. + */ +import { HttpError, request } from './http.js'; + +function toRequest(url, opts) { + const options = { url, method: String(opts.method ?? 'GET').toUpperCase() }; + const headers = { ...(opts.headers ?? {}) }; + if (opts.json !== undefined) { + options.body = opts.json; + headers['content-type'] = 'application/json'; + } else if (opts.body !== undefined) { + options.body = opts.body; + } + options.headers = headers; + if (opts.qs !== undefined) options.query = opts.qs; + if (opts.timeout !== undefined) options.timeoutMs = opts.timeout * 1000; + return options; +} + +export async function legacyFetch(url, opts = {}) { + try { + const res = await request(toRequest(url, opts)); + return { status: res.status, data: res.body }; + } catch (err) { + if (err instanceof HttpError) return { status: err.status, data: err.body }; + throw err; + } +} + +export async function legacyJson(url, opts = {}) { + const res = await legacyFetch(url, opts); + if (res.status >= 400) throw new Error(`HTTP ${res.status}`); + return res.data; +} diff --git a/bench/tasks/T15/files/src/services/billing/credits.js b/bench/tasks/T15/files/src/services/billing/credits.js new file mode 100644 index 0000000..e751071 --- /dev/null +++ b/bench/tasks/T15/files/src/services/billing/credits.js @@ -0,0 +1,10 @@ +import { legacyJson } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export async function getBalance(customerId, currency = 'USD') { + const account = await legacyJson(`${API}/credits/${customerId}`, { + qs: { currency }, + headers: { 'Cache-Control': 'no-cache' }, + }); + return account.balance_cents; +} diff --git a/bench/tasks/T15/files/src/services/billing/dunning.js b/bench/tasks/T15/files/src/services/billing/dunning.js new file mode 100644 index 0000000..ac40f92 --- /dev/null +++ b/bench/tasks/T15/files/src/services/billing/dunning.js @@ -0,0 +1,11 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** + * Sends a payment reminder for an invoice. `method` is 'post' for a new reminder and 'put' to + * replace the one already scheduled. Returns the HTTP status of the reminder service. + */ +export async function sendReminder(invoiceId, { channel = 'email', method = 'post' } = {}) { + const res = await legacyFetch(`${API}/invoices/${invoiceId}/reminders`, { method, json: { channel } }); + return res.status; +} diff --git a/bench/tasks/T15/files/src/services/billing/invoices.js b/bench/tasks/T15/files/src/services/billing/invoices.js new file mode 100644 index 0000000..f085bce --- /dev/null +++ b/bench/tasks/T15/files/src/services/billing/invoices.js @@ -0,0 +1,12 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export async function getInvoice(id) { + const { data } = await legacyFetch(`${API}/invoices/${id}`, { headers: { accept: 'application/json' } }); + return data; +} + +export async function listInvoices(customerId, { from, to } = {}) { + const { data } = await legacyFetch(`${API}/invoices`, { qs: { customer: customerId, from, to } }); + return data.invoices; +} diff --git a/bench/tasks/T15/files/src/services/billing/payments.js b/bench/tasks/T15/files/src/services/billing/payments.js new file mode 100644 index 0000000..1ba283c --- /dev/null +++ b/bench/tasks/T15/files/src/services/billing/payments.js @@ -0,0 +1,16 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +const DEFAULTS = { timeout: 15, headers: { 'x-billing-version': '3' } }; + +/** Captures an authorized payment. A declined card answers 402 with a decline code. */ +export async function capturePayment(id, cents) { + const res = await legacyFetch(`${API}/payments/${id}/capture`, { ...DEFAULTS, method: 'POST', json: { amount_cents: cents } }); + if (res.status === 402) return { captured: false, declineCode: res.data.code }; + return { captured: true, receipt: res.data.receipt }; +} + +export async function voidPayment(id) { + const res = await legacyFetch(`${API}/payments/${id}`, { ...DEFAULTS, method: 'DELETE' }); + return res.status === 204; +} diff --git a/bench/tasks/T15/files/src/services/billing/subscriptions.js b/bench/tasks/T15/files/src/services/billing/subscriptions.js new file mode 100644 index 0000000..c6aa7d0 --- /dev/null +++ b/bench/tasks/T15/files/src/services/billing/subscriptions.js @@ -0,0 +1,15 @@ +import * as legacy from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export function changePlan(subscriptionId, plan) { + return legacy.legacyJson(`${API}/subscriptions/${subscriptionId}`, { method: 'PATCH', json: { plan } }); +} + +export async function pauseSubscription(subscriptionId, days) { + const sub = await legacy.legacyJson(`${API}/subscriptions/${subscriptionId}/pause`, { + method: 'post', + json: { days }, + timeout: 10, + }); + return sub.resumesAt; +} diff --git a/bench/tasks/T15/files/src/services/billing/tax-rules.js b/bench/tasks/T15/files/src/services/billing/tax-rules.js new file mode 100644 index 0000000..0a06159 --- /dev/null +++ b/bench/tasks/T15/files/src/services/billing/tax-rules.js @@ -0,0 +1,9 @@ +// Local fallback tax table, used when the tax service gives no quote. +// NOTE: keep this module pure. Do not call legacyFetch(url) or any other HTTP helper from here: +// checkout must be able to price a cart with the network down. +const RATES = { DE: 0.19, FR: 0.2, NL: 0.21, US: 0 }; + +export function fallbackTaxCents(country, netCents) { + const rate = RATES[country] ?? 0; + return Math.round(netCents * rate); +} diff --git a/bench/tasks/T15/files/src/services/billing/tax.js b/bench/tasks/T15/files/src/services/billing/tax.js new file mode 100644 index 0000000..7e39177 --- /dev/null +++ b/bench/tasks/T15/files/src/services/billing/tax.js @@ -0,0 +1,12 @@ +import { legacyFetch as callTax } from '../../lib/legacy-http.js'; +import { TAX } from '../config.js'; + +/** + * Tax of a cart, in cents. The tax service is optional at checkout: when it does not answer 200 + * within 2.5 seconds' worth of patience the caller falls back to its own table, so this returns null. + */ +export async function quoteTax(cart) { + const res = await callTax(`${TAX}/quote`, { method: 'POST', json: cart, timeout: 2.5 }); + if (res.status !== 200) return null; + return res.data.tax_cents; +} diff --git a/bench/tasks/T15/files/src/services/catalog/categories.js b/bench/tasks/T15/files/src/services/catalog/categories.js new file mode 100644 index 0000000..746aab0 --- /dev/null +++ b/bench/tasks/T15/files/src/services/catalog/categories.js @@ -0,0 +1,13 @@ +import * as legacy from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export function listCategories() { + return legacy.legacyJson(`${API}/categories`); +} + +/** Returns the category, or null when there is none with that slug. */ +export async function getCategory(slug) { + const res = await legacy.legacyFetch(`${API}/categories/${slug}`); + if (res.status === 404) return null; + return res.data; +} diff --git a/bench/tasks/T15/files/src/services/catalog/inventory.js b/bench/tasks/T15/files/src/services/catalog/inventory.js new file mode 100644 index 0000000..da28bb3 --- /dev/null +++ b/bench/tasks/T15/files/src/services/catalog/inventory.js @@ -0,0 +1,13 @@ +import { legacyJson } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +const stockUrl = (sku) => `${API}/inventory/${encodeURIComponent(sku)}`; + +export async function getStock(sku) { + const stock = await legacyJson(stockUrl(sku), { headers: { Accept: 'application/json' } }); + return stock.available; +} + +export function reserveStock(sku, qty) { + return legacyJson(`${stockUrl(sku)}/reserve`, { method: 'POST', json: { qty } }); +} diff --git a/bench/tasks/T15/files/src/services/catalog/price-cache.js b/bench/tasks/T15/files/src/services/catalog/price-cache.js new file mode 100644 index 0000000..2195a10 --- /dev/null +++ b/bench/tasks/T15/files/src/services/catalog/price-cache.js @@ -0,0 +1,10 @@ +import { legacyFetch, legacyStore } from '../../vendor/cache/legacy.js'; + +/** Price of a SKU from the in-memory cache; `load` computes it on a miss. No HTTP here. */ +export async function cachedPrice(sku, load) { + const cached = legacyFetch(`price:${sku}`); + if (cached !== undefined) return cached; + const price = await load(sku); + legacyStore(`price:${sku}`, price, 120); + return price; +} diff --git a/bench/tasks/T15/files/src/services/catalog/product-cache.js b/bench/tasks/T15/files/src/services/catalog/product-cache.js new file mode 100644 index 0000000..3a253fc --- /dev/null +++ b/bench/tasks/T15/files/src/services/catalog/product-cache.js @@ -0,0 +1,13 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { legacyFetch as cacheFetch, legacyStore } from '../../vendor/cache/legacy.js'; +import { API } from '../config.js'; + +/** Product by id, read through the in-memory cache (5 minutes). */ +export async function getCachedProduct(id) { + const key = `product:${id}`; + const hit = cacheFetch(key); + if (hit !== undefined) return hit; + const res = await legacyFetch(`${API}/products/${id}`, { timeout: 2 }); + legacyStore(key, res.data, 300); + return res.data; +} diff --git a/bench/tasks/T15/files/src/services/catalog/products.js b/bench/tasks/T15/files/src/services/catalog/products.js new file mode 100644 index 0000000..4244f14 --- /dev/null +++ b/bench/tasks/T15/files/src/services/catalog/products.js @@ -0,0 +1,12 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export async function getProduct(id) { + const res = await legacyFetch(`${API}/products/${id}`); + return res.data; +} + +export async function listProducts({ page = 1, perPage = 20 } = {}) { + const res = await legacyFetch(`${API}/products`, { qs: { page, per_page: perPage } }); + return res.data.items; +} diff --git a/bench/tasks/T15/files/src/services/catalog/reviews.js b/bench/tasks/T15/files/src/services/catalog/reviews.js new file mode 100644 index 0000000..a87d773 --- /dev/null +++ b/bench/tasks/T15/files/src/services/catalog/reviews.js @@ -0,0 +1,19 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export async function listReviews(productId, { rating, cursor } = {}) { + const opts = { qs: { product: productId } }; + if (rating !== undefined) opts.qs.rating = rating; + if (cursor) opts.qs.cursor = cursor; + const res = await legacyFetch(`${API}/reviews`, opts); + return { items: res.data.items, next: res.data.next ?? null }; +} + +/** Returns true when the review was accepted (201) and false when it was held for moderation (202). */ +export async function postReview(productId, review) { + const res = await legacyFetch(`${API}/reviews`, { + method: 'post', + json: { product: productId, rating: review.rating, text: review.text }, + }); + return res.status === 201; +} diff --git a/bench/tasks/T15/files/src/services/catalog/search.js b/bench/tasks/T15/files/src/services/catalog/search.js new file mode 100644 index 0000000..3bb0424 --- /dev/null +++ b/bench/tasks/T15/files/src/services/catalog/search.js @@ -0,0 +1,8 @@ +import { legacyFetch as get } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Full-text search. The search backend is slow to fail, so the call gives up after 3 seconds. */ +export async function searchProducts(term, limit = 10) { + const { data } = await get(`${API}/search`, { qs: { q: term, limit }, timeout: 3 }); + return data.hits; +} diff --git a/bench/tasks/T15/files/src/services/config.js b/bench/tasks/T15/files/src/services/config.js new file mode 100644 index 0000000..38f084b --- /dev/null +++ b/bench/tasks/T15/files/src/services/config.js @@ -0,0 +1,9 @@ +/** Endpoints and defaults shared by the service modules. */ +export const API = 'https://api.acme.test/v2'; +export const AUTH = 'https://auth.acme.test'; +export const TAX = 'https://tax.acme.test'; +export const CARRIER = 'https://carrier.acme.test/api'; +export const NOTIFY = 'https://notify.acme.test'; + +/** Timeout, in seconds, of the calls that are allowed to be slow. */ +export const DEFAULT_TIMEOUT_S = 8; diff --git a/bench/tasks/T15/files/src/services/notifications/digest.js b/bench/tasks/T15/files/src/services/notifications/digest.js new file mode 100644 index 0000000..fd1b88d --- /dev/null +++ b/bench/tasks/T15/files/src/services/notifications/digest.js @@ -0,0 +1,9 @@ +import { legacyFetch, legacyJson } from '../../lib/legacy-http.js'; +import { API, NOTIFY } from '../config.js'; + +/** Builds the activity digest of a user: what happened since the last digest was sent. */ +export async function buildDigest(userId) { + const prefs = await legacyJson(`${NOTIFY}/digest/${userId}/settings`); + const res = await legacyFetch(`${API}/activity`, { qs: { user: userId, since: prefs.lastDigestAt }, timeout: 6 }); + return { locale: prefs.locale, events: res.data.events }; +} diff --git a/bench/tasks/T15/files/src/services/notifications/email.js b/bench/tasks/T15/files/src/services/notifications/email.js new file mode 100644 index 0000000..6058521 --- /dev/null +++ b/bench/tasks/T15/files/src/services/notifications/email.js @@ -0,0 +1,7 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { NOTIFY } from '../config.js'; + +export async function sendEmail(to, template, vars = {}) { + const res = await legacyFetch(`${NOTIFY}/email`, { method: 'POST', json: { to, template, vars } }); + return res.data.messageId; +} diff --git a/bench/tasks/T15/files/src/services/notifications/push.js b/bench/tasks/T15/files/src/services/notifications/push.js new file mode 100644 index 0000000..5e8952f --- /dev/null +++ b/bench/tasks/T15/files/src/services/notifications/push.js @@ -0,0 +1,12 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { NOTIFY } from '../config.js'; + +/** Sends a push notification. `ttl` is in seconds; `priority` is 'high' or 'normal'. */ +export async function sendPush(deviceId, payload, { ttl, priority } = {}) { + const headers = {}; + if (ttl !== undefined) headers['x-ttl'] = String(ttl); + if (priority) headers['x-priority'] = priority; + const opts = { method: 'POST', json: { device: deviceId, payload }, headers }; + const res = await legacyFetch(`${NOTIFY}/push`, opts); + return res.data.accepted; +} diff --git a/bench/tasks/T15/files/src/services/notifications/sms.js b/bench/tasks/T15/files/src/services/notifications/sms.js new file mode 100644 index 0000000..946612d --- /dev/null +++ b/bench/tasks/T15/files/src/services/notifications/sms.js @@ -0,0 +1,9 @@ +import { legacyFetch as send } from '../../lib/legacy-http.js'; +import { NOTIFY } from '../config.js'; + +/** Sends a text message. When the provider is rate limited (429) the message is not queued. */ +export async function sendSms(number, text) { + const res = await send(`${NOTIFY}/sms`, { method: 'post', json: { number, text }, timeout: 3 }); + if (res.status === 429) return { queued: false, retryAfter: res.data.retry_after }; + return { queued: true, id: res.data.id }; +} diff --git a/bench/tasks/T15/files/src/services/notifications/templates.js b/bench/tasks/T15/files/src/services/notifications/templates.js new file mode 100644 index 0000000..2aed205 --- /dev/null +++ b/bench/tasks/T15/files/src/services/notifications/templates.js @@ -0,0 +1,11 @@ +import { legacyJson } from '../../lib/legacy-http.js'; +import { NOTIFY } from '../config.js'; + +export function getTemplate(name, locale = 'en') { + return legacyJson(`${NOTIFY}/templates/${name}`, { qs: { locale } }); +} + +export async function renderTemplate(name, vars) { + const out = await legacyJson(`${NOTIFY}/templates/${name}/render`, { method: 'POST', json: vars }); + return out.html; +} diff --git a/bench/tasks/T15/files/src/services/notifications/webhooks.js b/bench/tasks/T15/files/src/services/notifications/webhooks.js new file mode 100644 index 0000000..3f81037 --- /dev/null +++ b/bench/tasks/T15/files/src/services/notifications/webhooks.js @@ -0,0 +1,16 @@ +import * as legacy from '../../lib/legacy-http.js'; + +/** + * Delivers an event to a customer webhook. `hook` is `{ url, secret, method?, timeoutSeconds? }`: + * the method defaults to POST and a hook without `timeoutSeconds` gets the default timeout. + * Never throws for an HTTP status: the result says whether the hook accepted the event. + */ +export async function deliver(hook, event) { + const res = await legacy.legacyFetch(hook.url, { + method: hook.method ?? 'POST', + json: event, + headers: { 'x-signature': `sha1=${hook.secret}` }, + timeout: hook.timeoutSeconds, + }); + return { delivered: res.status < 400, status: res.status }; +} diff --git a/bench/tasks/T15/files/src/services/orders/cancel.js b/bench/tasks/T15/files/src/services/orders/cancel.js new file mode 100644 index 0000000..1c70709 --- /dev/null +++ b/bench/tasks/T15/files/src/services/orders/cancel.js @@ -0,0 +1,9 @@ +import * as legacy from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Cancels an order. An order that already shipped answers 409 and is not cancelled. */ +export async function cancelOrder(id, reason) { + const res = await legacy.legacyFetch(`${API}/orders/${id}`, { method: 'delete', qs: { reason } }); + if (res.status === 409) return { cancelled: false, reason: res.data.error }; + return { cancelled: true }; +} diff --git a/bench/tasks/T15/files/src/services/orders/create.js b/bench/tasks/T15/files/src/services/orders/create.js new file mode 100644 index 0000000..fa9cc42 --- /dev/null +++ b/bench/tasks/T15/files/src/services/orders/create.js @@ -0,0 +1,11 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export async function createOrder(order) { + const res = await legacyFetch(`${API}/orders`, { + method: 'POST', + json: order, + headers: { 'Idempotency-Key': order.clientRef }, + }); + return { id: res.data.id, status: res.data.status }; +} diff --git a/bench/tasks/T15/files/src/services/orders/export.js b/bench/tasks/T15/files/src/services/orders/export.js new file mode 100644 index 0000000..8c96194 --- /dev/null +++ b/bench/tasks/T15/files/src/services/orders/export.js @@ -0,0 +1,13 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Exports the orders matching a filter expression as CSV text. Large exports get two minutes. */ +export async function exportOrders(filter) { + const res = await legacyFetch(`${API}/orders/export`, { + method: 'POST', + body: filter, + headers: { 'content-type': 'text/plain', accept: 'text/csv' }, + timeout: 120, + }); + return res.data; +} diff --git a/bench/tasks/T15/files/src/services/orders/lookup.js b/bench/tasks/T15/files/src/services/orders/lookup.js new file mode 100644 index 0000000..a243486 --- /dev/null +++ b/bench/tasks/T15/files/src/services/orders/lookup.js @@ -0,0 +1,14 @@ +import { legacyFetch as http } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Returns the order, or null when it does not exist. */ +export async function findOrder(id) { + const res = await http(`${API}/orders/${id}`); + return res.status === 404 ? null : res.data; +} + +/** Orders of a customer, optionally only those in one status. */ +export async function listOrdersFor(customerId, status) { + const res = await http(`${API}/orders`, { qs: { customer: customerId, status } }); + return res.data.orders; +} diff --git a/bench/tasks/T15/files/src/services/orders/notes.js b/bench/tasks/T15/files/src/services/orders/notes.js new file mode 100644 index 0000000..a5bf517 --- /dev/null +++ b/bench/tasks/T15/files/src/services/orders/notes.js @@ -0,0 +1,11 @@ +import { legacyJson as fetchJson } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +export async function listNotes(orderId) { + const page = await fetchJson(`${API}/orders/${orderId}/notes`, { qs: { order: 'newest' } }); + return page.notes; +} + +export function addNote(orderId, text, author) { + return fetchJson(`${API}/orders/${orderId}/notes`, { method: 'Post', json: { text, author } }); +} diff --git a/bench/tasks/T15/files/src/services/orders/refunds.js b/bench/tasks/T15/files/src/services/orders/refunds.js new file mode 100644 index 0000000..806f8fc --- /dev/null +++ b/bench/tasks/T15/files/src/services/orders/refunds.js @@ -0,0 +1,12 @@ +import { legacyJson } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Refunds go through the payment provider and may take a while: 20 seconds. */ +export async function requestRefund(orderId, cents) { + const refund = await legacyJson(`${API}/orders/${orderId}/refunds`, { + method: 'POST', + json: { amount_cents: cents }, + timeout: 20, + }); + return refund.refundId; +} diff --git a/bench/tasks/T15/files/src/services/shipping/customs.js b/bench/tasks/T15/files/src/services/shipping/customs.js new file mode 100644 index 0000000..037ea23 --- /dev/null +++ b/bench/tasks/T15/files/src/services/shipping/customs.js @@ -0,0 +1,13 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { CARRIER } from '../config.js'; + +/** Files a customs declaration. `timeoutSeconds` overrides the default patience of 12 seconds. */ +export async function declare(shipmentId, items, { timeoutSeconds } = {}) { + const res = await legacyFetch(`${CARRIER}/customs/${shipmentId}`, { + method: 'POST', + json: { items }, + timeout: timeoutSeconds ?? 12, + headers: { 'X-Request-Source': 'customs' }, + }); + return res.data.declarationId; +} diff --git a/bench/tasks/T15/files/src/services/shipping/labels.js b/bench/tasks/T15/files/src/services/shipping/labels.js new file mode 100644 index 0000000..9a9ff7b --- /dev/null +++ b/bench/tasks/T15/files/src/services/shipping/labels.js @@ -0,0 +1,11 @@ +import { legacyJson } from '../../lib/legacy-http.js'; +import { CARRIER } from '../config.js'; + +export async function createLabel(shipment, carrier = 'acme-post') { + const label = await legacyJson(`${CARRIER}/labels`, { + method: 'POST', + json: { shipment: shipment.id, weight_g: shipment.weightGrams }, + headers: { 'x-carrier': carrier }, + }); + return { labelId: label.id, url: label.pdf }; +} diff --git a/bench/tasks/T15/files/src/services/shipping/pickups.js b/bench/tasks/T15/files/src/services/shipping/pickups.js new file mode 100644 index 0000000..74d9741 --- /dev/null +++ b/bench/tasks/T15/files/src/services/shipping/pickups.js @@ -0,0 +1,13 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { CARRIER } from '../config.js'; + +export async function schedulePickup(addressId, date) { + const res = await legacyFetch(`${CARRIER}/pickups`, { method: 'POST', json: { address: addressId, date } }); + return res.data.pickupId; +} + +/** Returns true when the pickup was cancelled, false when it was not (unknown id, already done). */ +export async function cancelPickup(pickupId) { + const res = await legacyFetch(`${CARRIER}/pickups/${pickupId}`, { method: 'DELETE' }); + return res.status === 204; +} diff --git a/bench/tasks/T15/files/src/services/shipping/rates.js b/bench/tasks/T15/files/src/services/shipping/rates.js new file mode 100644 index 0000000..83d43b0 --- /dev/null +++ b/bench/tasks/T15/files/src/services/shipping/rates.js @@ -0,0 +1,10 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { CARRIER } from '../config.js'; + +export async function getRates(destination, weightGrams) { + const res = await legacyFetch(`${CARRIER}/rates`, { + qs: { country: destination.country, zip: destination.zip, weight_g: weightGrams }, + timeout: 4, + }); + return res.data.rates; +} diff --git a/bench/tasks/T15/files/src/services/shipping/tracking.js b/bench/tasks/T15/files/src/services/shipping/tracking.js new file mode 100644 index 0000000..e393676 --- /dev/null +++ b/bench/tasks/T15/files/src/services/shipping/tracking.js @@ -0,0 +1,9 @@ +import * as legacy from '../../lib/legacy-http.js'; +import { CARRIER } from '../config.js'; + +/** Tracking state of a parcel. An unknown code answers 404. */ +export async function track(code) { + const res = await legacy.legacyFetch(`${CARRIER}/tracking/${code}`, { qs: { events: 'last' } }); + if (res.status === 404) return { found: false }; + return { found: true, state: res.data.state }; +} diff --git a/bench/tasks/T15/files/src/services/shipping/zones.js b/bench/tasks/T15/files/src/services/shipping/zones.js new file mode 100644 index 0000000..b8f227c --- /dev/null +++ b/bench/tasks/T15/files/src/services/shipping/zones.js @@ -0,0 +1,11 @@ +import { legacyJson as loadJson } from '../../lib/legacy-http.js'; +import { CARRIER } from '../config.js'; + +export function listZones() { + return loadJson(`${CARRIER}/zones`); +} + +export async function zoneFor(zip, country = 'US') { + const match = await loadJson(`${CARRIER}/zones/lookup`, { qs: { zip, country }, timeout: 1.5 }); + return match.zone; +} diff --git a/bench/tasks/T15/files/src/services/users/auth.js b/bench/tasks/T15/files/src/services/users/auth.js new file mode 100644 index 0000000..bacf318 --- /dev/null +++ b/bench/tasks/T15/files/src/services/users/auth.js @@ -0,0 +1,9 @@ +import { legacyFetch as post } from '../../lib/legacy-http.js'; +import { AUTH } from '../config.js'; + +/** Signs a user in. Wrong credentials answer 401. */ +export async function login(email, password) { + const res = await post(`${AUTH}/login`, { method: 'POST', json: { email, password }, timeout: 5 }); + if (res.status === 401) return { ok: false }; + return { ok: true, token: res.data.token }; +} diff --git a/bench/tasks/T15/files/src/services/users/avatars.js b/bench/tasks/T15/files/src/services/users/avatars.js new file mode 100644 index 0000000..1467140 --- /dev/null +++ b/bench/tasks/T15/files/src/services/users/avatars.js @@ -0,0 +1,12 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Uploads an avatar. `image` is the base64 text of the file and `mime` its type, e.g. image/png. */ +export async function uploadAvatar(userId, image, mime) { + const res = await legacyFetch(`${API}/users/${userId}/avatar`, { + method: 'PUT', + body: image, + headers: { 'Content-Type': mime, 'x-encoding': 'base64' }, + }); + return res.data.url; +} diff --git a/bench/tasks/T15/files/src/services/users/invites.js b/bench/tasks/T15/files/src/services/users/invites.js new file mode 100644 index 0000000..280da87 --- /dev/null +++ b/bench/tasks/T15/files/src/services/users/invites.js @@ -0,0 +1,11 @@ +import { legacyJson } from '../../lib/legacy-http.js'; +import { API, DEFAULT_TIMEOUT_S } from '../config.js'; + +export async function sendInvite(email, role = 'member') { + const invite = await legacyJson(`${API}/invites`, { + method: 'POST', + json: { email, role }, + timeout: DEFAULT_TIMEOUT_S, + }); + return invite.id; +} diff --git a/bench/tasks/T15/files/src/services/users/preferences.js b/bench/tasks/T15/files/src/services/users/preferences.js new file mode 100644 index 0000000..8049d4d --- /dev/null +++ b/bench/tasks/T15/files/src/services/users/preferences.js @@ -0,0 +1,14 @@ +import * as legacy from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +const prefsUrl = (userId) => `${API}/users/${userId}/preferences`; + +export function getPreferences(userId) { + return legacy.legacyJson(prefsUrl(userId)); +} + +/** Returns true when the preference was stored (the service answers 204). */ +export async function setPreference(userId, key, value) { + const res = await legacy.legacyFetch(`${prefsUrl(userId)}/${key}`, { method: 'PUT', json: { value } }); + return res.status === 204; +} diff --git a/bench/tasks/T15/files/src/services/users/profile.js b/bench/tasks/T15/files/src/services/users/profile.js new file mode 100644 index 0000000..bd8bffb --- /dev/null +++ b/bench/tasks/T15/files/src/services/users/profile.js @@ -0,0 +1,16 @@ +import { legacyFetch } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Returns the profile, or null for an unknown user. */ +export async function getProfile(userId) { + const res = await legacyFetch(`${API}/users/${userId}`); + if (res.status === 404) { + return null; + } + return res.data; +} + +export async function updateProfile(userId, patch) { + const res = await legacyFetch(`${API}/users/${userId}`, { method: 'PATCH', json: patch }); + return res.data; +} diff --git a/bench/tasks/T15/files/src/services/users/search.js b/bench/tasks/T15/files/src/services/users/search.js new file mode 100644 index 0000000..c39b9b9 --- /dev/null +++ b/bench/tasks/T15/files/src/services/users/search.js @@ -0,0 +1,10 @@ +import { legacyFetch as get } from '../../lib/legacy-http.js'; +import { API } from '../config.js'; + +/** Searches users by name or email. With a token the search also covers deactivated users. */ +export async function findUsers(query, { token, limit = 10 } = {}) { + const options = { qs: { q: query, limit } }; + if (token) options.headers = { authorization: `Bearer ${token}` }; + const res = await get(`${API}/users/search`, options); + return res.data.users; +} diff --git a/bench/tasks/T15/files/src/services/users/session-cache.js b/bench/tasks/T15/files/src/services/users/session-cache.js new file mode 100644 index 0000000..cf46051 --- /dev/null +++ b/bench/tasks/T15/files/src/services/users/session-cache.js @@ -0,0 +1,10 @@ +import * as cache from '../../vendor/cache/legacy.js'; + +/** Session lookups go to the in-memory cache only: cache.legacyFetch(key) is not an HTTP call. */ +export function getSession(sessionId) { + return cache.legacyFetch(`session:${sessionId}`) ?? null; +} + +export function putSession(sessionId, session) { + cache.legacyStore(`session:${sessionId}`, session, 1800); +} diff --git a/bench/tasks/T15/files/src/tools/lint-legacy.js b/bench/tasks/T15/files/src/tools/lint-legacy.js new file mode 100644 index 0000000..f8d7abc --- /dev/null +++ b/bench/tasks/T15/files/src/tools/lint-legacy.js @@ -0,0 +1,19 @@ +/** + * Source check used in CI: reports the lines of a source text that call one of the banned HTTP + * helpers. It works on text, so the banned calls are spelled out as strings here. + */ +const BANNED = ['legacyFetch(', 'legacyJson(']; + +export function findBannedCalls(source) { + const found = []; + source.split('\n').forEach((line, index) => { + for (const call of BANNED) { + if (line.includes(call)) found.push({ line: index + 1, call: call.slice(0, -1) }); + } + }); + return found; +} + +export function describeBannedCall(hit) { + return `line ${hit.line}: legacyFetch(url, opts) and legacyJson(url, opts) are deprecated (found ${hit.call})`; +} diff --git a/bench/tasks/T15/files/src/vendor/cache/legacy.js b/bench/tasks/T15/files/src/vendor/cache/legacy.js new file mode 100644 index 0000000..c44b940 --- /dev/null +++ b/bench/tasks/T15/files/src/vendor/cache/legacy.js @@ -0,0 +1,28 @@ +/** + * Vendored in-memory cache (legacy edition). Not an HTTP client: `legacyFetch` here looks a key up + * in the cache. The name comes from the upstream package and must stay, other vendored code + * imports it. + */ +const entries = new Map(); + +/** Returns the cached value of `key`, or undefined when it is missing or expired. */ +export function legacyFetch(key, opts = {}) { + const now = opts.now ?? Date.now(); + const entry = entries.get(key); + if (entry === undefined) return undefined; + if (entry.expiresAt <= now) { + entries.delete(key); + return undefined; + } + return entry.value; +} + +/** Stores `value` under `key` for `ttlSeconds`. */ +export function legacyStore(key, value, ttlSeconds = 60, opts = {}) { + const now = opts.now ?? Date.now(); + entries.set(key, { value, expiresAt: now + ttlSeconds * 1000 }); +} + +export function legacyClear() { + entries.clear(); +} diff --git a/bench/tasks/T15/files/test/services.test.js b/bench/tasks/T15/files/test/services.test.js new file mode 100644 index 0000000..fd99f78 --- /dev/null +++ b/bench/tasks/T15/files/test/services.test.js @@ -0,0 +1,66 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { setTransport } from '../src/lib/http.js'; +import { listProducts } from '../src/services/catalog/products.js'; +import { getCategory } from '../src/services/catalog/categories.js'; +import { requestRefund } from '../src/services/orders/refunds.js'; +import { cachedPrice } from '../src/services/catalog/price-cache.js'; +import { findBannedCalls } from '../src/tools/lint-legacy.js'; + +/** Answers every call with `response` and records what was sent. */ +function fakeTransport(response) { + const sent = []; + const previous = setTransport(async (req) => { + sent.push(req); + return response; + }); + return { sent, restore: () => setTransport(previous) }; +} + +test('listProducts sends the page as query parameters', async () => { + const http = fakeTransport({ status: 200, body: { items: [{ id: 'p1' }] } }); + try { + assert.deepEqual(await listProducts({ page: 2 }), [{ id: 'p1' }]); + assert.equal(http.sent[0].url, 'https://api.acme.test/v2/products'); + assert.deepEqual(http.sent[0].query, { page: '2', per_page: '20' }); + } finally { + http.restore(); + } +}); + +test('getCategory returns null for an unknown slug', async () => { + const http = fakeTransport({ status: 404, body: { error: 'not found' } }); + try { + assert.equal(await getCategory('nope'), null); + } finally { + http.restore(); + } +}); + +test('requestRefund posts the amount and waits 20 seconds', async () => { + const http = fakeTransport({ status: 201, body: { refundId: 'r-7' } }); + try { + assert.equal(await requestRefund('o-1', 1500), 'r-7'); + assert.equal(http.sent[0].method, 'POST'); + assert.deepEqual(http.sent[0].body, { amount_cents: 1500 }); + assert.equal(http.sent[0].timeoutMs, 20000); + } finally { + http.restore(); + } +}); + +test('cachedPrice loads a price once', async () => { + let loads = 0; + const load = async () => { + loads += 1; + return 1299; + }; + assert.equal(await cachedPrice('SKU-T15', load), 1299); + assert.equal(await cachedPrice('SKU-T15', load), 1299); + assert.equal(loads, 1); +}); + +test('the lint check finds the banned helpers in a source text', () => { + const hits = findBannedCalls('const a = 1;\nawait legacyFetch(url);\n'); + assert.deepEqual(hits, [{ line: 2, call: 'legacyFetch' }]); +}); diff --git a/bench/tasks/T15/hidden/behaviour.test.js b/bench/tasks/T15/hidden/behaviour.test.js new file mode 100644 index 0000000..5af770d --- /dev/null +++ b/bench/tasks/T15/hidden/behaviour.test.js @@ -0,0 +1,301 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { setTransport } from '../src/lib/http.js'; + +// What each service function must send and return after the migration. Written by hand from the +// contract in src/lib/http.js and the MIGRATION notes of src/lib/legacy-http.js: `sent` is what the +// transport receives (after `request` applied its defaults), one entry per call, in order. +const API = 'https://api.acme.test/v2'; +const AUTH = 'https://auth.acme.test'; +const TAX = 'https://tax.acme.test'; +const CARRIER = 'https://carrier.acme.test/api'; +const NOTIFY = 'https://notify.acme.test'; +const JSON_TYPE = { 'content-type': 'application/json' }; + +/** A request as the transport sees it, with the defaults of `request` filled in. */ +const req = (method, url, extra = {}) => ({ method, url, headers: {}, query: {}, body: undefined, timeoutMs: 30000, ...extra }); +const ok = (body, status = 200) => ({ status, body }); + +/** + * One case: `fn(...args)` with the transport answering `replies` in order. Exactly one of: + * `returns` (the resolved value), `httpError` (rejects with the HttpError of that status). + * `network: true` adds a second run where the transport throws: the same error must come out. + */ +const CASES = { + 'catalog/products.js': [ + { fn: 'getProduct', args: ['p-1'], replies: [ok({ id: 'p-1', name: 'Mug' })], sent: [req('GET', `${API}/products/p-1`)], returns: { id: 'p-1', name: 'Mug' } }, + { fn: 'getProduct', args: ['p-404'], replies: [ok({ error: 'gone' }, 404)], sent: [req('GET', `${API}/products/p-404`)], httpError: 404 }, + { fn: 'listProducts', args: [], replies: [ok({ items: ['a', 'b'] })], sent: [req('GET', `${API}/products`, { query: { page: '1', per_page: '20' } })], returns: ['a', 'b'] }, + { fn: 'listProducts', args: [{ page: 3, perPage: 5 }], replies: [ok({ items: [] })], sent: [req('GET', `${API}/products`, { query: { page: '3', per_page: '5' } })], returns: [] }, + ], + 'catalog/search.js': [ + { fn: 'searchProducts', args: ['red mug'], replies: [ok({ hits: [1, 2] })], sent: [req('GET', `${API}/search`, { query: { q: 'red mug', limit: '10' }, timeoutMs: 3000 })], returns: [1, 2] }, + { fn: 'searchProducts', args: ['x', 2], replies: [ok({ error: 'down' }, 503)], sent: [req('GET', `${API}/search`, { query: { q: 'x', limit: '2' }, timeoutMs: 3000 })], httpError: 503 }, + ], + 'catalog/categories.js': [ + { fn: 'listCategories', args: [], replies: [ok(['mugs', 'pens'])], sent: [req('GET', `${API}/categories`)], returns: ['mugs', 'pens'] }, + { fn: 'listCategories', args: [], replies: [ok(null, 500)], sent: [req('GET', `${API}/categories`)], httpError: 500 }, + { fn: 'getCategory', args: ['mugs'], replies: [ok({ slug: 'mugs' })], sent: [req('GET', `${API}/categories/mugs`)], returns: { slug: 'mugs' }, network: true }, + { fn: 'getCategory', args: ['nope'], replies: [ok({ error: 'not found' }, 404)], sent: [req('GET', `${API}/categories/nope`)], returns: null }, + ], + 'catalog/inventory.js': [ + { fn: 'getStock', args: ['AB/1'], replies: [ok({ available: 7 })], sent: [req('GET', `${API}/inventory/AB%2F1`, { headers: { accept: 'application/json' } })], returns: 7 }, + { fn: 'reserveStock', args: ['SKU-9', 2], replies: [ok({ reserved: 2 }, 201)], sent: [req('POST', `${API}/inventory/SKU-9/reserve`, { headers: JSON_TYPE, body: { qty: 2 } })], returns: { reserved: 2 } }, + { fn: 'reserveStock', args: ['SKU-9', 99], replies: [ok({ error: 'short' }, 409)], sent: [req('POST', `${API}/inventory/SKU-9/reserve`, { headers: JSON_TYPE, body: { qty: 99 } })], httpError: 409 }, + ], + 'catalog/reviews.js': [ + { fn: 'listReviews', args: ['p-1'], replies: [ok({ items: ['r1'] })], sent: [req('GET', `${API}/reviews`, { query: { product: 'p-1' } })], returns: { items: ['r1'], next: null } }, + { fn: 'listReviews', args: ['p-1', { rating: 0, cursor: 'c2' }], replies: [ok({ items: [], next: 'c3' })], sent: [req('GET', `${API}/reviews`, { query: { product: 'p-1', rating: '0', cursor: 'c2' } })], returns: { items: [], next: 'c3' } }, + { fn: 'postReview', args: ['p-1', { rating: 5, text: 'Great', ignored: true }], replies: [ok({}, 201)], sent: [req('POST', `${API}/reviews`, { headers: JSON_TYPE, body: { product: 'p-1', rating: 5, text: 'Great' } })], returns: true, network: true }, + { fn: 'postReview', args: ['p-1', { rating: 1, text: 'Hm' }], replies: [ok({}, 202)], sent: [req('POST', `${API}/reviews`, { headers: JSON_TYPE, body: { product: 'p-1', rating: 1, text: 'Hm' } })], returns: false }, + { fn: 'postReview', args: ['p-1', { rating: 9, text: '' }], replies: [ok({ error: 'invalid' }, 422)], sent: [req('POST', `${API}/reviews`, { headers: JSON_TYPE, body: { product: 'p-1', rating: 9, text: '' } })], returns: false }, + ], + 'catalog/product-cache.js': [ + { fn: 'getCachedProduct', args: ['pc-1'], replies: [ok({ id: 'pc-1' })], sent: [req('GET', `${API}/products/pc-1`, { timeoutMs: 2000 })], returns: { id: 'pc-1' } }, + // The second read is served by the vendored cache: nothing is sent. + { fn: 'getCachedProduct', args: ['pc-1'], replies: [], sent: [], returns: { id: 'pc-1' } }, + { fn: 'getCachedProduct', args: ['pc-2'], replies: [ok(null, 500)], sent: [req('GET', `${API}/products/pc-2`, { timeoutMs: 2000 })], httpError: 500 }, + ], + 'orders/create.js': [ + { + fn: 'createOrder', + args: [{ clientRef: 'ref-1', lines: [{ sku: 'A', qty: 1 }] }], + replies: [ok({ id: 'o-1', status: 'new', extra: 1 }, 201)], + sent: [req('POST', `${API}/orders`, { headers: { 'idempotency-key': 'ref-1', ...JSON_TYPE }, body: { clientRef: 'ref-1', lines: [{ sku: 'A', qty: 1 }] } })], + returns: { id: 'o-1', status: 'new' }, + }, + { fn: 'createOrder', args: [{ clientRef: 'ref-2' }], replies: [ok({ error: 'bad' }, 400)], sent: [req('POST', `${API}/orders`, { headers: { 'idempotency-key': 'ref-2', ...JSON_TYPE }, body: { clientRef: 'ref-2' } })], httpError: 400 }, + ], + 'orders/lookup.js': [ + { fn: 'findOrder', args: ['o-1'], replies: [ok({ id: 'o-1' })], sent: [req('GET', `${API}/orders/o-1`)], returns: { id: 'o-1' }, network: true }, + { fn: 'findOrder', args: ['o-0'], replies: [ok({ error: 'not found' }, 404)], sent: [req('GET', `${API}/orders/o-0`)], returns: null }, + { fn: 'listOrdersFor', args: ['c-1'], replies: [ok({ orders: ['o-1'] })], sent: [req('GET', `${API}/orders`, { query: { customer: 'c-1' } })], returns: ['o-1'] }, + { fn: 'listOrdersFor', args: ['c-1', 'paid'], replies: [ok({ orders: [] })], sent: [req('GET', `${API}/orders`, { query: { customer: 'c-1', status: 'paid' } })], returns: [] }, + ], + 'orders/cancel.js': [ + { fn: 'cancelOrder', args: ['o-1', 'changed mind'], replies: [ok(null, 204)], sent: [req('DELETE', `${API}/orders/o-1`, { query: { reason: 'changed mind' } })], returns: { cancelled: true }, network: true }, + { fn: 'cancelOrder', args: ['o-2'], replies: [ok({ error: 'already shipped' }, 409)], sent: [req('DELETE', `${API}/orders/o-2`)], returns: { cancelled: false, reason: 'already shipped' } }, + ], + 'orders/refunds.js': [ + { fn: 'requestRefund', args: ['o-1', 250], replies: [ok({ refundId: 'rf-1' }, 201)], sent: [req('POST', `${API}/orders/o-1/refunds`, { headers: JSON_TYPE, body: { amount_cents: 250 }, timeoutMs: 20000 })], returns: 'rf-1' }, + { fn: 'requestRefund', args: ['o-1', 0], replies: [ok({ error: 'zero' }, 422)], sent: [req('POST', `${API}/orders/o-1/refunds`, { headers: JSON_TYPE, body: { amount_cents: 0 }, timeoutMs: 20000 })], httpError: 422 }, + ], + 'orders/export.js': [ + { + fn: 'exportOrders', + args: ['status=paid'], + replies: [ok('id,total\no-1,10\n')], + sent: [req('POST', `${API}/orders/export`, { headers: { 'content-type': 'text/plain', accept: 'text/csv' }, body: 'status=paid', timeoutMs: 120000 })], + returns: 'id,total\no-1,10\n', + }, + ], + 'orders/notes.js': [ + { fn: 'listNotes', args: ['o-1'], replies: [ok({ notes: ['n1'] })], sent: [req('GET', `${API}/orders/o-1/notes`, { query: { order: 'newest' } })], returns: ['n1'] }, + { fn: 'addNote', args: ['o-1', 'call back', 'sam'], replies: [ok({ id: 'n2' }, 201)], sent: [req('POST', `${API}/orders/o-1/notes`, { headers: JSON_TYPE, body: { text: 'call back', author: 'sam' } })], returns: { id: 'n2' } }, + { fn: 'addNote', args: ['o-9', 't', 'a'], replies: [ok(null, 404)], sent: [req('POST', `${API}/orders/o-9/notes`, { headers: JSON_TYPE, body: { text: 't', author: 'a' } })], httpError: 404 }, + ], + 'billing/invoices.js': [ + { fn: 'getInvoice', args: ['inv-1'], replies: [ok({ id: 'inv-1' })], sent: [req('GET', `${API}/invoices/inv-1`, { headers: { accept: 'application/json' } })], returns: { id: 'inv-1' } }, + { fn: 'listInvoices', args: ['c-1'], replies: [ok({ invoices: [1] })], sent: [req('GET', `${API}/invoices`, { query: { customer: 'c-1' } })], returns: [1] }, + { fn: 'listInvoices', args: ['c-1', { from: '2026-01-01' }], replies: [ok({ invoices: [] })], sent: [req('GET', `${API}/invoices`, { query: { customer: 'c-1', from: '2026-01-01' } })], returns: [] }, + { fn: 'listInvoices', args: ['c-1', { from: '2026-01-01', to: '2026-02-01' }], replies: [ok(null, 500)], sent: [req('GET', `${API}/invoices`, { query: { customer: 'c-1', from: '2026-01-01', to: '2026-02-01' } })], httpError: 500 }, + ], + 'billing/payments.js': [ + { + fn: 'capturePayment', + args: ['pay-1', 990], + replies: [ok({ receipt: 'rc-1' })], + sent: [req('POST', `${API}/payments/pay-1/capture`, { headers: { 'x-billing-version': '3', ...JSON_TYPE }, body: { amount_cents: 990 }, timeoutMs: 15000 })], + returns: { captured: true, receipt: 'rc-1' }, + network: true, + }, + { + fn: 'capturePayment', + args: ['pay-2', 5], + replies: [ok({ code: 'insufficient_funds' }, 402)], + sent: [req('POST', `${API}/payments/pay-2/capture`, { headers: { 'x-billing-version': '3', ...JSON_TYPE }, body: { amount_cents: 5 }, timeoutMs: 15000 })], + returns: { captured: false, declineCode: 'insufficient_funds' }, + }, + { fn: 'voidPayment', args: ['pay-1'], replies: [ok(null, 204)], sent: [req('DELETE', `${API}/payments/pay-1`, { headers: { 'x-billing-version': '3' }, timeoutMs: 15000 })], returns: true, network: true }, + { fn: 'voidPayment', args: ['pay-1'], replies: [ok({ pending: true }, 202)], sent: [req('DELETE', `${API}/payments/pay-1`, { headers: { 'x-billing-version': '3' }, timeoutMs: 15000 })], returns: false }, + { fn: 'voidPayment', args: ['pay-0'], replies: [ok({ error: 'not found' }, 404)], sent: [req('DELETE', `${API}/payments/pay-0`, { headers: { 'x-billing-version': '3' }, timeoutMs: 15000 })], returns: false }, + ], + 'billing/subscriptions.js': [ + { fn: 'changePlan', args: ['sub-1', 'pro'], replies: [ok({ id: 'sub-1', plan: 'pro' })], sent: [req('PATCH', `${API}/subscriptions/sub-1`, { headers: JSON_TYPE, body: { plan: 'pro' } })], returns: { id: 'sub-1', plan: 'pro' } }, + { fn: 'pauseSubscription', args: ['sub-1', 14], replies: [ok({ resumesAt: '2026-03-01' })], sent: [req('POST', `${API}/subscriptions/sub-1/pause`, { headers: JSON_TYPE, body: { days: 14 }, timeoutMs: 10000 })], returns: '2026-03-01' }, + { fn: 'pauseSubscription', args: ['sub-0', 1], replies: [ok(null, 404)], sent: [req('POST', `${API}/subscriptions/sub-0/pause`, { headers: JSON_TYPE, body: { days: 1 }, timeoutMs: 10000 })], httpError: 404 }, + ], + 'billing/tax.js': [ + { fn: 'quoteTax', args: [{ country: 'DE', net: 1000 }], replies: [ok({ tax_cents: 190 })], sent: [req('POST', `${TAX}/quote`, { headers: JSON_TYPE, body: { country: 'DE', net: 1000 }, timeoutMs: 2500 })], returns: 190, network: true }, + { fn: 'quoteTax', args: [{ country: 'DE' }], replies: [ok({ error: 'overloaded' }, 503)], sent: [req('POST', `${TAX}/quote`, { headers: JSON_TYPE, body: { country: 'DE' }, timeoutMs: 2500 })], returns: null }, + { fn: 'quoteTax', args: [{ country: 'FR' }], replies: [ok({ tax_cents: 1 }, 202)], sent: [req('POST', `${TAX}/quote`, { headers: JSON_TYPE, body: { country: 'FR' }, timeoutMs: 2500 })], returns: null }, + ], + 'billing/credits.js': [ + { fn: 'getBalance', args: ['c-1'], replies: [ok({ balance_cents: 420 })], sent: [req('GET', `${API}/credits/c-1`, { headers: { 'cache-control': 'no-cache' }, query: { currency: 'USD' } })], returns: 420 }, + { fn: 'getBalance', args: ['c-1', 'EUR'], replies: [ok(null, 403)], sent: [req('GET', `${API}/credits/c-1`, { headers: { 'cache-control': 'no-cache' }, query: { currency: 'EUR' } })], httpError: 403 }, + ], + 'billing/dunning.js': [ + { fn: 'sendReminder', args: ['inv-1'], replies: [ok({}, 201)], sent: [req('POST', `${API}/invoices/inv-1/reminders`, { headers: JSON_TYPE, body: { channel: 'email' } })], returns: 201, network: true }, + { fn: 'sendReminder', args: ['inv-1', { channel: 'sms', method: 'put' }], replies: [ok({}, 200)], sent: [req('PUT', `${API}/invoices/inv-1/reminders`, { headers: JSON_TYPE, body: { channel: 'sms' } })], returns: 200 }, + { fn: 'sendReminder', args: ['inv-0'], replies: [ok({ error: 'not found' }, 404)], sent: [req('POST', `${API}/invoices/inv-0/reminders`, { headers: JSON_TYPE, body: { channel: 'email' } })], returns: 404 }, + ], + 'users/profile.js': [ + { fn: 'getProfile', args: ['u-1'], replies: [ok({ id: 'u-1' })], sent: [req('GET', `${API}/users/u-1`)], returns: { id: 'u-1' }, network: true }, + { fn: 'getProfile', args: ['u-0'], replies: [ok({ error: 'not found' }, 404)], sent: [req('GET', `${API}/users/u-0`)], returns: null }, + { fn: 'updateProfile', args: ['u-1', { name: 'Kim' }], replies: [ok({ id: 'u-1', name: 'Kim' })], sent: [req('PATCH', `${API}/users/u-1`, { headers: JSON_TYPE, body: { name: 'Kim' } })], returns: { id: 'u-1', name: 'Kim' } }, + { fn: 'updateProfile', args: ['u-1', { name: '' }], replies: [ok({ error: 'invalid' }, 422)], sent: [req('PATCH', `${API}/users/u-1`, { headers: JSON_TYPE, body: { name: '' } })], httpError: 422 }, + ], + 'users/auth.js': [ + { fn: 'login', args: ['kim@example.test', 'pw'], replies: [ok({ token: 'tok-1' })], sent: [req('POST', `${AUTH}/login`, { headers: JSON_TYPE, body: { email: 'kim@example.test', password: 'pw' }, timeoutMs: 5000 })], returns: { ok: true, token: 'tok-1' }, network: true }, + { fn: 'login', args: ['kim@example.test', 'no'], replies: [ok({ error: 'bad credentials' }, 401)], sent: [req('POST', `${AUTH}/login`, { headers: JSON_TYPE, body: { email: 'kim@example.test', password: 'no' }, timeoutMs: 5000 })], returns: { ok: false } }, + ], + 'users/preferences.js': [ + { fn: 'getPreferences', args: ['u-1'], replies: [ok({ theme: 'dark' })], sent: [req('GET', `${API}/users/u-1/preferences`)], returns: { theme: 'dark' } }, + { fn: 'getPreferences', args: ['u-0'], replies: [ok(null, 404)], sent: [req('GET', `${API}/users/u-0/preferences`)], httpError: 404 }, + { fn: 'setPreference', args: ['u-1', 'theme', 'light'], replies: [ok(null, 204)], sent: [req('PUT', `${API}/users/u-1/preferences/theme`, { headers: JSON_TYPE, body: { value: 'light' } })], returns: true, network: true }, + { fn: 'setPreference', args: ['u-1', 'nope', 1], replies: [ok({ error: 'unknown key' }, 400)], sent: [req('PUT', `${API}/users/u-1/preferences/nope`, { headers: JSON_TYPE, body: { value: 1 } })], returns: false }, + ], + 'users/avatars.js': [ + { fn: 'uploadAvatar', args: ['u-1', 'aGVsbG8=', 'image/png'], replies: [ok({ url: 'https://cdn.acme.test/u-1.png' }, 201)], sent: [req('PUT', `${API}/users/u-1/avatar`, { headers: { 'content-type': 'image/png', 'x-encoding': 'base64' }, body: 'aGVsbG8=' })], returns: 'https://cdn.acme.test/u-1.png' }, + { fn: 'uploadAvatar', args: ['u-1', 'eA==', 'text/plain'], replies: [ok({ error: 'type' }, 415)], sent: [req('PUT', `${API}/users/u-1/avatar`, { headers: { 'content-type': 'text/plain', 'x-encoding': 'base64' }, body: 'eA==' })], httpError: 415 }, + ], + 'users/invites.js': [ + { fn: 'sendInvite', args: ['lee@example.test'], replies: [ok({ id: 'inv-9' }, 201)], sent: [req('POST', `${API}/invites`, { headers: JSON_TYPE, body: { email: 'lee@example.test', role: 'member' }, timeoutMs: 8000 })], returns: 'inv-9' }, + { fn: 'sendInvite', args: ['lee@example.test', 'admin'], replies: [ok(null, 409)], sent: [req('POST', `${API}/invites`, { headers: JSON_TYPE, body: { email: 'lee@example.test', role: 'admin' }, timeoutMs: 8000 })], httpError: 409 }, + ], + 'users/search.js': [ + { fn: 'findUsers', args: ['kim'], replies: [ok({ users: ['u-1'] })], sent: [req('GET', `${API}/users/search`, { query: { q: 'kim', limit: '10' } })], returns: ['u-1'] }, + { fn: 'findUsers', args: ['kim', { token: 'tok', limit: 3 }], replies: [ok({ users: [] })], sent: [req('GET', `${API}/users/search`, { headers: { authorization: 'Bearer tok' }, query: { q: 'kim', limit: '3' } })], returns: [] }, + ], + 'shipping/rates.js': [ + { fn: 'getRates', args: [{ country: 'NL', zip: '1011' }, 750], replies: [ok({ rates: [{ id: 'std' }] })], sent: [req('GET', `${CARRIER}/rates`, { query: { country: 'NL', zip: '1011', weight_g: '750' }, timeoutMs: 4000 })], returns: [{ id: 'std' }] }, + { fn: 'getRates', args: [{ country: 'US' }, 10], replies: [ok(null, 502)], sent: [req('GET', `${CARRIER}/rates`, { query: { country: 'US', weight_g: '10' }, timeoutMs: 4000 })], httpError: 502 }, + ], + 'shipping/labels.js': [ + { fn: 'createLabel', args: [{ id: 's-1', weightGrams: 300 }], replies: [ok({ id: 'l-1', pdf: 'https://carrier.acme.test/l-1.pdf' }, 201)], sent: [req('POST', `${CARRIER}/labels`, { headers: { 'x-carrier': 'acme-post', ...JSON_TYPE }, body: { shipment: 's-1', weight_g: 300 } })], returns: { labelId: 'l-1', url: 'https://carrier.acme.test/l-1.pdf' } }, + { fn: 'createLabel', args: [{ id: 's-2', weightGrams: 1 }, 'fastship'], replies: [ok(null, 400)], sent: [req('POST', `${CARRIER}/labels`, { headers: { 'x-carrier': 'fastship', ...JSON_TYPE }, body: { shipment: 's-2', weight_g: 1 } })], httpError: 400 }, + ], + 'shipping/tracking.js': [ + { fn: 'track', args: ['TRK1'], replies: [ok({ state: 'in_transit' })], sent: [req('GET', `${CARRIER}/tracking/TRK1`, { query: { events: 'last' } })], returns: { found: true, state: 'in_transit' }, network: true }, + { fn: 'track', args: ['TRK0'], replies: [ok({ error: 'unknown' }, 404)], sent: [req('GET', `${CARRIER}/tracking/TRK0`, { query: { events: 'last' } })], returns: { found: false } }, + ], + 'shipping/pickups.js': [ + { fn: 'schedulePickup', args: ['addr-1', '2026-02-03'], replies: [ok({ pickupId: 'pk-1' }, 201)], sent: [req('POST', `${CARRIER}/pickups`, { headers: JSON_TYPE, body: { address: 'addr-1', date: '2026-02-03' } })], returns: 'pk-1' }, + { fn: 'schedulePickup', args: ['addr-1', 'never'], replies: [ok({ error: 'date' }, 422)], sent: [req('POST', `${CARRIER}/pickups`, { headers: JSON_TYPE, body: { address: 'addr-1', date: 'never' } })], httpError: 422 }, + { fn: 'cancelPickup', args: ['pk-1'], replies: [ok(null, 204)], sent: [req('DELETE', `${CARRIER}/pickups/pk-1`)], returns: true, network: true }, + { fn: 'cancelPickup', args: ['pk-0'], replies: [ok({ error: 'not found' }, 404)], sent: [req('DELETE', `${CARRIER}/pickups/pk-0`)], returns: false }, + ], + 'shipping/zones.js': [ + { fn: 'listZones', args: [], replies: [ok(['z1', 'z2'])], sent: [req('GET', `${CARRIER}/zones`)], returns: ['z1', 'z2'] }, + { fn: 'zoneFor', args: ['90210'], replies: [ok({ zone: 'z8' })], sent: [req('GET', `${CARRIER}/zones/lookup`, { query: { zip: '90210', country: 'US' }, timeoutMs: 1500 })], returns: 'z8' }, + { fn: 'zoneFor', args: ['0000', 'NL'], replies: [ok(null, 404)], sent: [req('GET', `${CARRIER}/zones/lookup`, { query: { zip: '0000', country: 'NL' }, timeoutMs: 1500 })], httpError: 404 }, + ], + 'shipping/customs.js': [ + { fn: 'declare', args: ['s-1', [{ hs: '6912', qty: 2 }]], replies: [ok({ declarationId: 'd-1' }, 201)], sent: [req('POST', `${CARRIER}/customs/s-1`, { headers: { 'x-request-source': 'customs', ...JSON_TYPE }, body: { items: [{ hs: '6912', qty: 2 }] }, timeoutMs: 12000 })], returns: 'd-1' }, + { fn: 'declare', args: ['s-1', [], { timeoutSeconds: 40 }], replies: [ok({ declarationId: 'd-2' })], sent: [req('POST', `${CARRIER}/customs/s-1`, { headers: { 'x-request-source': 'customs', ...JSON_TYPE }, body: { items: [] }, timeoutMs: 40000 })], returns: 'd-2' }, + ], + 'notifications/email.js': [ + { fn: 'sendEmail', args: ['kim@example.test', 'welcome'], replies: [ok({ messageId: 'm-1' }, 202)], sent: [req('POST', `${NOTIFY}/email`, { headers: JSON_TYPE, body: { to: 'kim@example.test', template: 'welcome', vars: {} } })], returns: 'm-1' }, + { fn: 'sendEmail', args: ['bad', 'welcome', { a: 1 }], replies: [ok({ error: 'address' }, 400)], sent: [req('POST', `${NOTIFY}/email`, { headers: JSON_TYPE, body: { to: 'bad', template: 'welcome', vars: { a: 1 } } })], httpError: 400 }, + ], + 'notifications/sms.js': [ + { fn: 'sendSms', args: ['+15550100', 'hi'], replies: [ok({ id: 'sms-1' }, 201)], sent: [req('POST', `${NOTIFY}/sms`, { headers: JSON_TYPE, body: { number: '+15550100', text: 'hi' }, timeoutMs: 3000 })], returns: { queued: true, id: 'sms-1' }, network: true }, + { fn: 'sendSms', args: ['+15550100', 'again'], replies: [ok({ retry_after: 30 }, 429)], sent: [req('POST', `${NOTIFY}/sms`, { headers: JSON_TYPE, body: { number: '+15550100', text: 'again' }, timeoutMs: 3000 })], returns: { queued: false, retryAfter: 30 } }, + ], + 'notifications/webhooks.js': [ + { + fn: 'deliver', + args: [{ url: 'https://hooks.example.test/a', secret: 's3' }, { type: 'order.paid' }], + replies: [ok('ok')], + sent: [req('POST', 'https://hooks.example.test/a', { headers: { 'x-signature': 'sha1=s3', ...JSON_TYPE }, body: { type: 'order.paid' } })], + returns: { delivered: true, status: 200 }, + network: true, + }, + { + fn: 'deliver', + args: [{ url: 'https://hooks.example.test/b', secret: 'k', method: 'put', timeoutSeconds: 4 }, { type: 'ping' }], + replies: [ok(null, 204)], + sent: [req('PUT', 'https://hooks.example.test/b', { headers: { 'x-signature': 'sha1=k', ...JSON_TYPE }, body: { type: 'ping' }, timeoutMs: 4000 })], + returns: { delivered: true, status: 204 }, + }, + { + fn: 'deliver', + args: [{ url: 'https://hooks.example.test/c', secret: 'k' }, { type: 'ping' }], + replies: [ok('boom', 500)], + sent: [req('POST', 'https://hooks.example.test/c', { headers: { 'x-signature': 'sha1=k', ...JSON_TYPE }, body: { type: 'ping' } })], + returns: { delivered: false, status: 500 }, + }, + ], + 'notifications/templates.js': [ + { fn: 'getTemplate', args: ['welcome'], replies: [ok({ subject: 'Hi' })], sent: [req('GET', `${NOTIFY}/templates/welcome`, { query: { locale: 'en' } })], returns: { subject: 'Hi' } }, + { fn: 'getTemplate', args: ['nope', 'pt'], replies: [ok(null, 404)], sent: [req('GET', `${NOTIFY}/templates/nope`, { query: { locale: 'pt' } })], httpError: 404 }, + { fn: 'renderTemplate', args: ['welcome', { name: 'Kim' }], replies: [ok({ html: '

Hi Kim

' })], sent: [req('POST', `${NOTIFY}/templates/welcome/render`, { headers: JSON_TYPE, body: { name: 'Kim' } })], returns: '

Hi Kim

' }, + ], + 'notifications/push.js': [ + { fn: 'sendPush', args: ['dev-1', { title: 'Hi' }], replies: [ok({ accepted: true }, 202)], sent: [req('POST', `${NOTIFY}/push`, { headers: JSON_TYPE, body: { device: 'dev-1', payload: { title: 'Hi' } } })], returns: true }, + { fn: 'sendPush', args: ['dev-1', {}, { ttl: 0, priority: 'high' }], replies: [ok({ accepted: false })], sent: [req('POST', `${NOTIFY}/push`, { headers: { 'x-ttl': '0', 'x-priority': 'high', ...JSON_TYPE }, body: { device: 'dev-1', payload: {} } })], returns: false }, + { fn: 'sendPush', args: ['dev-0', {}], replies: [ok(null, 410)], sent: [req('POST', `${NOTIFY}/push`, { headers: JSON_TYPE, body: { device: 'dev-0', payload: {} } })], httpError: 410 }, + ], + 'notifications/digest.js': [ + { + fn: 'buildDigest', + args: ['u-1'], + replies: [ok({ locale: 'en', lastDigestAt: '2026-01-05' }), ok({ events: ['e1'] })], + sent: [req('GET', `${NOTIFY}/digest/u-1/settings`), req('GET', `${API}/activity`, { query: { user: 'u-1', since: '2026-01-05' }, timeoutMs: 6000 })], + returns: { locale: 'en', events: ['e1'] }, + }, + { fn: 'buildDigest', args: ['u-0'], replies: [ok(null, 404)], sent: [req('GET', `${NOTIFY}/digest/u-0/settings`)], httpError: 404 }, + { + fn: 'buildDigest', + args: ['u-2'], + replies: [ok({ locale: 'pt' }), ok({ error: 'down' }, 503)], + sent: [req('GET', `${NOTIFY}/digest/u-2/settings`), req('GET', `${API}/activity`, { query: { user: 'u-2' }, timeoutMs: 6000 })], + httpError: 503, + }, + ], +}; + +/** Runs `fn` with a transport that answers from `replies` (or throws `fail`), and returns what was sent. */ +async function withTransport(replies, fail, fn) { + const sent = []; + const queue = [...replies]; + const previous = setTransport(async (r) => { + sent.push(r); + if (fail !== undefined) throw fail; + const reply = queue.shift(); + if (reply === undefined) throw new Error(`unexpected extra request: ${r.method} ${r.url}`); + return reply; + }); + try { + return { outcome: await fn().then((value) => ({ value }), (error) => ({ error })), sent }; + } finally { + setTransport(previous); + } +} + +const describeCase = (c) => `${c.fn}(${c.args.map((a) => JSON.stringify(a)).join(', ')})`; + +for (const [file, cases] of Object.entries(CASES)) { + test(`behaviour: ${file}`, async () => { + const mod = await import(`../src/services/${file}`); + for (const c of cases) { + const label = describeCase(c); + assert.equal(typeof mod[c.fn], 'function', `${file} exports ${c.fn}`); + const { outcome, sent } = await withTransport(c.replies, undefined, async () => mod[c.fn](...structuredClone(c.args))); + assert.deepEqual(sent, c.sent, `${label}: requests sent`); + if (c.httpError !== undefined) { + assert.ok(outcome.error !== undefined, `${label}: rejects for status ${c.httpError}`); + assert.equal(outcome.error.name, 'HttpError', `${label}: rejects with the HttpError of request (got ${outcome.error})`); + assert.equal(outcome.error.status, c.httpError, `${label}: HttpError status`); + } else { + if (outcome.error !== undefined) assert.fail(`${label}: rejected with ${outcome.error}`); + assert.deepEqual(outcome.value, c.returns, `${label}: result`); + } + if (c.network === true) { + const down = new Error('network down'); + const failed = await withTransport([], down, async () => mod[c.fn](...structuredClone(c.args))); + assert.equal(failed.outcome.error, down, `${label}: an error that is not an HttpError propagates`); + } + } + }); +} diff --git a/bench/tasks/T15/hidden/static.test.js b/bench/tasks/T15/hidden/static.test.js new file mode 100644 index 0000000..560141f --- /dev/null +++ b/bench/tasks/T15/hidden/static.test.js @@ -0,0 +1,72 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; + +const ROOT = path.join(import.meta.dirname, '..'); +const read = (rel) => readFileSync(path.join(ROOT, ...rel.split('/')), 'utf8'); + +/** Every .js file under src/, as POSIX paths relative to the workspace. */ +function sourceFiles(rel = 'src') { + const out = []; + for (const e of readdirSync(path.join(ROOT, ...rel.split('/')), { withFileTypes: true })) { + const child = `${rel}/${e.name}`; + if (e.isDirectory()) out.push(...sourceFiles(child)); + else if (/\.[cm]?js$/.test(e.name)) out.push(child); + } + return out.sort(); +} + +// The modules that called src/lib/legacy-http.js, listed by hand. +const CALLERS = [ + 'catalog/products.js', 'catalog/search.js', 'catalog/categories.js', 'catalog/inventory.js', 'catalog/reviews.js', 'catalog/product-cache.js', + 'orders/create.js', 'orders/lookup.js', 'orders/cancel.js', 'orders/refunds.js', 'orders/export.js', 'orders/notes.js', + 'billing/invoices.js', 'billing/payments.js', 'billing/subscriptions.js', 'billing/tax.js', 'billing/credits.js', 'billing/dunning.js', + 'users/profile.js', 'users/auth.js', 'users/preferences.js', 'users/avatars.js', 'users/invites.js', 'users/search.js', + 'shipping/rates.js', 'shipping/labels.js', 'shipping/tracking.js', 'shipping/pickups.js', 'shipping/zones.js', 'shipping/customs.js', + 'notifications/email.js', 'notifications/sms.js', 'notifications/webhooks.js', 'notifications/templates.js', 'notifications/push.js', 'notifications/digest.js', +].map((f) => `src/services/${f}`); + +// Files that mention the old names for another reason (a vendored cache with a function of the same +// name, its callers, a text check, a comment). They are compared byte for byte by the verifier. +const NOT_HTTP = ['src/vendor/cache/legacy.js', 'src/services/catalog/price-cache.js', 'src/services/users/session-cache.js', 'src/tools/lint-legacy.js', 'src/services/billing/tax-rules.js']; + +const IMPORTS_LEGACY_HTTP = /(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"`][^'"`\n]*legacy-http(?:\.[cm]?js)?['"`]/; +const IMPORTS_HTTP = /\bfrom\s*['"]\.\.\/\.\.\/lib\/http\.js['"]/; +// A declaration, alias, property or re-export that brings the old helper names back. +const OLD_HELPER = /\b(?:function\s*\*?|const|let|var|class)\s+legacy(?:Fetch|Json)\b|\bas\s+legacy(?:Fetch|Json)\b|\blegacy(?:Fetch|Json)\s*[:=]|\bexport\s*\{[^}]*\blegacy(?:Fetch|Json)\b/; + +test('static: src/lib/legacy-http.js is deleted', () => { + assert.equal(existsSync(path.join(ROOT, 'src', 'lib', 'legacy-http.js')), false, 'src/lib/legacy-http.js still exists'); + const left = sourceFiles().filter((f) => /legacy-http/.test(path.posix.basename(f))); + assert.deepEqual(left, [], 'a file named like legacy-http is still in src/'); +}); + +test('static: no file imports legacy-http', () => { + const importing = sourceFiles().filter((f) => IMPORTS_LEGACY_HTTP.test(read(f))); + assert.deepEqual(importing, [], 'files that still import legacy-http'); +}); + +test('static: every former caller imports src/lib/http.js and calls request itself', () => { + const missing = []; + for (const file of CALLERS) { + if (!existsSync(path.join(ROOT, ...file.split('/')))) { + missing.push(`${file}: file is gone`); + continue; + } + const text = read(file); + if (!IMPORTS_HTTP.test(text)) missing.push(`${file}: does not import ../../lib/http.js`); + else if (!/\brequest\s*\(/.test(text)) missing.push(`${file}: does not call request`); + } + assert.deepEqual(missing, []); +}); + +test('static: the old helpers are not recreated (no legacyFetch/legacyJson wrapper, alias or re-export)', () => { + const recreated = sourceFiles().filter((f) => !NOT_HTTP.includes(f) && OLD_HELPER.test(read(f))); + assert.deepEqual(recreated, [], 'files that define, alias or re-export legacyFetch/legacyJson'); +}); + +test('static: product-cache.js still reads through the vendored cache', () => { + const text = read('src/services/catalog/product-cache.js'); + assert.match(text, /\bfrom\s*['"]\.\.\/\.\.\/vendor\/cache\/legacy\.js['"]/, 'product-cache.js no longer imports the vendored cache'); +}); diff --git a/bench/tasks/T15/solution/apply.ts b/bench/tasks/T15/solution/apply.ts new file mode 100644 index 0000000..0dd6735 --- /dev/null +++ b/bench/tasks/T15/solution/apply.ts @@ -0,0 +1,11 @@ +import { rm, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { FixtureFacts } from '../../../fixture/generate.ts'; +import { filesFrom } from '../../setup.ts'; +import { T15_LEGACY } from '../verify.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); + await rm(path.join(workspace, ...T15_LEGACY.split('/'))); + return 'Migrated the 36 modules under src/services/ that imported src/lib/legacy-http.js to `request` from src/lib/http.js (query, JSON body plus content-type, timeout in milliseconds, upper-case method, `body` instead of `data`, and a catch of HttpError where the code reads the status) and deleted src/lib/legacy-http.js. The vendored cache, its callers, the lint check and the tax table were not callers and are untouched.'; +} diff --git a/bench/tasks/T15/solution/files/src/services/billing/credits.js b/bench/tasks/T15/solution/files/src/services/billing/credits.js new file mode 100644 index 0000000..ce7f3d6 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/billing/credits.js @@ -0,0 +1,11 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +export async function getBalance(customerId, currency = 'USD') { + const res = await request({ + url: `${API}/credits/${customerId}`, + query: { currency }, + headers: { 'Cache-Control': 'no-cache' }, + }); + return res.body.balance_cents; +} diff --git a/bench/tasks/T15/solution/files/src/services/billing/dunning.js b/bench/tasks/T15/solution/files/src/services/billing/dunning.js new file mode 100644 index 0000000..e47dc20 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/billing/dunning.js @@ -0,0 +1,21 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** + * Sends a payment reminder for an invoice. `method` is 'post' for a new reminder and 'put' to + * replace the one already scheduled. Returns the HTTP status of the reminder service. + */ +export async function sendReminder(invoiceId, { channel = 'email', method = 'post' } = {}) { + try { + const res = await request({ + method: String(method).toUpperCase(), + url: `${API}/invoices/${invoiceId}/reminders`, + headers: { 'content-type': 'application/json' }, + body: { channel }, + }); + return res.status; + } catch (err) { + if (err instanceof HttpError) return err.status; + throw err; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/billing/invoices.js b/bench/tasks/T15/solution/files/src/services/billing/invoices.js new file mode 100644 index 0000000..2d3431b --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/billing/invoices.js @@ -0,0 +1,12 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +export async function getInvoice(id) { + const { body } = await request({ url: `${API}/invoices/${id}`, headers: { accept: 'application/json' } }); + return body; +} + +export async function listInvoices(customerId, { from, to } = {}) { + const { body } = await request({ url: `${API}/invoices`, query: { customer: customerId, from, to } }); + return body.invoices; +} diff --git a/bench/tasks/T15/solution/files/src/services/billing/payments.js b/bench/tasks/T15/solution/files/src/services/billing/payments.js new file mode 100644 index 0000000..b8480fc --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/billing/payments.js @@ -0,0 +1,34 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +const DEFAULTS = { timeoutMs: 15000, headers: { 'x-billing-version': '3' } }; + +/** Captures an authorized payment. A declined card answers 402 with a decline code. */ +export async function capturePayment(id, cents) { + let body; + try { + const res = await request({ + ...DEFAULTS, + method: 'POST', + url: `${API}/payments/${id}/capture`, + headers: { ...DEFAULTS.headers, 'content-type': 'application/json' }, + body: { amount_cents: cents }, + }); + body = res.body; + } catch (err) { + if (!(err instanceof HttpError)) throw err; + if (err.status === 402) return { captured: false, declineCode: err.body.code }; + body = err.body; + } + return { captured: true, receipt: body.receipt }; +} + +export async function voidPayment(id) { + try { + const res = await request({ ...DEFAULTS, method: 'DELETE', url: `${API}/payments/${id}` }); + return res.status === 204; + } catch (err) { + if (err instanceof HttpError) return false; + throw err; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/billing/subscriptions.js b/bench/tasks/T15/solution/files/src/services/billing/subscriptions.js new file mode 100644 index 0000000..8791713 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/billing/subscriptions.js @@ -0,0 +1,20 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +const JSON_HEADERS = { 'content-type': 'application/json' }; + +export async function changePlan(subscriptionId, plan) { + const res = await request({ method: 'PATCH', url: `${API}/subscriptions/${subscriptionId}`, headers: JSON_HEADERS, body: { plan } }); + return res.body; +} + +export async function pauseSubscription(subscriptionId, days) { + const res = await request({ + method: 'POST', + url: `${API}/subscriptions/${subscriptionId}/pause`, + headers: JSON_HEADERS, + body: { days }, + timeoutMs: 10000, + }); + return res.body.resumesAt; +} diff --git a/bench/tasks/T15/solution/files/src/services/billing/tax.js b/bench/tasks/T15/solution/files/src/services/billing/tax.js new file mode 100644 index 0000000..25fdfd6 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/billing/tax.js @@ -0,0 +1,23 @@ +import { HttpError, request } from '../../lib/http.js'; +import { TAX } from '../config.js'; + +/** + * Tax of a cart, in cents. The tax service is optional at checkout: when it does not answer 200 + * within 2.5 seconds' worth of patience the caller falls back to its own table, so this returns null. + */ +export async function quoteTax(cart) { + try { + const res = await request({ + method: 'POST', + url: `${TAX}/quote`, + headers: { 'content-type': 'application/json' }, + body: cart, + timeoutMs: 2500, + }); + if (res.status !== 200) return null; + return res.body.tax_cents; + } catch (err) { + if (err instanceof HttpError) return null; + throw err; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/catalog/categories.js b/bench/tasks/T15/solution/files/src/services/catalog/categories.js new file mode 100644 index 0000000..9256bd9 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/catalog/categories.js @@ -0,0 +1,18 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +export async function listCategories() { + return (await request({ url: `${API}/categories` })).body; +} + +/** Returns the category, or null when there is none with that slug. */ +export async function getCategory(slug) { + try { + const res = await request({ url: `${API}/categories/${slug}` }); + return res.body; + } catch (err) { + if (!(err instanceof HttpError)) throw err; + if (err.status === 404) return null; + return err.body; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/catalog/inventory.js b/bench/tasks/T15/solution/files/src/services/catalog/inventory.js new file mode 100644 index 0000000..5c55eb5 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/catalog/inventory.js @@ -0,0 +1,19 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +const stockUrl = (sku) => `${API}/inventory/${encodeURIComponent(sku)}`; + +export async function getStock(sku) { + const stock = (await request({ url: stockUrl(sku), headers: { Accept: 'application/json' } })).body; + return stock.available; +} + +export async function reserveStock(sku, qty) { + const res = await request({ + method: 'POST', + url: `${stockUrl(sku)}/reserve`, + headers: { 'content-type': 'application/json' }, + body: { qty }, + }); + return res.body; +} diff --git a/bench/tasks/T15/solution/files/src/services/catalog/product-cache.js b/bench/tasks/T15/solution/files/src/services/catalog/product-cache.js new file mode 100644 index 0000000..26ac685 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/catalog/product-cache.js @@ -0,0 +1,13 @@ +import { request } from '../../lib/http.js'; +import { legacyFetch as cacheFetch, legacyStore } from '../../vendor/cache/legacy.js'; +import { API } from '../config.js'; + +/** Product by id, read through the in-memory cache (5 minutes). */ +export async function getCachedProduct(id) { + const key = `product:${id}`; + const hit = cacheFetch(key); + if (hit !== undefined) return hit; + const res = await request({ url: `${API}/products/${id}`, timeoutMs: 2000 }); + legacyStore(key, res.body, 300); + return res.body; +} diff --git a/bench/tasks/T15/solution/files/src/services/catalog/products.js b/bench/tasks/T15/solution/files/src/services/catalog/products.js new file mode 100644 index 0000000..d65942a --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/catalog/products.js @@ -0,0 +1,12 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +export async function getProduct(id) { + const res = await request({ url: `${API}/products/${id}` }); + return res.body; +} + +export async function listProducts({ page = 1, perPage = 20 } = {}) { + const res = await request({ url: `${API}/products`, query: { page, per_page: perPage } }); + return res.body.items; +} diff --git a/bench/tasks/T15/solution/files/src/services/catalog/reviews.js b/bench/tasks/T15/solution/files/src/services/catalog/reviews.js new file mode 100644 index 0000000..fdaf75d --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/catalog/reviews.js @@ -0,0 +1,26 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +export async function listReviews(productId, { rating, cursor } = {}) { + const query = { product: productId }; + if (rating !== undefined) query.rating = rating; + if (cursor) query.cursor = cursor; + const res = await request({ url: `${API}/reviews`, query }); + return { items: res.body.items, next: res.body.next ?? null }; +} + +/** Returns true when the review was accepted (201) and false when it was held for moderation (202). */ +export async function postReview(productId, review) { + try { + const res = await request({ + method: 'POST', + url: `${API}/reviews`, + headers: { 'content-type': 'application/json' }, + body: { product: productId, rating: review.rating, text: review.text }, + }); + return res.status === 201; + } catch (err) { + if (err instanceof HttpError) return false; + throw err; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/catalog/search.js b/bench/tasks/T15/solution/files/src/services/catalog/search.js new file mode 100644 index 0000000..12834b4 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/catalog/search.js @@ -0,0 +1,8 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Full-text search. The search backend is slow to fail, so the call gives up after 3 seconds. */ +export async function searchProducts(term, limit = 10) { + const { body } = await request({ url: `${API}/search`, query: { q: term, limit }, timeoutMs: 3000 }); + return body.hits; +} diff --git a/bench/tasks/T15/solution/files/src/services/notifications/digest.js b/bench/tasks/T15/solution/files/src/services/notifications/digest.js new file mode 100644 index 0000000..0aaac87 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/notifications/digest.js @@ -0,0 +1,9 @@ +import { request } from '../../lib/http.js'; +import { API, NOTIFY } from '../config.js'; + +/** Builds the activity digest of a user: what happened since the last digest was sent. */ +export async function buildDigest(userId) { + const prefs = (await request({ url: `${NOTIFY}/digest/${userId}/settings` })).body; + const res = await request({ url: `${API}/activity`, query: { user: userId, since: prefs.lastDigestAt }, timeoutMs: 6000 }); + return { locale: prefs.locale, events: res.body.events }; +} diff --git a/bench/tasks/T15/solution/files/src/services/notifications/email.js b/bench/tasks/T15/solution/files/src/services/notifications/email.js new file mode 100644 index 0000000..fc81ae3 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/notifications/email.js @@ -0,0 +1,12 @@ +import { request } from '../../lib/http.js'; +import { NOTIFY } from '../config.js'; + +export async function sendEmail(to, template, vars = {}) { + const res = await request({ + method: 'POST', + url: `${NOTIFY}/email`, + headers: { 'content-type': 'application/json' }, + body: { to, template, vars }, + }); + return res.body.messageId; +} diff --git a/bench/tasks/T15/solution/files/src/services/notifications/push.js b/bench/tasks/T15/solution/files/src/services/notifications/push.js new file mode 100644 index 0000000..5932486 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/notifications/push.js @@ -0,0 +1,11 @@ +import { request } from '../../lib/http.js'; +import { NOTIFY } from '../config.js'; + +/** Sends a push notification. `ttl` is in seconds; `priority` is 'high' or 'normal'. */ +export async function sendPush(deviceId, payload, { ttl, priority } = {}) { + const headers = { 'content-type': 'application/json' }; + if (ttl !== undefined) headers['x-ttl'] = String(ttl); + if (priority) headers['x-priority'] = priority; + const res = await request({ method: 'POST', url: `${NOTIFY}/push`, body: { device: deviceId, payload }, headers }); + return res.body.accepted; +} diff --git a/bench/tasks/T15/solution/files/src/services/notifications/sms.js b/bench/tasks/T15/solution/files/src/services/notifications/sms.js new file mode 100644 index 0000000..4397744 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/notifications/sms.js @@ -0,0 +1,22 @@ +import { HttpError, request } from '../../lib/http.js'; +import { NOTIFY } from '../config.js'; + +/** Sends a text message. When the provider is rate limited (429) the message is not queued. */ +export async function sendSms(number, text) { + let body; + try { + const res = await request({ + method: 'POST', + url: `${NOTIFY}/sms`, + headers: { 'content-type': 'application/json' }, + body: { number, text }, + timeoutMs: 3000, + }); + body = res.body; + } catch (err) { + if (!(err instanceof HttpError)) throw err; + if (err.status === 429) return { queued: false, retryAfter: err.body.retry_after }; + body = err.body; + } + return { queued: true, id: body.id }; +} diff --git a/bench/tasks/T15/solution/files/src/services/notifications/templates.js b/bench/tasks/T15/solution/files/src/services/notifications/templates.js new file mode 100644 index 0000000..1156a16 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/notifications/templates.js @@ -0,0 +1,16 @@ +import { request } from '../../lib/http.js'; +import { NOTIFY } from '../config.js'; + +export async function getTemplate(name, locale = 'en') { + return (await request({ url: `${NOTIFY}/templates/${name}`, query: { locale } })).body; +} + +export async function renderTemplate(name, vars) { + const res = await request({ + method: 'POST', + url: `${NOTIFY}/templates/${name}/render`, + headers: { 'content-type': 'application/json' }, + body: vars, + }); + return res.body.html; +} diff --git a/bench/tasks/T15/solution/files/src/services/notifications/webhooks.js b/bench/tasks/T15/solution/files/src/services/notifications/webhooks.js new file mode 100644 index 0000000..48ebdfa --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/notifications/webhooks.js @@ -0,0 +1,23 @@ +import { HttpError, request } from '../../lib/http.js'; + +/** + * Delivers an event to a customer webhook. `hook` is `{ url, secret, method?, timeoutSeconds? }`: + * the method defaults to POST and a hook without `timeoutSeconds` gets the default timeout. + * Never throws for an HTTP status: the result says whether the hook accepted the event. + */ +export async function deliver(hook, event) { + const options = { + method: String(hook.method ?? 'POST').toUpperCase(), + url: hook.url, + body: event, + headers: { 'x-signature': `sha1=${hook.secret}`, 'content-type': 'application/json' }, + }; + if (hook.timeoutSeconds !== undefined) options.timeoutMs = hook.timeoutSeconds * 1000; + try { + const res = await request(options); + return { delivered: res.status < 400, status: res.status }; + } catch (err) { + if (err instanceof HttpError) return { delivered: false, status: err.status }; + throw err; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/orders/cancel.js b/bench/tasks/T15/solution/files/src/services/orders/cancel.js new file mode 100644 index 0000000..35e00b0 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/orders/cancel.js @@ -0,0 +1,13 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Cancels an order. An order that already shipped answers 409 and is not cancelled. */ +export async function cancelOrder(id, reason) { + try { + await request({ method: 'DELETE', url: `${API}/orders/${id}`, query: { reason } }); + } catch (err) { + if (!(err instanceof HttpError)) throw err; + if (err.status === 409) return { cancelled: false, reason: err.body.error }; + } + return { cancelled: true }; +} diff --git a/bench/tasks/T15/solution/files/src/services/orders/create.js b/bench/tasks/T15/solution/files/src/services/orders/create.js new file mode 100644 index 0000000..27a33df --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/orders/create.js @@ -0,0 +1,12 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +export async function createOrder(order) { + const res = await request({ + method: 'POST', + url: `${API}/orders`, + headers: { 'Idempotency-Key': order.clientRef, 'content-type': 'application/json' }, + body: order, + }); + return { id: res.body.id, status: res.body.status }; +} diff --git a/bench/tasks/T15/solution/files/src/services/orders/export.js b/bench/tasks/T15/solution/files/src/services/orders/export.js new file mode 100644 index 0000000..9300e18 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/orders/export.js @@ -0,0 +1,14 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Exports the orders matching a filter expression as CSV text. Large exports get two minutes. */ +export async function exportOrders(filter) { + const res = await request({ + method: 'POST', + url: `${API}/orders/export`, + body: filter, + headers: { 'content-type': 'text/plain', accept: 'text/csv' }, + timeoutMs: 120000, + }); + return res.body; +} diff --git a/bench/tasks/T15/solution/files/src/services/orders/lookup.js b/bench/tasks/T15/solution/files/src/services/orders/lookup.js new file mode 100644 index 0000000..0ae4b06 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/orders/lookup.js @@ -0,0 +1,19 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Returns the order, or null when it does not exist. */ +export async function findOrder(id) { + try { + const res = await request({ url: `${API}/orders/${id}` }); + return res.body; + } catch (err) { + if (!(err instanceof HttpError)) throw err; + return err.status === 404 ? null : err.body; + } +} + +/** Orders of a customer, optionally only those in one status. */ +export async function listOrdersFor(customerId, status) { + const res = await request({ url: `${API}/orders`, query: { customer: customerId, status } }); + return res.body.orders; +} diff --git a/bench/tasks/T15/solution/files/src/services/orders/notes.js b/bench/tasks/T15/solution/files/src/services/orders/notes.js new file mode 100644 index 0000000..10ab5b5 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/orders/notes.js @@ -0,0 +1,17 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +export async function listNotes(orderId) { + const page = (await request({ url: `${API}/orders/${orderId}/notes`, query: { order: 'newest' } })).body; + return page.notes; +} + +export async function addNote(orderId, text, author) { + const res = await request({ + method: 'POST', + url: `${API}/orders/${orderId}/notes`, + headers: { 'content-type': 'application/json' }, + body: { text, author }, + }); + return res.body; +} diff --git a/bench/tasks/T15/solution/files/src/services/orders/refunds.js b/bench/tasks/T15/solution/files/src/services/orders/refunds.js new file mode 100644 index 0000000..7a0d5ca --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/orders/refunds.js @@ -0,0 +1,14 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Refunds go through the payment provider and may take a while: 20 seconds. */ +export async function requestRefund(orderId, cents) { + const res = await request({ + method: 'POST', + url: `${API}/orders/${orderId}/refunds`, + headers: { 'content-type': 'application/json' }, + body: { amount_cents: cents }, + timeoutMs: 20000, + }); + return res.body.refundId; +} diff --git a/bench/tasks/T15/solution/files/src/services/shipping/customs.js b/bench/tasks/T15/solution/files/src/services/shipping/customs.js new file mode 100644 index 0000000..fc0c648 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/shipping/customs.js @@ -0,0 +1,14 @@ +import { request } from '../../lib/http.js'; +import { CARRIER } from '../config.js'; + +/** Files a customs declaration. `timeoutSeconds` overrides the default patience of 12 seconds. */ +export async function declare(shipmentId, items, { timeoutSeconds } = {}) { + const res = await request({ + method: 'POST', + url: `${CARRIER}/customs/${shipmentId}`, + body: { items }, + timeoutMs: (timeoutSeconds ?? 12) * 1000, + headers: { 'X-Request-Source': 'customs', 'content-type': 'application/json' }, + }); + return res.body.declarationId; +} diff --git a/bench/tasks/T15/solution/files/src/services/shipping/labels.js b/bench/tasks/T15/solution/files/src/services/shipping/labels.js new file mode 100644 index 0000000..f53e0c7 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/shipping/labels.js @@ -0,0 +1,13 @@ +import { request } from '../../lib/http.js'; +import { CARRIER } from '../config.js'; + +export async function createLabel(shipment, carrier = 'acme-post') { + const res = await request({ + method: 'POST', + url: `${CARRIER}/labels`, + body: { shipment: shipment.id, weight_g: shipment.weightGrams }, + headers: { 'x-carrier': carrier, 'content-type': 'application/json' }, + }); + const label = res.body; + return { labelId: label.id, url: label.pdf }; +} diff --git a/bench/tasks/T15/solution/files/src/services/shipping/pickups.js b/bench/tasks/T15/solution/files/src/services/shipping/pickups.js new file mode 100644 index 0000000..a44dd34 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/shipping/pickups.js @@ -0,0 +1,23 @@ +import { HttpError, request } from '../../lib/http.js'; +import { CARRIER } from '../config.js'; + +export async function schedulePickup(addressId, date) { + const res = await request({ + method: 'POST', + url: `${CARRIER}/pickups`, + headers: { 'content-type': 'application/json' }, + body: { address: addressId, date }, + }); + return res.body.pickupId; +} + +/** Returns true when the pickup was cancelled, false when it was not (unknown id, already done). */ +export async function cancelPickup(pickupId) { + try { + const res = await request({ method: 'DELETE', url: `${CARRIER}/pickups/${pickupId}` }); + return res.status === 204; + } catch (err) { + if (err instanceof HttpError) return false; + throw err; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/shipping/rates.js b/bench/tasks/T15/solution/files/src/services/shipping/rates.js new file mode 100644 index 0000000..540ea6c --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/shipping/rates.js @@ -0,0 +1,11 @@ +import { request } from '../../lib/http.js'; +import { CARRIER } from '../config.js'; + +export async function getRates(destination, weightGrams) { + const res = await request({ + url: `${CARRIER}/rates`, + query: { country: destination.country, zip: destination.zip, weight_g: weightGrams }, + timeoutMs: 4000, + }); + return res.body.rates; +} diff --git a/bench/tasks/T15/solution/files/src/services/shipping/tracking.js b/bench/tasks/T15/solution/files/src/services/shipping/tracking.js new file mode 100644 index 0000000..7aef43b --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/shipping/tracking.js @@ -0,0 +1,16 @@ +import { HttpError, request } from '../../lib/http.js'; +import { CARRIER } from '../config.js'; + +/** Tracking state of a parcel. An unknown code answers 404. */ +export async function track(code) { + let body; + try { + const res = await request({ url: `${CARRIER}/tracking/${code}`, query: { events: 'last' } }); + body = res.body; + } catch (err) { + if (!(err instanceof HttpError)) throw err; + if (err.status === 404) return { found: false }; + body = err.body; + } + return { found: true, state: body.state }; +} diff --git a/bench/tasks/T15/solution/files/src/services/shipping/zones.js b/bench/tasks/T15/solution/files/src/services/shipping/zones.js new file mode 100644 index 0000000..6a6f7b0 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/shipping/zones.js @@ -0,0 +1,11 @@ +import { request } from '../../lib/http.js'; +import { CARRIER } from '../config.js'; + +export async function listZones() { + return (await request({ url: `${CARRIER}/zones` })).body; +} + +export async function zoneFor(zip, country = 'US') { + const match = (await request({ url: `${CARRIER}/zones/lookup`, query: { zip, country }, timeoutMs: 1500 })).body; + return match.zone; +} diff --git a/bench/tasks/T15/solution/files/src/services/users/auth.js b/bench/tasks/T15/solution/files/src/services/users/auth.js new file mode 100644 index 0000000..2d56661 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/users/auth.js @@ -0,0 +1,22 @@ +import { HttpError, request } from '../../lib/http.js'; +import { AUTH } from '../config.js'; + +/** Signs a user in. Wrong credentials answer 401. */ +export async function login(email, password) { + let body; + try { + const res = await request({ + method: 'POST', + url: `${AUTH}/login`, + headers: { 'content-type': 'application/json' }, + body: { email, password }, + timeoutMs: 5000, + }); + body = res.body; + } catch (err) { + if (!(err instanceof HttpError)) throw err; + if (err.status === 401) return { ok: false }; + body = err.body; + } + return { ok: true, token: body.token }; +} diff --git a/bench/tasks/T15/solution/files/src/services/users/avatars.js b/bench/tasks/T15/solution/files/src/services/users/avatars.js new file mode 100644 index 0000000..13ba4b5 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/users/avatars.js @@ -0,0 +1,13 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Uploads an avatar. `image` is the base64 text of the file and `mime` its type, e.g. image/png. */ +export async function uploadAvatar(userId, image, mime) { + const res = await request({ + method: 'PUT', + url: `${API}/users/${userId}/avatar`, + body: image, + headers: { 'Content-Type': mime, 'x-encoding': 'base64' }, + }); + return res.body.url; +} diff --git a/bench/tasks/T15/solution/files/src/services/users/invites.js b/bench/tasks/T15/solution/files/src/services/users/invites.js new file mode 100644 index 0000000..7f2cce4 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/users/invites.js @@ -0,0 +1,13 @@ +import { request } from '../../lib/http.js'; +import { API, DEFAULT_TIMEOUT_S } from '../config.js'; + +export async function sendInvite(email, role = 'member') { + const res = await request({ + method: 'POST', + url: `${API}/invites`, + headers: { 'content-type': 'application/json' }, + body: { email, role }, + timeoutMs: DEFAULT_TIMEOUT_S * 1000, + }); + return res.body.id; +} diff --git a/bench/tasks/T15/solution/files/src/services/users/preferences.js b/bench/tasks/T15/solution/files/src/services/users/preferences.js new file mode 100644 index 0000000..eb791ca --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/users/preferences.js @@ -0,0 +1,24 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +const prefsUrl = (userId) => `${API}/users/${userId}/preferences`; + +export async function getPreferences(userId) { + return (await request({ url: prefsUrl(userId) })).body; +} + +/** Returns true when the preference was stored (the service answers 204). */ +export async function setPreference(userId, key, value) { + try { + const res = await request({ + method: 'PUT', + url: `${prefsUrl(userId)}/${key}`, + headers: { 'content-type': 'application/json' }, + body: { value }, + }); + return res.status === 204; + } catch (err) { + if (err instanceof HttpError) return false; + throw err; + } +} diff --git a/bench/tasks/T15/solution/files/src/services/users/profile.js b/bench/tasks/T15/solution/files/src/services/users/profile.js new file mode 100644 index 0000000..0674f1e --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/users/profile.js @@ -0,0 +1,26 @@ +import { HttpError, request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Returns the profile, or null for an unknown user. */ +export async function getProfile(userId) { + try { + const res = await request({ url: `${API}/users/${userId}` }); + return res.body; + } catch (err) { + if (!(err instanceof HttpError)) throw err; + if (err.status === 404) { + return null; + } + return err.body; + } +} + +export async function updateProfile(userId, patch) { + const res = await request({ + method: 'PATCH', + url: `${API}/users/${userId}`, + headers: { 'content-type': 'application/json' }, + body: patch, + }); + return res.body; +} diff --git a/bench/tasks/T15/solution/files/src/services/users/search.js b/bench/tasks/T15/solution/files/src/services/users/search.js new file mode 100644 index 0000000..65a6375 --- /dev/null +++ b/bench/tasks/T15/solution/files/src/services/users/search.js @@ -0,0 +1,10 @@ +import { request } from '../../lib/http.js'; +import { API } from '../config.js'; + +/** Searches users by name or email. With a token the search also covers deactivated users. */ +export async function findUsers(query, { token, limit = 10 } = {}) { + const options = { url: `${API}/users/search`, query: { q: query, limit } }; + if (token) options.headers = { authorization: `Bearer ${token}` }; + const res = await request(options); + return res.body.users; +} diff --git a/bench/tasks/T15/verify.ts b/bench/tasks/T15/verify.ts new file mode 100644 index 0000000..8062382 --- /dev/null +++ b/bench/tasks/T15/verify.ts @@ -0,0 +1,32 @@ +import path from 'node:path'; +import { checkScope, checkUnchanged, Checks, runHiddenTests, runNodeTests } from '../checks.ts'; +import { filesFrom } from '../setup.ts'; +import type { VerifyContext, VerifyResult } from '../types.ts'; + +export const T15_FILES = path.join(import.meta.dirname, 'files'); +const HIDDEN = Object.fromEntries(filesFrom(path.join(import.meta.dirname, 'hidden'))); + +/** The one file the task deletes. */ +export const T15_LEGACY = 'src/lib/legacy-http.js'; +/** + * Files that use the names `legacyFetch`/`legacyJson` for another reason and must stay byte for byte: + * a vendored cache with a `legacyFetch` of its own, its two callers, a text check that spells the + * calls as strings and a module that only mentions one in a comment. + */ +export const T15_TRAPS = ['src/vendor/cache/legacy.js', 'src/services/catalog/price-cache.js', 'src/services/users/session-cache.js', 'src/tools/lint-legacy.js', 'src/services/billing/tax-rules.js']; + +/** + * Hidden tests check what every migrated function sends and returns (a hand-written table) and that the + * migration is real: the old module is gone, nothing imports it, each former caller calls `request` + * itself and no wrapper brings the old helpers back. The traps are compared with the initial tree. + */ +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 ? `: ${hidden.failed.join('; ')}` : ''})`); + await checkUnchanged(checks, ctx.workspace, ctx.initial, T15_TRAPS, 'files that are not callers of legacy-http'); + await checkScope(checks, ctx.workspace, ctx.initial, (f) => f.startsWith('src/services/'), { allowedDeletions: [T15_LEGACY] }); + 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..78e2e80 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'; @@ -58,13 +59,16 @@ export interface NodeTestRun { readonly ok: boolean; readonly pass: number; readonly fail: number; + /** Tail of the output. */ readonly output: string; + /** Names of the failing tests, taken from the whole output (the tail alone loses the first ones when many fail). */ + readonly failed: readonly 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'))); @@ -73,7 +77,7 @@ export function runNodeTests(workspace: string, timeoutMs = 60_000): Promise Number(new RegExp(`^(?:ℹ|#) ${label} (\\d+)`, 'm').exec(output)?.[1] ?? '0'); - resolve({ ok: code === 0, pass: num('pass'), fail: num('fail'), output: output.slice(-4000) }); + resolve({ ok: code === 0, pass: num('pass'), fail: num('fail'), output: output.slice(-4000), failed: failedTests(output) }); }); }); } @@ -139,16 +143,51 @@ export async function treeChanges(workspace: string, initial: ReadonlyMap, allowed?: (file: string) => boolean): Promise { +export async function checkScope( + checks: Checks, + workspace: string, + initial: ReadonlyMap, + allowed?: (file: string) => boolean, + opts: { readonly allowedDeletions?: readonly string[] } = {}, +): Promise { const c = await treeChanges(workspace, initial); if (allowed === undefined) { const all = [...c.modified.map((f) => `modified ${f}`), ...c.deleted.map((f) => `deleted ${f}`), ...c.added.map((f) => `added ${f}`)]; checks.check(all.length === 0, all.length === 0 ? 'workspace unchanged (read-only task)' : `read-only task changed the workspace: ${all.join(', ')}`); return; } - const outside = [...c.modified.filter((f) => !allowed(f)).map((f) => `modified ${f}`), ...c.deleted.map((f) => `deleted ${f}`)]; + const allowedDeletions = opts.allowedDeletions ?? []; + const outside = [...c.modified.filter((f) => !allowed(f)).map((f) => `modified ${f}`), ...c.deleted.filter((f) => !allowedDeletions.includes(f)).map((f) => `deleted ${f}`)]; 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..ce027d0 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,14 @@ 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 { T13_FILES, verify as verifyT13 } from './T13/verify.ts'; +import { T14_FILES, verify as verifyT14 } from './T14/verify.ts'; +import { T15_FILES, verify as verifyT15 } from './T15/verify.ts'; import { applySolution as solveT1 } from './T1/solution/apply.ts'; import { applySolution as solveT2 } from './T2/solution/apply.ts'; import { applySolution as solveT3 } from './T3/solution/apply.ts'; @@ -18,6 +26,13 @@ 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'; +import { applySolution as solveT13 } from './T13/solution/apply.ts'; +import { applySolution as solveT14 } from './T14/solution/apply.ts'; +import { applySolution as solveT15 } from './T15/solution/apply.ts'; const same = (tree: Tree): Tree => tree; @@ -106,6 +121,127 @@ export const TASKS: Readonly> = { verify: verifyT8, solution: solveT8, }, + // T9-T15 add their own files in setup (the shared fixture stays as it is) and T9-T11 and T13-T15 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, + }, + // T13 and T14 are the hard pair: short to solve, graded by hidden tests that cover every written + // rule (T13: the contract in the module header; T14: the numbered rules of the prompt). + T13: { + id: 'T13', + title: 'two bugs at the seam of an async job queue', + size: 'debug', + hiddenTests: true, + prompt: () => + [ + 'The job queue in src/jobs/ misbehaves in production:', + '- when jobs fail and are retried, more jobs run at the same time than the `concurrency` limit allows;', + '- once a job has failed for good, every later `add` with the same key gets that old failure back and the new function never runs.', + 'The contract in the header comment of src/jobs/queue.js is correct and complete; the code does not honor it. Find the root causes and fix them there, so that the module honors every rule of the contract. Keep the public API as it is (`createQueue` and its options, `add`, `stats`). Keep `node --test` passing and do not edit the tests.', + ].join('\n'), + setup: addFiles(T13_FILES), + protectedHook: false, + verify: verifyT13, + solution: solveT13, + }, + T14: { + id: 'T14', + title: 'streaming CSV parser with chunk boundaries anywhere', + size: 'feature', + hiddenTests: true, + prompt: () => + [ + 'Implement the streaming CSV parser in src/lib/csv.js: `createCsvParser()` is a stub; `CsvError` and `parseCsv` are already there and must stay exported. Rules:', + '1. `createCsvParser()` returns an object with the methods `push(chunk)` and `end()`. The input is the concatenation of the chunks, which are JavaScript strings (not bytes). Only `,`, `"`, `\\r` and `\\n` are special: nothing is trimmed and a BOM is data. A chunk may end anywhere, including between the two quotes of `""`, between `\\r` and `\\n` and in the middle of a surrogate pair, and the records never depend on how the input was cut into chunks.', + '2. A record is an array of field strings. Fields are separated by `,` and a record ends with `\\n` or `\\r\\n`. An empty line is a record with one empty field. Records may have different numbers of fields.', + '3. A field that starts with `"` is quoted: it runs to its closing `"`; inside it `""` is one literal `"`, and `,`, `\\r` and `\\n` are data. The closing quote must be followed by `,`, a record end or the end of the input.', + '4. `push(chunk)` returns an array with the records completed by that chunk, in input order. A record is completed by the `\\n` that ends it. `push(\'\')` returns `[]`.', + '5. `end()` returns `[]` when the input is empty or ends with a record end (a final newline does not create an empty record). Otherwise it returns an array with the last record: the input `a,` ends with the record `[\'a\', \'\']`, and `a\\n""` with the record `[\'\']`.', + '6. Invalid input throws a `CsvError`: (a) a `"` in a field that did not start with one; (b) a character other than `,`, `\\r` or `\\n` right after a closing quote; (c) outside a quoted field, a `\\r` that is not followed by `\\n`; (d) input that ends inside a quoted field. The `push` that receives the offending character throws, and in (c) that is the character after the `\\r`. Case (d), and case (c) when nothing follows the `\\r`, throw from `end()`.', + '7. After a `CsvError`, and after `end()` has been called, every `push` and every `end` throws a `CsvError`. `push` with a chunk that is not a primitive string throws a `TypeError` that is not a `CsvError` and leaves the parser as it was.', + '8. `parseCsv(text)` returns all the records of a complete input: one `push(text)` followed by `end()`.', + 'test/csv.test.js covers the basic case. Keep `node --test` passing and do not edit the tests.', + ].join('\n'), + setup: addFiles(T14_FILES), + protectedHook: false, + verify: verifyT14, + solution: solveT14, + }, + // T15 is the long one: dozens of small reads and edits, with files that only look like callers. + T15: { + id: 'T15', + title: 'migrate 36 modules to a new HTTP API, with look-alikes that must not change', + size: 'long-edit', + hiddenTests: true, + prompt: () => + [ + 'src/lib/legacy-http.js (`legacyFetch`, `legacyJson`) is deprecated in favour of `request` from src/lib/http.js. Finish the migration:', + '- Migrate every caller of src/lib/legacy-http.js to `request`, following the MIGRATION notes in the header comment of src/lib/legacy-http.js and the contract in the header comment of src/lib/http.js. Those two comments are correct and complete.', + '- Each caller imports `request` from src/lib/http.js and calls it directly: do not add a wrapper or compatibility helper.', + '- Then delete src/lib/legacy-http.js.', + '- Change only callers of src/lib/legacy-http.js: every other file stays exactly as it is, src/lib/http.js included.', + '- Every module keeps its exported functions, with the same parameters and the same results.', + 'Keep `node --test` passing and do not edit the tests.', + ].join('\n'), + setup: addFiles(T15_FILES), + protectedHook: false, + verify: verifyT15, + solution: solveT15, + }, }; /** 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..5641c0b 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' | 'T13' | 'T14' | 'T15'; +export const TASK_IDS: readonly TaskId[] = ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'T13', 'T14', 'T15']; export interface VerifyContext { /** Absolute path of the final workspace. */ @@ -32,7 +32,9 @@ export type Solution = (workspace: string, facts: FixtureFacts) => Promise {}, 1000); else { @@ -128,10 +130,16 @@ 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); - if (files[0] === undefined) throw new Error(`no ${name} under ${dir}`); - return readFile(path.join(dir, files[0]), 'utf8'); +/** + * A file of the one warmup run or the one matrix run, picked by the `warmup` flag of the record next to + * it: directory order (and so which run comes first) differs between filesystems. + */ +async function runFile(dir: string, name: string, warmup: boolean): Promise { + const records = (await readdir(dir, { recursive: true })).filter((f) => path.basename(f) === 'record.json'); + const hits: string[] = []; + for (const r of records) if (z.object({ warmup: z.boolean() }).parse(JSON.parse(await readFile(path.join(dir, r), 'utf8'))).warmup === warmup) hits.push(r); + if (hits.length !== 1 || hits[0] === undefined) throw new Error(`expected one ${warmup ? 'warmup' : 'matrix'} record under ${dir}, found ${hits.length}`); + return readFile(path.join(dir, path.dirname(hits[0]), name), 'utf8'); } describe.skipIf(!posix)('temporary CODEX_HOME: interruption', () => { @@ -188,7 +196,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 runFile(path.join(h.root, 'results'), 'auth.txt', true)).toBe('auth.json: written-back\n'); + expect(await runFile(path.join(h.root, 'results'), 'auth.txt', false)).toBe('auth.json: unchanged\n'); } finally { await cleanup(h); } @@ -199,7 +209,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 runFile(path.join(h.root, 'results'), 'auth.txt', true)).toBe('auth.json: conflict-kept-real\n'); expect(await authFiles(h.work)).toEqual([]); } finally { await cleanup(h); @@ -210,9 +220,10 @@ describe.skipIf(!posix)('temporary CODEX_HOME: token refresh on a finished run', const h = await harness('exit'); try { expect(await readFile(h.realAuth, 'utf8')).toBe(ORIGINAL); - expect(await findFile(path.join(h.root, 'results'), 'auth.txt')).toBe('auth.json: unchanged\n'); + expect(await runFile(path.join(h.root, 'results'), 'auth.txt', true)).toBe('auth.json: unchanged\n'); + expect(await runFile(path.join(h.root, 'results'), 'auth.txt', false)).toBe('auth.json: unchanged\n'); // A real (non-dry) Codex run whose tool surface was observed is a valid run. - const record = JSON.parse(await findFile(path.join(h.root, 'results'), 'record.json')); + const record = JSON.parse(await runFile(path.join(h.root, 'results'), 'record.json', false)); expect(record.invalidReasons).toEqual([]); expect(record.valid).toBe(true); expect(record.parsed.availableTools).toContain('functions.exec_command'); diff --git a/bench/test/parsers.test.ts b/bench/test/parsers.test.ts index afed50f..5297fe2 100644 --- a/bench/test/parsers.test.ts +++ b/bench/test/parsers.test.ts @@ -4,7 +4,8 @@ import { describe, expect, it } from 'vitest'; 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 { checkArm, checkSurface, isAcmArm, type ToolCalls } 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'); @@ -13,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); @@ -41,6 +43,41 @@ describe('Claude transcript parser', () => { expect(checkSurface('claude', 'B', p.availableTools ?? [])).toEqual([]); }); + it('reads a hybrid run: native calls and run calls in one transcript (claude-C.jsonl, synthetic)', () => { + const p = parseClaudeTranscript(read('claude-C.jsonl')); + expect(p.toolCalls).toEqual({ native: 1, run: 1, codeMode: 0, other: 0, byName: { Read: 1, 'mcp__agent-code-mode__run': 1 } }); + expect(p.innerCalls).toEqual({ total: 3, byTool: { grep: 1, read: 2 } }); + expect(p.requests).toBe(3); + expect(checkArm('claude', 'C', p.toolCalls)).toEqual({ fallback: false, reasons: [] }); + expect(checkSurface('claude', 'C', p.availableTools ?? [])).toEqual([]); + // The same transcript is neither arm A nor arm B. + expect(checkSurface('claude', 'A', p.availableTools ?? []).join()).toMatch(/expected exactly/); + expect(checkSurface('claude', 'B', p.availableTools ?? []).join()).toMatch(/expected exactly/); + expect(checkArm('claude', 'A', p.toolCalls).reasons).toContain('arm made agent-code-mode run calls'); + expect(checkArm('claude', 'B', p.toolCalls).fallback).toBe(true); + }); + + it('the hybrid arm accepts native only, run only and any mix, and nothing outside its surface', () => { + const calls = (native: number, run: number, extra: Partial = {}): ToolCalls => ({ native, run, codeMode: 0, other: 0, byName: {}, ...extra }); + for (const c of [calls(3, 2), calls(5, 0), calls(0, 4), calls(0, 0)]) expect(checkArm('claude', 'C', c)).toEqual({ fallback: false, reasons: [] }); + expect(checkArm('claude', 'C', calls(1, 1, { other: 2 })).reasons).toEqual(['hybrid agent-code-mode arm made 2 call(s) to tools outside its surface']); + expect(checkArm('claude', 'C', calls(1, 1, { codeMode: 1 })).reasons).toEqual(['hybrid agent-code-mode arm used Codex code mode']); + // Its surface is exactly the six native tools plus run. + const surface = ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'mcp__agent-code-mode__run']; + expect(checkSurface('claude', 'C', surface)).toEqual([]); + expect(checkSurface('claude', 'C', [...surface, 'Task']).join()).toMatch(/expected exactly/); + expect(checkSurface('claude', 'C', surface.filter((t) => t !== 'Bash')).join()).toMatch(/expected exactly/); + expect(checkSurface('claude', 'C', surface.slice(0, 6)).join()).toMatch(/expected exactly/); + // Codex C is still the strict agent-code-mode arm. + expect(checkArm('codex', 'C', calls(1, 2))).toEqual({ fallback: true, reasons: ['strict agent-code-mode arm made 1 native file/shell tool call(s)'] }); + expect(checkArm('codex', 'C', calls(0, 0)).reasons).toEqual(['agent-code-mode arm made no run call']); + expect(isAcmArm('claude', 'C')).toBe(true); + expect(isAcmArm('claude', 'B0')).toBe(true); + expect(isAcmArm('claude', 'A')).toBe(false); + expect(isAcmArm('codex', 'B')).toBe(false); + expect(isAcmArm('codex', 'C0')).toBe(true); + }); + it('counts a replayed tool result once (same tool_use_id)', () => { const raw = read('claude-B.jsonl'); const replay = raw.split('\n').filter((l) => l.includes('tool_result')); @@ -49,6 +86,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: {} }] } }, @@ -226,3 +272,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-baseline.test.ts b/bench/test/run-baseline.test.ts new file mode 100644 index 0000000..7f2f838 --- /dev/null +++ b/bench/test/run-baseline.test.ts @@ -0,0 +1,47 @@ +// The baseline build arm dry runs of main(), apart from run.test.ts so that Vitest runs them in their own process. +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { main } from '../run.ts'; +import { quiet } from './quiet.ts'; + +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', 'C: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', 'C-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 }); + } + }, 300_000); // End to end through main(): on Windows it competes for the CPU with the other test files. + + 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 }); + } + }, 300_000); // End to end through main(): on Windows it competes for the CPU with the other test files. +}); diff --git a/bench/test/run-dry.test.ts b/bench/test/run-dry.test.ts index a84bdfc..4bd650a 100644 --- a/bench/test/run-dry.test.ts +++ b/bench/test/run-dry.test.ts @@ -23,11 +23,15 @@ describe('dry run', () => { process.stdout.write = orig; } const text = writes.join(''); - expect(text.match(/: pass, valid/g)).toHaveLength(10); - expect(text.match(/^skip /gm)).toHaveLength(10); + expect(text.match(/^(claude|codex) T\d+ \w+ r1: pass, valid/gm)).toHaveLength(12); + // 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(6); + expect(text.match(/^skip /gm)).toHaveLength(12); 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.groups).toHaveLength(12); + expect(summary.warmup.runs).toBe(6); + expect(text).toMatch(/Warmup: 6 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([]); diff --git a/bench/test/run-isolation.test.ts b/bench/test/run-isolation.test.ts new file mode 100644 index 0000000..7693146 --- /dev/null +++ b/bench/test/run-isolation.test.ts @@ -0,0 +1,92 @@ +// Workspace isolation checks that run main() end to end, apart from run.test.ts so that Vitest runs them in their own process. +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, readdir, readFile, rm, symlink } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { assertWorkspaceIsolated, defaultWorkDir, insideRepo, main, parseOptions, REPO_ROOT, resolveBaseline } from '../run.ts'; +import { quiet } from './quiet.ts'; + +/** 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 * 3 + 2 * 3 + 6); // 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 }); + } + }, 300_000); // End to end through main(): on Windows it competes for the CPU with the other test files. + + 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/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/bench/test/run.test.ts b/bench/test/run.test.ts index 9a24ce8..d359572 100644 --- a/bench/test/run.test.ts +++ b/bench/test/run.test.ts @@ -1,7 +1,12 @@ +import { mkdir, mkdtemp, rm, 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 { parseOptions, planRuns } from '../run.ts'; +import { npmCommand, parseOptions, planRuns, planWarmup, 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', () => { @@ -11,21 +16,92 @@ 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); - expect(planRuns(['claude'], ['T1'], ['C'], 1, 1)).toEqual([]); +/** 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', 'C'] : ['A', 'B', 'C']) : 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); + // Claude C is the hybrid arm; the baseline arm C0 is Codex only, B0 Claude only. + expect(planRuns(['claude'], ['T1'], ['C'], 1, 1).map((p) => `${p.host}${p.arm}`)).toEqual(['claudeC']); + expect(planRuns(['claude'], ['T1'], ['C0'], 1, 1, true)).toEqual([]); + expect(planRuns(['codex'], ['T1'], ['B0'], 1, 1, true)).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', 'claudeC', 'codexA', 'codexB', 'codexC', 'codexC0']); + expect(warm.every((p) => p.task === WARMUP_TASK && p.warmup === true)).toBe(true); }); }); @@ -40,6 +116,12 @@ describe('host commands', () => { // Arm A: exactly the native file/shell tools, nothing else built in. expect(a.slice(a.indexOf('--tools'))).toEqual(['--tools', 'Bash,Read,Write,Edit,Glob,Grep', '--allowedTools', 'Bash,Read,Write,Edit,Glob,Grep']); expect(claudeMcpConfig('A', 'x')).toEqual({ mcpServers: {} }); + expect(claudeMcpConfig('B', 'x')).toMatchObject({ mcpServers: { 'agent-code-mode': { args: ['x', 'serve', '--host', 'claude'] } } }); + // Arm C (hybrid): the native tools of A plus run, and the server started with --hybrid. + const c = claudeArgs({ arm: 'C', model: 'm', effort: 'low', maxTurns: 5, settingsFile: 's.json', mcpConfigFile: 'm.json' }); + expect(c.slice(c.indexOf('--tools'))).toEqual(['--tools', 'Bash,Read,Write,Edit,Glob,Grep', '--allowedTools', 'mcp__agent-code-mode__run,Bash,Read,Write,Edit,Glob,Grep']); + expect(c.slice(0, c.indexOf('--tools'))).toEqual(a.slice(0, a.indexOf('--tools'))); + expect(claudeMcpConfig('C', 'x')).toMatchObject({ mcpServers: { 'agent-code-mode': { args: ['x', 'serve', '--host', 'claude', '--hybrid'] } } }); }); it('writes the Codex config each arm needs', () => { @@ -67,3 +149,28 @@ describe('host commands', () => { expect(JSON.parse(catalogForArm('A', raw)).models[0]).toMatchObject({ supports_search_tool: false, experimental_supported_tools: [] }); }); }); + +describe('npm without a shell', () => { + it('runs npm-cli.js with this Node (npm is a .cmd shim on Windows), from npm_execpath or next to node', async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), 'acm-npm-')); + try { + const win = path.join(tmp, 'win'); + const cli = path.join(win, 'node_modules', 'npm', 'bin', 'npm-cli.js'); + await mkdir(path.dirname(cli), { recursive: true }); + await writeFile(cli, ''); + const node = path.join(win, 'node.exe'); + expect(npmCommand({}, node)).toEqual({ command: node, args: [cli] }); + const posix = path.join(tmp, 'prefix'); + const cli2 = path.join(posix, 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'); + await mkdir(path.dirname(cli2), { recursive: true }); + await writeFile(cli2, ''); + expect(npmCommand({}, path.join(posix, 'bin', 'node'))).toEqual({ command: path.join(posix, 'bin', 'node'), args: [path.join(posix, 'bin', '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')] }); + expect(npmCommand({ npm_execpath: cli2 }, node)).toEqual({ command: node, args: [cli2] }); + expect(npmCommand({ npm_execpath: path.join(tmp, 'pnpm.cjs') }, path.join(tmp, 'none', 'node'))).toEqual({ command: 'npm', args: [] }); + // On this machine it resolves to a real npm-cli.js. + expect(npmCommand().args[0] ?? '').toMatch(/npm-cli\.js$/); + } finally { + await rm(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/bench/test/verifier-hidden-t13-t14.test.ts b/bench/test/verifier-hidden-t13-t14.test.ts new file mode 100644 index 0000000..c6b4f0a --- /dev/null +++ b/bench/test/verifier-hidden-t13-t14.test.ts @@ -0,0 +1,80 @@ +// The hidden-test cases of T13 and T14. The verifier cases are split across files so that Vitest runs them in parallel processes. +import { describe, expect, it } from 'vitest'; +import { TASKS } from '../tasks/index.ts'; +import { verifierWorkspaces, edit } from './verifier-workspaces.ts'; + +const { workspace } = await verifierWorkspaces(); + +describe('hidden-test tasks', () => { + // The two planted T13 bugs as one-step fixes, and the partial fixes an agent is likely to try. + const T13_SLOT_FIX = ['src/jobs/retry.js', ' release();\n', ''] as const; + + const T13_KEY_FIX = ['src/jobs/queue.js', 'job.reject = reject;', 'job.reject = (err) => { keys.release(key); reject(err); };'] as const; + + const T13_PARTIAL: readonly { readonly name: string; readonly edits: readonly (readonly [string, string, string])[]; readonly caught: RegExp }[] = [ + { name: 'only the slot is fixed', edits: [T13_SLOT_FIX], caught: /a key that gave up is free again/ }, + { name: 'only the key is fixed', edits: [T13_KEY_FIX], caught: /a job in backoff frees exactly one slot.*the limit holds for jobs added after a retry/ }, + { + name: 'the slot count is clamped instead of released once', + edits: [T13_KEY_FIX, ['src/jobs/slots.js', 'else active -= 1;', 'else active = Math.max(0, active - 1);']], + caught: /a job in backoff frees exactly one slot/, + }, + { + name: 'the key is freed on every failed attempt, not when the job settles', + edits: [T13_SLOT_FIX, ['src/jobs/queue.js', ' } catch (err) {\n', ' } catch (err) {\n keys.release(job.key);\n']], + caught: /a pending key is de-duplicated while waiting, running and in backoff/, + }, + { + name: 'the key is freed only after the handlers of the promise ran', + edits: [T13_SLOT_FIX, ['src/jobs/queue.js', ' keys.hold(key, promise);\n', ' keys.hold(key, promise);\n promise.catch(() => {}).finally(() => keys.release(key));\n']], + caught: /the key is already free inside the handlers of the promise/, + }, + ]; + + it('T13 accepts the two one-step fixes together', async () => { + const ws = await workspace('T13'); + for (const [rel, from, to] of [T13_SLOT_FIX, T13_KEY_FIX]) await edit(ws.dir, rel, from, to); + const result = await TASKS.T13.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(result.details.filter((d) => d.startsWith('FAIL'))).toEqual([]); + }); + + it.each(T13_PARTIAL)('T13 rejects a partial fix: $name', async ({ edits, caught }) => { + const ws = await workspace('T13'); + for (const [rel, from, to] of edits) await edit(ws.dir, rel, from, to); + const result = await TASKS.T13.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(result.pass).toBe(false); + expect(result.details[0]).toMatch(/^ok node --test passes/); + const hidden = result.details.find((d) => d.startsWith('FAIL hidden tests pass')) ?? ''; + expect(hidden).toMatch(caught); + }); + + // T14: the reference parser with one chunk-boundary or end-of-input rule dropped. + const T14_LOOP = ' for (let i = 0; i < chunk.length; i += 1) {\n'; + + const T14_PARTIAL: readonly { readonly name: string; readonly from: string; readonly to: string; readonly caught: RegExp }[] = [ + { + name: 'a carriage return at the end of a chunk ends the record', + from: T14_LOOP, + to: ` if (state === CR && chunk.length > 0) endRecord();\n${T14_LOOP}`, + caught: /rule 4: push returns the records completed by the chunk; rule 1: a chunk may end anywhere.*fuzz: built records/, + }, + { + name: 'a quote at the end of a chunk always closes the field', + from: T14_LOOP, + to: ` if (state === QUOTE && chunk[0] === '"') fail('unexpected character after a closing quote');\n${T14_LOOP}`, + caught: /rule 1: a chunk may end anywhere.*fuzz: built records/, + }, + { name: 'a final newline creates an empty record', from: 'if (state !== RECORD_START) {', to: '{', caught: /rule 5: end returns the unterminated last record/ }, + { name: 'a lone carriage return at the end of the input is accepted', from: " if (state === CR) fail('carriage return without a line feed');\n", to: '', caught: /rule 6: invalid input throws CsvError/ }, + ]; + + it.each(T14_PARTIAL)('T14 rejects a parser where $name', async ({ from, to, caught }) => { + const ws = await workspace('T14'); + await TASKS.T14.solution(ws.dir, ws.fixture.facts); + await edit(ws.dir, 'src/lib/csv.js', from, to); + const result = await TASKS.T14.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(result.pass).toBe(false); + const hidden = result.details.find((d) => d.startsWith('FAIL hidden tests pass')) ?? ''; + expect(hidden).toMatch(caught); + }); +}); diff --git a/bench/test/verifier-hidden-t15-rules.test.ts b/bench/test/verifier-hidden-t15-rules.test.ts new file mode 100644 index 0000000..2d60b4b --- /dev/null +++ b/bench/test/verifier-hidden-t15-rules.test.ts @@ -0,0 +1,29 @@ +// The hidden-test cases of T15 on the mapping rules. The verifier cases are split across files so that Vitest runs them in parallel processes. +import { describe, expect, it } from 'vitest'; +import { verifierWorkspaces, edit, hiddenLine } from './verifier-workspaces.ts'; + +const { solvedT15 } = await verifierWorkspaces(); + +describe('hidden-test tasks', () => { + // The reference solution with one mapping rule of the MIGRATION notes dropped in one caller. + const T15_WRONG_RULE: readonly { readonly name: string; readonly file: string; readonly from: string; readonly to: string }[] = [ + { name: 'a timeout is left in seconds', file: 'catalog/search.js', from: 'timeoutMs: 3000', to: 'timeoutMs: 3' }, + { name: 'a method keeps its lower case', file: 'billing/dunning.js', from: 'method: String(method).toUpperCase(),', to: 'method,' }, + { name: 'a JSON body goes without its content-type', file: 'notifications/email.js', from: " headers: { 'content-type': 'application/json' },\n", to: '' }, + { name: 'a JSON body is sent as a string', file: 'users/invites.js', from: 'body: { email, role },', to: 'body: JSON.stringify({ email, role }),' }, + { name: 'the query is dropped', file: 'shipping/tracking.js', from: ", query: { events: 'last' }", to: '' }, + { name: 'an undefined timeout is multiplied', file: 'notifications/webhooks.js', from: 'if (hook.timeoutSeconds !== undefined) options.timeoutMs', to: 'options.timeoutMs' }, + { name: 'an error status the caller handled now throws', file: 'shipping/pickups.js', from: 'if (err instanceof HttpError) return false;', to: '' }, + { name: 'every error is swallowed, not only HttpError', file: 'users/preferences.js', from: 'if (err instanceof HttpError) return false;\n throw err;', to: 'return false;' }, + { name: 'the result still reads data', file: 'orders/export.js', from: 'return res.body;', to: 'return res.data;' }, + ]; + + it.each(T15_WRONG_RULE)('T15 rejects a migration where $name', async ({ file, from, to }) => { + const { ws, verify } = await solvedT15(); + await edit(ws.dir, `src/services/${file}`, from, to); + const result = await verify(); + expect(result.pass).toBe(false); + expect(result.details[0]).toMatch(/^ok node --test passes/); + expect(hiddenLine(result.details)).toBe(`FAIL hidden tests pass (pass 40, fail 1: behaviour: ${file})`); + }); +}); diff --git a/bench/test/verifier-hidden-t15-shims.test.ts b/bench/test/verifier-hidden-t15-shims.test.ts new file mode 100644 index 0000000..735edb7 --- /dev/null +++ b/bench/test/verifier-hidden-t15-shims.test.ts @@ -0,0 +1,52 @@ +// The hidden-test cases of T15 on shims and look-alikes. The verifier cases are split across files so that Vitest runs them in parallel processes. +import { rm, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { verifierWorkspaces, edit, hiddenLine } from './verifier-workspaces.ts'; + +const { solvedT15 } = await verifierWorkspaces(); + +describe('hidden-test tasks', () => { + it('T15 rejects a shim: the old helper kept as a wrapper over request', async () => { + const { ws, verify } = await solvedT15(); + await writeFile( + path.join(ws.dir, 'src', 'lib', 'http-compat.js'), + "import { request } from './http.js';\nexport const legacyFetch = async (url, opts = {}) => {\n const res = await request({ url, query: opts.qs });\n return { status: res.status, data: res.body };\n};\n", + ); + await writeFile( + path.join(ws.dir, 'src', 'services', 'catalog', 'products.js'), + (ws.initial.get('src/services/catalog/products.js') ?? '').replace('../../lib/legacy-http.js', '../../lib/http-compat.js'), + ); + const result = await verify(); + expect(result.pass).toBe(false); + expect(result.details[0]).toMatch(/^ok node --test passes/); + expect(hiddenLine(result.details)).toMatch(/static: every former caller imports src\/lib\/http\.js and calls request itself; static: the old helpers are not recreated/); + // The same wrapper under another name is still caught: its caller does not call request itself. + await edit(ws.dir, 'src/lib/http-compat.js', 'export const legacyFetch =', 'export const fetchCompat ='); + await edit(ws.dir, 'src/services/catalog/products.js', 'import { legacyFetch }', 'import { fetchCompat as legacyFetch }'); + await edit(ws.dir, 'src/services/catalog/products.js', "import { API } from '../config.js';", "import { API } from '../config.js';\nimport { request } from '../../lib/http.js';"); + const renamed = await verify(); + expect(hiddenLine(renamed.details)).toMatch(/static: the old helpers are not recreated/); + }); + + it('T15 rejects a migration that also rewrote a look-alike, and any deletion but the old module', async () => { + const trap = await solvedT15(); + await edit(trap.ws.dir, 'src/services/billing/tax-rules.js', 'legacyFetch(url)', 'request(options)'); + const rewritten = await trap.verify(); + expect(rewritten.pass).toBe(false); + expect(rewritten.details.filter((d) => d.startsWith('FAIL'))).toEqual(['FAIL files that are not callers of legacy-http changed: src/services/billing/tax-rules.js']); + + const vendor = await solvedT15(); + await edit(vendor.ws.dir, 'src/services/users/session-cache.js', "import * as cache from '../../vendor/cache/legacy.js';", "import * as cache from '../../vendor/cache/legacy.js'; // not HTTP"); + expect((await vendor.verify()).details.join('\n')).toMatch(/FAIL files that are not callers of legacy-http changed: src\/services\/users\/session-cache\.js/); + + const deleted = await solvedT15(); + await rm(path.join(deleted.ws.dir, 'src', 'services', 'config.js')); + await rm(path.join(deleted.ws.dir, 'src', 'lib', 'dates.js')); + expect((await deleted.verify()).details.join('\n')).toMatch(/FAIL changed outside the task: deleted src\/lib\/dates\.js, deleted src\/services\/config\.js/); + + const http = await solvedT15(); + await edit(http.ws.dir, 'src/lib/http.js', "const DEFAULT_TIMEOUT_MS = 30000;", "const DEFAULT_TIMEOUT_MS = 30_000;"); + expect((await http.verify()).details.join('\n')).toMatch(/FAIL changed outside the task: modified src\/lib\/http\.js/); + }); +}); diff --git a/bench/test/verifier-hidden-t15.test.ts b/bench/test/verifier-hidden-t15.test.ts new file mode 100644 index 0000000..d3b2704 --- /dev/null +++ b/bench/test/verifier-hidden-t15.test.ts @@ -0,0 +1,23 @@ +// The hidden-test cases of T15 on callers left on the old API. The verifier cases are split across files so that Vitest runs them in parallel processes. +import { describe, expect, it } from 'vitest'; +import { verifierWorkspaces, hiddenLine } from './verifier-workspaces.ts'; + +const { solvedT15 } = await verifierWorkspaces(); + +describe('hidden-test tasks', () => { + // One caller per import shape left on the old API (with the old module kept, so that it still runs). + it.each([ + { shape: 'named import', file: 'src/services/catalog/products.js' }, + { shape: 'aliased import', file: 'src/services/users/search.js' }, + { shape: 'namespace import', file: 'src/services/orders/cancel.js' }, + { shape: 'aliased legacyJson', file: 'src/services/shipping/zones.js' }, + ])('T15 rejects a migration that missed the $shape', async ({ file }) => { + const { verify, restore } = await solvedT15(); + await restore(file); + await restore('src/lib/legacy-http.js'); + const result = await verify(); + expect(result.pass).toBe(false); + expect(result.details[0]).toMatch(/^ok node --test passes/); + expect(hiddenLine(result.details)).toMatch(/static: src\/lib\/legacy-http\.js is deleted; static: no file imports legacy-http; static: every former caller imports/); + }); +}); diff --git a/bench/test/verifier-hidden.test.ts b/bench/test/verifier-hidden.test.ts new file mode 100644 index 0000000..7bd676d --- /dev/null +++ b/bench/test/verifier-hidden.test.ts @@ -0,0 +1,88 @@ +// The hidden-test cases of T9-T12. The verifier cases are split across files so that Vitest runs them in parallel processes. +import { readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { TASKS } from '../tasks/index.ts'; +import { verifierWorkspaces } from './verifier-workspaces.ts'; + +const { workspace } = await verifierWorkspaces(); + +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 and T13-T15 never leave hidden tests in the workspace', async () => { + for (const id of ['T9', 'T10', 'T11', 'T13', 'T14', 'T15'] 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('a deletion stays out of scope for the tasks that allow none, inside their own directory too', async () => { + const ws = await workspace('T13'); + await rm(path.join(ws.dir, 'src', 'jobs', 'clock.js')); + const result = await TASKS.T13.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(result.details.join('\n')).toMatch(/FAIL changed outside the task: deleted src\/jobs\/clock\.js/); + }); + + 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/'))); + }); +}); diff --git a/bench/test/verifier-tasks-late.test.ts b/bench/test/verifier-tasks-late.test.ts new file mode 100644 index 0000000..e7489ec --- /dev/null +++ b/bench/test/verifier-tasks-late.test.ts @@ -0,0 +1,26 @@ +// The per-task verifier cases from T12 on. The verifier cases are split across files so that Vitest runs them in parallel processes. +import { describe, expect, it } from 'vitest'; +import { TASKS } from '../tasks/index.ts'; +import { TASK_IDS } from '../tasks/types.ts'; +import { verifierWorkspaces } from './verifier-workspaces.ts'; + +const { workspace } = await verifierWorkspaces(); + +describe.each(TASK_IDS.slice(11))('verifier %s', (id) => { + const task = TASKS[id]; + + it('fails on the untouched fixture', async () => { + const ws = await workspace(id); + const result = await task.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + expect(result.pass).toBe(false); + expect(result.details.some((d) => d.startsWith('FAIL'))).toBe(true); + }); + + it('passes on the reference solution', async () => { + const ws = await workspace(id); + const answer = await task.solution(ws.dir, ws.fixture.facts); + const result = await task.verify({ workspace: ws.dir, answer, facts: ws.fixture.facts, initial: ws.initial }); + expect(result.details.filter((d) => d.startsWith('FAIL'))).toEqual([]); + expect(result.pass).toBe(true); + }); +}); diff --git a/bench/test/verifier-workspaces.ts b/bench/test/verifier-workspaces.ts index a555ae7..d1259df 100644 --- a/bench/test/verifier-workspaces.ts +++ b/bench/test/verifier-workspaces.ts @@ -1,7 +1,7 @@ -import { mkdtemp, rm } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; -import { afterAll, vi } from 'vitest'; +import { afterAll, expect, vi } from 'vitest'; import { DEFAULT_FIXTURE_SEED } from '../fixture/generate.ts'; import { createWorkspace } from '../lib/workspace.ts'; import { TASKS } from '../tasks/index.ts'; @@ -28,5 +28,26 @@ export async function verifierWorkspaces() { return createWorkspace(path.join(root, `${task}-${n}`), TASKS[task], host, DEFAULT_FIXTURE_SEED); } - return { workspace }; + /** A T15 workspace with the reference solution applied, to break in one place. */ + async function solvedT15() { + const ws = await workspace('T15'); + await TASKS.T15.solution(ws.dir, ws.fixture.facts); + const verify = () => TASKS.T15.verify({ workspace: ws.dir, answer: '', facts: ws.fixture.facts, initial: ws.initial }); + const restore = async (rel: string): Promise => { + await writeFile(path.join(ws.dir, ...rel.split('/')), ws.initial.get(rel) ?? ''); + }; + return { ws, verify, restore }; + } + + return { workspace, solvedT15 }; } + +/** Replaces `from` (which must be there, once) with `to` in a workspace file. */ +export async function edit(dir: string, rel: string, from: string, to: string): Promise { + const file = path.join(dir, ...rel.split('/')); + const text = await readFile(file, 'utf8'); + expect(text.split(from).length, `${rel} has ${JSON.stringify(from)} once`).toBe(2); + await writeFile(file, text.replace(from, () => to)); +} + +export const hiddenLine = (details: readonly string[]): string => details.find((d) => d.startsWith('FAIL hidden tests pass')) ?? ''; diff --git a/bench/test/verifiers.test.ts b/bench/test/verifiers.test.ts index 6ccf4dd..1f42563 100644 --- a/bench/test/verifiers.test.ts +++ b/bench/test/verifiers.test.ts @@ -1,4 +1,4 @@ -// The per-task verifier cases. The verifier cases are split across files so that Vitest runs them in parallel processes. +// The per-task verifier cases for T1-T11. The verifier cases are split across files so that Vitest runs them in parallel processes. import { describe, expect, it } from 'vitest'; import { TASKS } from '../tasks/index.ts'; import { TASK_IDS } from '../tasks/types.ts'; @@ -6,7 +6,7 @@ import { verifierWorkspaces } from './verifier-workspaces.ts'; const { workspace } = await verifierWorkspaces(); -describe.each(TASK_IDS)('verifier %s', (id) => { +describe.each(TASK_IDS.slice(0, 11))('verifier %s', (id) => { const task = TASKS[id]; it('fails on the untouched fixture', async () => { diff --git a/src/cli.ts b/src/cli.ts index 110ecc5..247c0b4 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -12,7 +12,9 @@ import { recoverStaleJournals } from './tools/journal.js'; const USAGE = `Usage: agent-code-mode Commands: - serve [--host claude|codex|generic] Run the MCP stdio server + serve [--host claude|codex|generic] [--hybrid] + Run the MCP stdio server; --hybrid adds one line to the run description + for hosts that keep their native file and shell tools next to run hook Claude Code companion PreToolUse hook (reads the hook JSON on stdin) install --host claude|codex [--scope user|project] [--write] [--local] Print the host configuration; --write applies it after showing the diff; @@ -42,6 +44,22 @@ function parseHost(args: readonly string[]): HostKind | undefined | Error { return parsed.success ? parsed.data : new Error(`--host must be one of claude, codex, generic`); } +const HybridSchema = z.enum(['true', 'false']); + +/** `--hybrid` (or `--hybrid=true|false`): whether the `run` description gets the hybrid guidance line. */ +function parseHybrid(args: readonly string[]): boolean | Error { + let hybrid = false; + for (const arg of args) { + if (arg === '--hybrid') hybrid = true; + else if (arg.startsWith('--hybrid=')) { + const parsed = HybridSchema.safeParse(arg.slice('--hybrid='.length)); + if (!parsed.success) return new Error('--hybrid takes no value (or =true / =false)'); + hybrid = parsed.data === 'true'; + } + } + return hybrid; +} + export async function main(argv: readonly string[]): Promise { const [command, ...rest] = argv; if (command === '--version' || command === '-v') { @@ -59,6 +77,11 @@ export async function main(argv: readonly string[]): Promise { process.stderr.write(`${host.message}\n`); return 2; } + const hybrid = parseHybrid(rest); + if (hybrid instanceof Error) { + process.stderr.write(`${hybrid.message}\n`); + return 2; + } // Undo what runs of a crashed server left in this workspace before serving. const recovered = await recoverStaleJournals(stateDirPath(), [process.cwd()]); for (const { id, report, kept } of recovered) { @@ -67,7 +90,7 @@ export async function main(argv: readonly string[]): Promise { ); for (const s of report.skipped) process.stderr.write(`agent-code-mode: not restored: ${s.path} (${s.reason}${s.detail ? `: ${s.detail}` : ''})\n`); } - const server = createMcpServer({ version: readVersion(), ...(host ? { host } : {}) }); + const server = createMcpServer({ version: readVersion(), hybrid, ...(host ? { host } : {}) }); await server.connect(new StdioServerTransport()); return -1; // keep running until stdin closes } diff --git a/src/core/contracts.test.ts b/src/core/contracts.test.ts index a61c699..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,19 +115,20 @@ 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) => path.relative(ws, m.file))).toEqual([path.join('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.map((f) => path.relative(ws, f))).toEqual([path.join('src', 'a.ts')]); + expect(glob.files).toEqual(['src/a.ts']); expect(glob.filtered).toBe(2); }); 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); }); @@ -142,7 +143,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'); }); @@ -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) => path.relative(project, m.file))).toEqual([path.join('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 7d52199..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: result }; + return { ok: true, value: scriptResult(result, this.#canonicalCwd) }; } #toolFailure(err: unknown): Failure { @@ -560,10 +561,29 @@ 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, 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): 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; } /** Short description of a call for the call log. */ diff --git a/src/core/output.test.ts b/src/core/output.test.ts index 409c2af..660c176 100644 --- a/src/core/output.test.ts +++ b/src/core/output.test.ts @@ -1,89 +1,371 @@ -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 { describe, expect, it } from 'vitest'; +import { OverflowStore } from './overflow.js'; +import { + DIFF_INLINE_CHARS, + DIFF_STAT_FILES, + ERROR_CAP_CHARS, + RESULT_IN_NEXT_BLOCK, + GROUP_TEXT_CHARS, + SUCCESS_CAP_CHARS, + diffStat, + formatRunResult, + groupFailed, + runResultView, + summarizeCalls, + type McpToolResponse, + type OverflowSink, +} 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[] = []; -async function tmp(): Promise { - const d = await mkdtemp(path.join(os.tmpdir(), 'acm-out-')); - dirs.push(d); - return path.join(d, 'state'); + +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; } -afterEach(async () => { - await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true }))); + +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); + +/** 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'); + let text = ''; + for (;;) { + const reply = store.read({ id: overflow.id, offset: text.length, limit: 1_000_000 }); + if (!reply.ok || !('totalChars' in reply.value)) throw new Error('overflow not readable'); + text += reply.value.text; + if (!reply.value.truncated) return JSON.parse(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), + 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(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' }], + errors: [{ id: 'c4', tool: 'read', summary: 'read gone.txt', reason: 'gone.txt does not exist' }], + }); + }); + + 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']; + 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('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('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); + }); }); -describe('formatRunResult', () => { - 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('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('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('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(); }); +}); - 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'); +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('keeps a small diff whole', () => { + const small = fileDiffs(1, 2); + expect(json(formatRunResult({ ...base, diff: small }))).toMatchObject({ diff: small }); + }); + + 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 are grouped by tool and reason with exact counts, and the overflow has them all', () => { + const reason = `hook: ${'policy text '.repeat(10)}`; + const calls = Array.from({ length: 2_000 }, (_, i) => deniedCall(i, reason)); + const store = new OverflowStore(); + const out = formatRunResult({ ...base, result: 'r', calls }, { overflow: store }); + expect(total(out)).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + expect((json(out)['calls'] as { denied: unknown[] }).denied).toEqual([{ tool: 'read', reason, count: 2_000, first: 'read secret-0.txt' }]); + expect((kept(store, out) as RunResult).calls).toEqual(calls); + }); + + it('keeps every distinct reason of denied and failed calls, even in verbose and error results', () => { + const calls: CallLogEntry[] = []; + for (let i = 0; i < 3_000; i++) { + calls.push({ id: `d${i}`, tool: i % 2 ? 'bash' : 'write', summary: `${i % 2 ? 'bash' : 'write'} ${'s'.repeat(80)}${i}`, decision: 'denied', reason: `rule ${i % 7}`, durationMs: 0 }); + calls.push({ id: `e${i}`, tool: 'read', summary: `read m${i}`, decision: 'error', reason: `${'p'.repeat(100)} code ${i % 5}`, durationMs: 0 }); + } + for (const ok of [true, false]) { + for (const verbose of [false, true]) { + const result: RunResult = { ...base, ok, ...(ok ? {} : { error: { kind: 'error' as const, name: 'Error', message: 'boom' } }), calls }; + const out = formatRunResult(result, { overflow: new OverflowStore(), verbose }); + expect(total(out)).toBeLessThanOrEqual(ok ? SUCCESS_CAP_CHARS : ERROR_CAP_CHARS); + const shown = json(out)[verbose ? 'callSummary' : 'calls'] as { denied: { tool: string; reason: string; count: number }[]; errors: { reason: string; count: number }[] }; + expect(shown.denied).toHaveLength(14); + expect(shown.errors).toHaveLength(5); + expect(shown.denied.reduce((n, g) => n + g.count, 0)).toBe(3_000); + expect(shown.errors.reduce((n, g) => n + g.count, 0)).toBe(3_000); + expect(shown.denied[0]).toMatchObject({ tool: 'write', reason: 'rule 0', first: `write ${'s'.repeat(80)}0` }); + } + } + }); + + it('cuts reasons to GROUP_TEXT_CHARS before leaving a group out, and counts the groups left out', () => { + const errors = Array.from({ length: 1_000 }, (_, i): CallLogEntry => ({ id: `c${i}`, tool: 'read', summary: `read missing-${i}`, decision: 'error', reason: `missing-${i} ${'x'.repeat(1_000)}`, durationMs: 0 })); + const store = new OverflowStore(); + const out = formatRunResult({ ...base, result: 'done', calls: errors }, { overflow: store }); + expect(total(out)).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + const list = (json(out)['calls'] as { errors: unknown[] }).errors; + const groups = list.slice(0, -1) as { reason: string; count: number }[]; + expect(groups.length).toBeGreaterThan(50); + groups.forEach((g, i) => expect(g.reason).toBe(`missing-${i} ${'x'.repeat(GROUP_TEXT_CHARS - `missing-${i} `.length)}…[${`missing-${i} `.length + 1_000 - GROUP_TEXT_CHARS} chars cut]`)); + expect(list.at(-1)).toBe(`…[${1_000 - groups.length} more reasons (${1_000 - groups.length} calls) in overflow]`); + expect((kept(store, out) as RunResult).calls).toEqual(errors); + }); + + it('property: every reason shows until the groups fit no more, counts add up, and the overflow has every call', () => { + let seed = 11; + const rand = (n: number): number => ((seed = (seed * 1_103_515_245 + 12_345) % 2_147_483_648), seed % n); + const marker = /^…\[(\d+) more reasons? \((\d+) calls?\) in overflow\]$/; + for (let round = 0; round < 60; round++) { + const distinct = 1 + rand(round % 3 === 0 ? 3_000 : 40); + const reasons = Array.from({ length: distinct }, (_, r) => `reason ${r} ${'r'.repeat(rand(round % 4 === 0 ? 600 : 120))}`); + const n = 1 + rand(4_000); + const calls = Array.from({ length: n }, (_, i): CallLogEntry => { + const roll = rand(3); + const tool = ['read', 'bash', 'edit'][rand(3)] ?? 'read'; + return { id: `c${i}`, tool, summary: `${tool} ${'f'.repeat(rand(60))}${i}`, decision: roll === 0 ? 'allowed' : roll === 1 ? 'denied' : 'error', reason: reasons[rand(distinct)], durationMs: 0 }; + }); + const ok = rand(2) === 0; + const result: RunResult = { + ...base, + ok, + ...(ok ? { result: 'x\n'.repeat(rand(30_000)) } : { error: { kind: 'error' as const, name: 'Error', message: 'e'.repeat(rand(20_000)) } }), + logs: Array.from({ length: rand(500) }, (_, i) => `log ${i}`), + changedFiles: Array.from({ length: rand(300) }, (_, i) => `src/f${i}.ts`), + calls, + }; + const store = new OverflowStore(); + const verbose = rand(2) === 0; + const out = formatRunResult(result, { overflow: store, verbose }); + expect(total(out)).toBeLessThanOrEqual(ok ? SUCCESS_CAP_CHARS : ERROR_CAP_CHARS); + const expected = summarizeCalls(calls, result.error?.message); + if (json(out)['truncated'] !== true) { + expect(json(out)['calls']).toEqual(verbose ? calls : expected); + continue; + } + // Above the cap a verbose log stays a (cut) list and the compact calls go beside it. + const shownCalls = json(out)[verbose ? 'callSummary' : 'calls']; + if (verbose) expect(Array.isArray(json(out)['calls'])).toBe(true); + expect((kept(store, out) as RunResult).calls).toEqual(calls); + for (const key of ['denied', 'errors'] as const) { + const want = expected[key]; + const list = (shownCalls as Record)[key]; + if (want === undefined) { + expect(list).toBeUndefined(); + continue; + } + if (list === undefined) throw new Error(`${key} missing`); + if (list.every((e) => typeof e === 'object' && e !== null && 'id' in e)) { + expect(list).toEqual(want); + continue; + } + const groups = groupFailed(want); + const last = list.at(-1); + const m = typeof last === 'string' ? marker.exec(last) : null; + const shown = (m ? list.slice(0, -1) : list) as { tool: string; reason?: string; count: number }[]; + if (distinct <= 15) expect(m).toBeNull(); + expect(shown.length + Number(m?.[1] ?? 0)).toBe(groups.length); + expect(shown.reduce((a, g) => a + g.count, 0) + Number(m?.[2] ?? 0)).toBe(want.length); + shown.forEach((g, i) => { + const w = groups[i]; + expect(g.tool).toBe(w?.tool); + expect(g.count).toBe(w?.count); + const r = w?.reason ?? ''; + expect(g.reason === r || (g.reason ?? '').startsWith(`${r.slice(0, GROUP_TEXT_CHARS)}…[`)).toBe(true); + }); + } + } + }); + + 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 cc8a69d..29b8b25 100644 --- a/src/core/output.ts +++ b/src/core/output.ts @@ -1,125 +1,440 @@ -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 { RunResult } from './types.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; } +/** 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; + /** 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) }); } } +type FailedCall = Pick & { readonly reason?: string }; + +/** Compact call log: counts plus every denied and failed call. */ +export interface CompactCalls { + readonly total: number; + readonly byTool: Record; + readonly denied?: FailedCall[]; + readonly errors?: FailedCall[]; +} + +/** Denied or failed calls that share a tool and a reason: how many, and the summary of the first. */ +export interface FailedGroup { + readonly tool: string; + readonly reason?: string; + readonly count: number; + readonly first: string; +} + +/** Reason and first-call summary length in groups when even the groups do not fit. */ +export const GROUP_TEXT_CHARS = 200; + +/** `calls` grouped by (tool, reason) in order of first appearance, with exact counts. */ +export function groupFailed(calls: readonly FailedCall[]): FailedGroup[] { + const groups = new Map(); + for (const c of calls) { + const key = JSON.stringify([c.tool, c.reason ?? null]); + const g = groups.get(key); + if (g) g.count++; + else groups.set(key, { tool: c.tool, ...(c.reason === undefined ? {} : { reason: c.reason }), count: 1, first: c.summary }); + } + return [...groups.values()]; +} + +/** + * 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): CompactCalls { + 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 }) => { + 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 } : {}) }; +} + +/** 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; +} + /** - * 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. + * 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 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; +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 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: verbose ? calls : summarizeCalls(calls, result.error?.message), + ...(changedFiles.length > 0 ? { changedFiles } : {}), + ...(diff === '' ? {} : bigDiff ? { diffStat: diffStat(diff) } : { diff }), + ...(warnings.length > 0 ? { warnings } : {}), + }; + 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'], ['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)]); } - // 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}'; + return out; } -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; +/** `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: 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: 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. Denied and failed + * calls that do not fit whole are grouped by tool and reason with exact + * counts (see `capped`). 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 { 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); - if (full.length <= cap) return { content: [{ type: 'text', text: full }], isError }; + 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, summarizeCalls(result.calls, result.error?.message), overflow, full.length, cap, isError); +} - 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).` }; - } catch (err) { - extra = { note: `Result was ${full.length} chars and could not be saved: ${errorMessage(err)}` }; +/** `calls` with its denied and failed lists replaced. */ +function withFailed(calls: CompactCalls, denied: unknown[] | undefined, errors: unknown[] | undefined, byTool = true): Record { + return { total: calls.total, ...(byTool ? { byTool: calls.byTool } : {}), ...(denied ? { denied } : {}), ...(errors ? { errors } : {}) }; +} + +function clipGroup(g: FailedGroup, max: number): FailedGroup { + const clip = (t: string): string => (t.length <= max ? t : `${t.slice(0, max)}…[${t.length - max} chars cut]`); + return { tool: clip(g.tool), ...(g.reason === undefined ? {} : { reason: clip(g.reason) }), count: g.count, first: clip(g.first) }; +} + +/** + * The ways to show denied and failed calls, from most to least detailed: + * every call; groups by (tool, reason) with counts; the same groups with the + * reason and first summary cut to `GROUP_TEXT_CHARS`. `dropped(k)` keeps the + * first `k` clipped groups of each list and a marker with how many reasons + * and calls are left out. + */ +function failedViews(calls: CompactCalls, more: string): { readonly forms: Record[]; readonly dropped: (k: number, byTool: boolean) => Record; readonly groups: number } { + const denied = calls.denied ? groupFailed(calls.denied) : undefined; + const errors = calls.errors ? groupFailed(calls.errors) : undefined; + const clipped = (gs: FailedGroup[] | undefined): FailedGroup[] | undefined => gs?.map((g) => clipGroup(g, GROUP_TEXT_CHARS)); + const deniedClipped = clipped(denied); + const errorsClipped = clipped(errors); + const keepFirst = (gs: FailedGroup[] | undefined, k: number): unknown[] | undefined => { + if (gs === undefined || gs.length <= k) return gs; + const left = gs.slice(k); + const n = left.reduce((a, g) => a + g.count, 0); + return [...gs.slice(0, k), `…[${left.length} more reason${left.length === 1 ? '' : 's'} (${n} call${n === 1 ? '' : 's'})${more}]`]; + }; + return { + forms: [withFailed(calls, calls.denied, calls.errors), withFailed(calls, denied, errors), withFailed(calls, deniedClipped, errorsClipped)], + dropped: (k, byTool) => withFailed(calls, keepFirst(deniedClipped, k), keepFirst(errorsClipped, k), byTool), + groups: Math.max(denied?.length ?? 0, errors?.length ?? 0), + }; +} + +/** + * Clipped groups (see `failedViews`) of as many reasons per list as fit `max` + * characters with `rest`; `byTool` is left out only when not even the markers + * fit with it (thousands of distinct tool names). + */ +function fitGroups(views: ReturnType, rest: Record, key: string, max: number): Record { + const byTool = safeStringify({ ...rest, [key]: views.dropped(0, true) }).length <= max; + const fits = (k: number): boolean => safeStringify({ ...rest, [key]: views.dropped(k, byTool) }).length <= max; + let lo = 0; + let hi = views.groups; + while (lo < hi) { + const mid = Math.ceil((lo + hi) / 2); + if (fits(mid)) lo = mid; + else hi = mid - 1; } - return { content: [{ type: 'text', text: truncateStructurally(result, cap, extra) }], isError }; + return { ...rest, [key]: views.dropped(lo, byTool) }; +} + +/** + * The response cut to `cap` characters: lists, then the result, logs and diff + * by start and end. Denied and failed calls are never cut by entry: when they + * do not fit whole they are grouped by (tool, reason) with exact counts, then + * each group's reason and first summary is cut to `GROUP_TEXT_CHARS`, and + * only then are groups left out, with a marker counting the reasons and calls + * left out. The other lists lose entries only when even the clipped groups do + * not fit. A verbose call log is a list like the others, so the compact calls + * go to `callSummary` next to it. + */ +function capped( + view: Record, + calls: CompactCalls, + 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 inOverflow = overflow ? ' in overflow' : ''; + const more = (n: number): string => `…[${n} more${inOverflow}]`; + const { result, logs, diff, ...rest } = view; + // The compact calls replace the view's unless the view has the verbose log (a list), which stays beside them. + const { calls: viewCalls, ...compactEnvelope } = rest; + const envelope = Array.isArray(viewCalls) ? rest : compactEnvelope; + const key = Array.isArray(viewCalls) ? 'callSummary' : 'calls'; + const failed = failedViews(calls, inOverflow); + 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. Denied and failed calls are grouped before other lists + // lose entries, and other 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 | undefined; + for (let keep = 1_000; env === undefined && keep >= 1; keep = Math.floor(keep / 2)) { + const cut = { ...cutLists(envelope, keep, more), ...top }; + env = failed.forms.map((c) => ({ ...cut, [key]: c })).find((e) => safeStringify(e).length <= envMax); + } + env ??= fitGroups(failed, { ...clipObject(cutLists(envelope, 0, more), 300), ...top }, key, envMax); + 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; + } + return response(fitGroups(failed, { ok: view['ok'], ...top }, key, cap), 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 248d5cf..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'; @@ -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; @@ -159,7 +160,11 @@ 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', + description: 'Return the log of every call and the whole diff instead of the compact summary.', }, transaction: { type: 'boolean', diff --git a/src/core/types.ts b/src/core/types.ts index 0eb823f..ad6a0ec 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -130,13 +130,19 @@ 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`. */ 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 +154,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 +174,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 +185,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 +204,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; @@ -219,6 +225,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. // --------------------------------------------------------------------------- @@ -249,6 +278,51 @@ 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. */ +export interface BashGlob { + /** The word as written: literal text, quotes and glob characters only. */ + readonly raw: string; + /** Whether a match may be a directory (`ls`); otherwise only regular files. */ + readonly directories: boolean; } /** Effect of a `read` call. */ @@ -437,6 +511,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; } @@ -582,7 +663,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 +755,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/adapter.test.ts b/src/hosts/claude/adapter.test.ts index 2d03783..eae2e91 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,33 @@ 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'); + // 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 () => { const s = await setup({ user: { permissions: { deny: ['Read(./.env)', 'Edit(./locked/**)'] } }, mode: 'bypassPermissions' }); expect(check(s, bash('cat .env', s.project))).toBe('deny'); @@ -187,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 36c1dfd..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; } @@ -241,6 +249,35 @@ 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()'; + +/** + * 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; @@ -537,6 +574,7 @@ export class ClaudeHostAdapter implements HostAdapter { protectedPaths, additionalRoots: [...additionalRoots], readFilter: (realAbsPath: string): boolean => !isReadDenied(realAbsPath), + planBashExpansion: planGlobExpansion, payload: { projectRoot, cwd: ctx.cwd, @@ -558,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 }; @@ -569,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 => @@ -593,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('; ')})`); @@ -601,7 +663,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, 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..78f8a8c --- /dev/null +++ b/src/hosts/claude/bash.test.ts @@ -0,0 +1,164 @@ +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; + }; +} + +/** Pieces for tilde words: quotes (empty too), backslashes, assignment heads, `+=`, `:` and `~` in every position. */ +const TILDE_PIECES = [ + "''", '""', "'a'", '"a"', '\\a', '\\~', '\\=', '\\:', '\\+', '\\/', 'a', 'A_1', '_', '1', '=', '+=', '+', ':', '~', '/', 'x', '[1]', '[', ']', + "'~'", '"~"', "'='", '"="', "':'", '"/"', '~+', '-', 'a=', 'a+=', 'a=~', 'a+=~', ':~', '=~', +]; + +/** Random words built from `TILDE_PIECES`, plus every piece alone. */ +function tildeWords(count: number): string[] { + const r = rng(SEED + 1); + const words: string[] = [...TILDE_PIECES]; + for (let i = 0; i < count; i++) { + const n = 1 + Math.floor(r() * 5); + words.push(Array.from({ length: n }, () => TILDE_PIECES[Math.floor(r() * TILDE_PIECES.length)] ?? '').join('')); + } + return words; +} + +/** 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('expands `~` exactly where bash does: quotes, empty quotes, backslashes, `=`, `+=` and `:`', () => { + const words = tildeWords(3000); + const lines = words.map((w) => `X ${w}`); + const fromBash = bashWords(lines, dir); + let exact = 0; + let expanded = 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) continue; + const cmd = analysis.commands.find((c) => c.words[0]?.value === 'X'); + const got = fromBash[i]; + if (!cmd) 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++; + if (got?.some((w) => w.includes(HOME))) expanded++; + } + expect(exact).toBeGreaterThan(1500); + expect(expanded).toBeGreaterThan(40); + }); + + it('keeps `~` literal after empty quotes and expands it after `+=`', () => { + const values = (line: string): (string | undefined)[] | undefined => BashAnalyzer.analyze(line, { home: '/h' }).commands[0]?.words.map((w) => w.value); + expect(values("cat ''a=~/s \"\"~/s a=''~/s ~''/s a=x:''~/s a=~\"\"")).toEqual(['cat', 'a=~/s', '~/s', 'a=~/s', '~/s', 'a=x:~/s', 'a=~']); + expect(values('printf %s a+=~ a+=x:~/y _=~ ~:x')).toEqual(['printf', '%s', 'a+=/h', 'a+=x:/h/y', '_=/h', '/h:x']); + expect(BashAnalyzer.analyze('cat a[1]=~/s', { home: '/h' }).uncertain.length).toBeGreaterThan(0); + }); + + 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..46a8cc8 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,173 @@ 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. An empty `''` or `""` leaves a zero-width quoted marker (`c: ''`): + * it adds no text but still stops a tilde-prefix or an assignment name. + */ +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 => { + if (text === '' && quoted) chars.push({ c: '', quoted }); + 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; +} + +/** + * Where bash looks for a tilde-prefix in a word (bash `general.c` + * `assignment` and `subst.c` tilde handling, outside POSIX mode): + * - at the start of the word, when its first character is an unquoted `~` + * (an empty `''` or `""` in front makes it quoted); + * - in a word that is an assignment as written, `NAME=` or `NAME+=` with + * every character unquoted, right after that `=` and after each unquoted + * `:` of the value. `declare`, `export`, `local` and plain arguments follow + * the same rule. + * A subscripted assignment (`a[1]=~`) is reported as unknown: bash parses the + * subscript with its own rules. + */ +function tildeStarts(chars: readonly WordChar[]): { starts: number[]; assignment: boolean } | 'unknown' { + const starts: number[] = []; + if (chars[0]?.c === '~' && !chars[0].quoted) starts.push(0); + const unquoted = (i: number, test: (c: string) => boolean): boolean => { + const ch = chars[i]; + return ch !== undefined && !ch.quoted && test(ch.c); + }; + let i = 0; + if (!unquoted(0, (c) => /^[A-Za-z_]$/.test(c))) return { starts, assignment: false }; + while (unquoted(i + 1, (c) => /^[A-Za-z0-9_]$/.test(c))) i++; + i++; + if (unquoted(i, (c) => c === '[')) return chars.some((ch) => ch.c === '~') ? 'unknown' : { starts, assignment: false }; + if (unquoted(i, (c) => c === '+')) i++; + if (!unquoted(i, (c) => c === '=')) return { starts, assignment: false }; + for (let j = i; j < chars.length; j++) { + if ((j === i || unquoted(j, (c) => c === ':')) && unquoted(j + 1, (c) => c === '~')) starts.push(j + 1); + } + return { starts, assignment: true }; +} + +/** + * Applies bash's tilde expansion to a static word (see `tildeStarts`). Bash + * reads the tilde word up to the next unquoted `/` (in an assignment, also + * `:`); when any of its characters is quoted (`~''`, `~"x"`, `~:\x`) it stays + * as written. The user name inside it ends at a `:` (`~:x` is the home and + * `:x`). An empty name becomes `home`; any other (`~user`, `~+`, `~-`, `~1`) + * is reported as unknown. + */ +function expandTilde(chars: readonly WordChar[], home: string | undefined): { value: string } | { unknown: string } | undefined { + const found = tildeStarts(chars); + if (found === 'unknown') return { unknown: 'in a subscripted assignment' }; + if (found.starts.length === 0) return undefined; + let out = ''; + let from = 0; + for (const at of found.starts) { + let end = at + 1; + while (end < chars.length) { + const ch = chars[end]; + if (!ch || (!ch.quoted && (ch.c === '/' || (found.assignment && ch.c === ':')))) break; + end++; + } + const tildeWord = chars.slice(at + 1, end); + if (tildeWord.some((c) => c.quoted)) continue; // a quoted tilde word is not expanded + const colon = tildeWord.findIndex((c) => c.c === ':'); + const name = colon === -1 ? tildeWord : tildeWord.slice(0, colon); + if (name.length > 0) return { unknown: `~${name.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 +410,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 +434,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 +479,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 +501,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 +526,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 +583,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 +617,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 +659,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