Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat(bench): add reproducible with/without-ix agent evaluation (#855)

Tanner Kocherc1062f12264a
diff --git a/bench/agent-eval/.gitignore b/bench/agent-eval/.gitignore
new file mode 100644
index 00000000..e8b7af39
--- /dev/null
+++ b/bench/agent-eval/.gitignore
@@ -0,0 +1,3 @@
+local/
+results/
+results-test-*/
diff --git a/bench/agent-eval/README.md b/bench/agent-eval/README.md
new file mode 100644
index 00000000..4e3225b5
--- /dev/null
+++ b/bench/agent-eval/README.md
@@ -0,0 +1,104 @@
+# With/without-Ix agent evaluation
+
+This harness compares `baseline` and `ix` runs of the same agent, model, effort and budget. It records resolution, usage and time, and reports paired differences with bootstrap 90% confidence intervals. Run Claude Code and Codex as separate experiments.
+
+## Offline smoke and tests
+
+From the repository root, with Node 22+ on Linux or macOS:
+
+```sh
+node --test bench/agent-eval/test/eval.test.mjs
+node bench/agent-eval/run.mjs --dry-run --out bench/agent-eval/results/smoke
+```
+
+Use a fresh output directory each time. The dry run executes subprocess setup, probes, a stub agent, evaluation, metrics parsing and reporting for three tasks × two arms × two repeats (12 runs). It requires neither Docker nor a paid agent. The checked-in `smoke.json` contains **synthetic tasks and placeholder SHAs**; its reports are explicitly synthetic and cannot establish Ix effectiveness.
+
+The CLI test bridge runs portable manifest, telemetry and statistics tests on every platform in `npm test`, `test:unit` and `test:coverage`. POSIX orchestration/provisioning tests and the dry run are skipped on Windows; Linux/macOS retain that integration coverage. To exercise the portable subset alone, set `AGENT_EVAL_PORTABLE_ONLY=1` when invoking the Node test suite. The tests cover manifests, arm configuration/isolation, native telemetry fixtures, bootstrap bounds, committed solution patches, local provisioning and the smoke.
+
+## Pin a real task set
+
+**No real SWE-bench Verified manifest ships with this repository, and none was generated or checked during development.** Obtain an official `princeton-nlp/SWE-bench_Verified` test-split JSON array or JSONL export locally. Save a JSON array at `bench/agent-eval/local/verified.json`; save JSONL as `verified.jsonl` and use that name below and in `dataset_export`. The official evaluator picks its parser by file extension, so the importer and runner reject a mismatched name before any agent runs. Keep the upstream dataset revision and license information alongside it. Do not redistribute exports or task patches without checking upstream and repository licenses. The importer validates content but cannot authenticate provenance.
+
+```sh
+mkdir -p bench/agent-eval/local
+# After placing your official export at local/verified.json:
+node bench/agent-eval/manifest.mjs bench/agent-eval/local/verified.json bench/agent-eval/local/manifest-50.json
+# A smaller real experiment: task count, minimum repo count, seed
+node bench/agent-eval/manifest.mjs bench/agent-eval/local/verified.json bench/agent-eval/local/manifest-3.json 3 3 20261013
+```
+
+The default selects 50 tasks across at least five repos, using stable SHA-256 ranking by seed and task id. The generated manifest pins every task id, repo and base SHA, and the complete export hash. Preserve this manifest for reproduction. The runner checks each task against the hash-verified export. Gold/test patches are omitted from the manifest and native agent prompt.
+
+SWE-PolyBench is not enabled; adding it requires license review and its official evaluator.
+
+## Local real-run setup
+
+Use a reachable Docker daemon, a pinned local official SWE-bench checkout, cached public task repos, a local Ix backend and the installed native agent. Docker image downloads and real agent usage may incur costs; there is no hosted benchmark dependency. Supply authentication through the native CLI's supported environment, never through benchmark JSON. Existing home-directory login caches are deliberately not copied. The harness does not provide a sandbox against a malicious solver accessing other host files; use a disposable machine with no unrelated data.
+
+1. Obtain the official SWE-bench source locally at a chosen full commit SHA. Keep its tracked files clean and install its dependencies:
+
+ ```sh
+ python3 -m venv bench/agent-eval/local/venv
+ bench/agent-eval/local/venv/bin/python -m pip install -e bench/agent-eval/local/SWE-bench
+ git -C bench/agent-eval/local/SWE-bench rev-parse HEAD
+ ```
+
+ Set `evaluator.revision` to that SHA and retain dependency versions and Docker image digests with the experiment. The evaluator verifies HEAD/cleanliness and imports from that checkout. Evaluation uses the saved official export, one worker and a separate deadline.
+
+2. Cache a bare clone of each selected repo as `local/repos/OWNER__NAME.git`. Each cache must contain the manifest's base commits. For each locally obtained public task checkout:
+
+ ```sh
+ mkdir -p bench/agent-eval/local/repos
+ git clone --bare /path/to/public-task-checkout bench/agent-eval/local/repos/OWNER__NAME.git
+ ```
+
+ The runner only clones from these caches, with detached pinned checkouts; it never fetches task repositories.
+
+3. Build Ix in this checkout and start a dedicated local backend using the repository's documented Docker setup. Keep the backend image digest fixed throughout the experiment and save it with the results. No backend reset is performed by this harness.
+
+ ```sh
+ npm --prefix ix-cli ci
+ npm --prefix ix-cli run build
+ node ix-cli/dist/cli/main.js --version
+ git rev-parse HEAD
+ ```
+
+4. Copy `bench/agent-eval/config.example.json` to `bench/agent-eval/local/config.json`. Fill in the native agent version, immutable model id, built Ix version, Ix source SHA and SWE-bench SHA. `environment.source_path` points to the Ix checkout; `ix_cli` points to its built CLI entrypoint; `plugin_revision` is its full HEAD SHA. Tracked CLI source and skills must match that SHA. Configure the reachable loopback `endpoint` (default example: `http://127.0.0.1:8090`). Config paths are relative to the invocation directory; run from the repository root. The example uses supplied setup/probe programs; no adapter implementation is needed.
+
+5. Run a small real experiment before scaling:
+
+ ```sh
+ node bench/agent-eval/run.mjs --manifest bench/agent-eval/local/manifest-3.json --config bench/agent-eval/local/config.json --out /path/to/isolated-eval-results/verified-3
+ # Use manifest-50.json and a fresh output directory for the full subset.
+ ```
+
+For Codex, set both `agent.family` and `agent.telemetry` to `codex`. For Claude Code, use `claude`. Keep the supplied `agent.command`. `agent.binary` can pin an absolute executable; otherwise it is resolved before isolation. `agent.args` supplies shared noninteractive permission options supported by your pinned version and must not override integrations. `claude --print` denies anything that would prompt. The example therefore passes `--permission-mode acceptEdits` in `agent.args` and lists shared tool rules (`Bash`) in `agent.allowed_tools`. The harness emits a single `--allowedTools` from that list and, for the ix arm only, adds the Ix MCP server rule (`mcp__plugin_ix-agent-eval_ix-memory`). `agent.args` cannot carry `--allowedTools` or any plugin/MCP/settings flag, and `agent.allowed_tools` cannot grant MCP tools. If Claude reports an Ix tool permission denial, the run fails instead of counting it as an Ix error. For Codex, `codex exec` needs an explicit `--sandbox` mode that can write the checkout (for example `workspace-write`). Check that sandboxed `ix` commands can still reach the loopback endpoint, and use the same args in both arms. Unsupported CLI flags fail the run. Config placeholders must be replaced; they are not model/version defaults.
+
+## Supplied arm provisioning
+
+Both arms receive fresh homes and Git/XDG/agent configuration directories. The runner constructs a private executable PATH for **every solver-side stage** (clone, setup, probe, agent and its hooks), excluding ambient `ix` launchers. The evaluator is identical for both arms and runs after the solver has exited, with the runner's own inherited environment (real `HOME` and `PATH`), so the SWE-bench Docker client sees the host's `~/.docker` configuration and contexts (rootless Docker, Docker Desktop). `environment.tool_paths` optionally pins the tool directories to copy into that PATH. Inherited Ix routing and parent sessions are removed. Claude Code's authentication and provider variables (`CLAUDE_CODE_OAUTH_TOKEN`, `CLAUDE_CODE_USE_BEDROCK`/`_VERTEX`/`_FOUNDRY` and their `SKIP_*_AUTH` and client-certificate settings) are kept, identically in both arms; other `CLAUDE_CODE_*` variables are removed. Other environment variables are inherited but never serialized. `IX_TOKEN` is removed with the other `IX_*` variables, and each run gets a fresh `IX_HOME` with no stored token. The harness does not forward credentials, so the configured loopback backend must accept unauthenticated local requests: do not start it with `ix docker start --local-token`. A token-protected backend fails setup at `ix map` before any agent runs. PATH isolation prevents ordinary direct Ix invocation; it is not an OS access boundary.
+
+The baseline has no Ix launcher, skills, MCP registration or hooks. The Ix arm gets an explicit launcher for the configured built CLI, the revision-pinned tracked `skills/ix` files, and the benchmark's local integration:
+
+- Claude Code: a local plugin loaded with `--plugin-dir`, containing the skill, Ix MCP registration and a PostToolUse hook for edits and Bash. The hook refreshes the map and runs `ix hook claude-post-edit` for dependent context. The product relies on editor plugins to re-ingest edits on a debounce. The benchmark has no editor plugin, so it refreshes synchronously, and only when the checkout changed since the last refresh: the hook compares a fingerprint of `git status`, `git diff HEAD` and the untracked files' sizes and modification times, so a read-only Bash call (`ls`, `cat`, a search) costs two Git calls rather than an `ix map`. Each hook record says whether it `mapped`. The hook's Claude timeout outlasts both ix deadlines. Hook time is part of `wall_seconds` and is also reported separately as `hook_seconds`.
+- Codex: the skill in the run's `$CODEX_HOME/skills/ix` (the location the product installer uses, `ix-cli/scripts/skill-harnesses.mjs`), an isolated `mcp_servers.ix-memory` configuration (with `IX_ENDPOINT` set in its `env` table, because Codex starts MCP servers with an allowlisted environment) and a native `notify` hook that refreshes the map after `agent-turn-complete`. Its integration receipt records these settings. `codex exec` receives one prompt, which is normally one turn, so this refresh runs once, after the agent finishes. Codex may exit while that hook is still running. So when the agent CLI exits, the harness stops the stage's process group, kills every remaining process except Ix hooks (a command line running `hook.mjs`) and their children, and waits only for those (up to the hook timeout, `2 × environment.seconds + 30`) before reaping the group. Both arms go through the same step; the baseline has no hooks, so all its leftovers die at once. Nothing the agent left running (a background build, test runner or server) can change the checkout after the agent exits, in either arm, and the hooks themselves only read the checkout. This needs `ps` (POSIX); without it the whole group is killed at exit; that wait is not part of `wall_seconds`, which (like the time budget) ends when the agent CLI exits, even if a hook still holds its output open, and the hook's own time is reported in `hook_seconds`. A hook still running when the group is reaped (outside an agent time-budget outcome) fails the run, because its telemetry would be incomplete. Within a Codex session, Ix answers do not reflect the agent's own edits. Mid-session refresh needs a per-tool hook in the pinned Codex version, which is not yet verified. Hook timing differs across agent families; compare arms within one family.
+
+The probe does not take the skill file's presence as proof that Codex loads it. It runs `codex debug prompt-input` (which renders the model-visible prompt locally, without a model call) in the arm's environment and requires the `ix` skill in its skill list. A pinned Codex without that subcommand, or one that does not list the skill, fails the probe.
+
+These are supplied benchmark integrations built from this repository, rather than installations from a marketplace or separate plugin repository. Preserve the harness checkout as well as the Ix source pin. Each run's solver-facing files (task checkout, home, integrations, hook telemetry) live in a fresh work directory under `work_root` (optional config field; default: the system temporary directory), not in the output directory. The solver's request names only that work directory; it carries no dataset export path (the gold patches), no evaluator settings and no output path. Only the evaluator, which runs after the solver exits, receives `evaluate-request.json` with the export. After a run is recorded, its `request.json`, `hooks.jsonl` and map receipts are copied into the run's output directory (`agent-request.json`, …) and the work directory is removed, so a later solver cannot browse earlier runs' patches or reports. A failed run keeps its work directory (named in `failure.json`) for inspection; the failure ends the experiment. Real runs reject an output directory inside `work_root`. Put `work_root` outside project ancestry containing agent instructions/configuration (including this Ix checkout); the provisioner rejects those ancestors and names the offending path. Home directories count too: a home holding `~/.claude`, `~/.codex` or `~/.agents` rejects every work directory beneath it, so if your temporary directory is under such a home, set `work_root` to a location outside it (for example a dedicated data volume). For Codex, prefer a `work_root` outside the system temporary directory too: codex-cli 0.162.1 warns that it will not create its helper PATH aliases when its home is under a temporary directory. The provisioner also rejects ambient task `AGENTS.md`, `CLAUDE.md`, `.claude`, `.codex`, `.agents` and `.mcp.json` configurations rather than editing task files. Choose compatible tasks or deliberately implement and document a custom isolation policy.
+
+The probe verifies native CLI versions, pinned skill/config content, HEAD, executable availability and an exercised hook. Because isolation is only a PATH, it also asks a login shell (`bash -l`, plus `$SHELL` when it is bash or zsh, the shells Claude Code runs; Codex runs commands through `bash -lc`) where `ix` is: a profile that resets PATH (Debian's `/etc/profile`, macOS `path_helper`) and so hides the ix arm's launcher or exposes a global `ix` to the baseline fails the run. So does a profile that exits non-zero under the arm's PATH; the error quotes the shell's stderr. It queries live `ix status` and `ix stats`; stale, incomplete, empty or unhealthy maps invalidate the run. Ix runs that produce nonempty patches must also have hook execution receipts. Version-specific native activation is still a real-run check: unit fixtures do not prove a particular installed CLI supports its plugin/notify flags.
+
+Every stage receives one final absolute request-file argument. Custom setup/probe/agent/evaluator adapters remain possible through argv-array configs. Probe receipts contain version, repo/base/agent identity, `ix_available`, `mapped`, `plugin_installed`, `skills_installed`, `hooks_enabled`, and, for Ix, `mapped_commit`, `plugin_revision` and SHA-256 file evidence. The runner validates these fields and requires evidence inside the run directory. Evaluation receipts must agree with the official task report, whose saved bytes are hashed. Empty patches require the official harness's empty-patch evidence.
+
+## Measurements and interpretation
+
+Artifacts include `harness.json` (script hashes), `manifest.json`, `config.json`, `schedule.json`, per-run `agent-request.json`/`evaluate-request.json`, per-stage logs, binary solution patches, official report evidence, `runs.jsonl`, `report.json` and `summary.md`. Patches compare against the task's pinned base, including agent commits and newly created files; integration files are excluded. Runs are sequential, with seed-randomized task/arm order and two repeats by default.
+
+Native JSONL and normalized adapter telemetry record input/output/cached tokens, turns, tool calls, search counts, Ix calls and Ix errors by code. Claude input includes cache reads and cache creation; cached tokens are the cache-read subset. Claude `turns` counts only the main agent's assistant messages; messages from a subagent (Task/Explore: `parent_tool_use_id` set, or `isSidechain`) are not turns, matching what `--max-turns` limits, though their tool calls still count. Codex usage sums completed turns. Message/tool ids are deduplicated. Missing usage or terminal events invalidate a normally completed transcript. Budget deadlines may leave partial transcripts: observed tool/turn counters are retained, missing total token usage is `null`, and partial usage is saved separately as `observed_usage`. A final interrupted JSONL write is discarded only for a budget-limited agent stage. `search_calls` is shell searches (`rg_calls`, `grep_calls`, `find_calls`) plus Claude Code's built-in `Grep`/`Glob` tool calls, which are also reported as `native_search_calls` (Codex has no built-in search tool, so it is 0 there). Search/Ix shell counts cover direct commands and `sh`/`bash`/`zsh -c` wrappers with quote-aware tokenization, including ANSI-C `$'...'` quotes. An unbalanced quote never stops a run; the command is counted from what was parsed. Heredoc bodies are file content, not commands, so they are never counted (command substitutions inside an unquoted heredoc are missed too). Dynamic expansions, aliases and commands hidden inside scripts require normalized tool telemetry; counts are observed invocations, not a full shell execution trace. Hook Ix calls/errors are reported as `hook_ix_calls`/`hook_ix_errors`, excluding setup/probe calls; `ix_calls`/`ix_errors` count only the agent's own Ix use. An Ix call fails when its output shows an Ix error code or a shell "ix: not found" message, so `ix … 2>&1 | head` and `ix … || rg …` failures are not hidden by a zero exit status. A nonzero exit (or Claude tool error) counts as an Ix failure only when the whole command is one `ix` invocation (optionally inside `bash -c`); a failing `ix map && npm test` is an Ix failure only if its output shows one. In the baseline, a failed `ix` attempt (the probe proved there is no launcher) is recorded as an Ix call and error, and the run continues. A baseline Ix call that certainly succeeded is an isolation leak and stops the experiment: an Ix MCP call without an error, or a command that exited 0 and is a lone `ix` call or an `&&` chain containing one. Commands whose status does not prove `ix` ran (`ix --version || echo no ix`, `rg foo || ix text foo`, `ix … | head`, `…; ix …`) never count as a leak. Claude permission denials are counted per run as `permission_denials`.
+
+The common budget sets agent wall time and post-run turn/token ceilings; budget exhaustion records a run outcome and continues the remaining schedule. Agent deadlines terminate the process group, preserve logs and the current patch, and still evaluate that patch. Native Claude `error_max_turns` receipts are retained even when the CLI exits nonzero. Ordinary crashes and invalid setup/probe/evaluation stages remain fatal. The official harness writes no task report when a patch fails to apply or its tests time out. It lists those instances in the run summary's `error_ids`, and so does the scorer. When `run_instance.log` names either cause, the run is scored unresolved (`report_kind: error-summary`, `evaluation_error`). Any other evaluator error, such as an image build or Docker failure, stays fatal. Claude also receives `--max-turns`. Codex receives no native turn limit, and its `turns` metric counts `codex exec` turns (normally one per run), not model requests; for Codex, `max_turns` and `turn_budget` are effectively inert, so rely on the time and token ceilings and do not compare `turns` across agent families. Turn/token ceilings are checked against observed usage after execution. The token ceiling counts uncached input plus output: cache reads are excluded, because a long session re-reads its cached context every turn; overshoots are conservatively `resolved: 0` because the final patch may include work beyond the declared limit. The official test verdict is retained as `official_resolved`. Time-limited or native turn-limited patches produced within the ceiling retain their official verdict. Each result has a `termination` reason (`completed`, `time_budget`, `turn_budget`, or `token_budget`). These are resource ceilings, not guaranteed billing caps. No retries occur. There is no resume: a fatal run error stops the experiment without `report.json`/`summary.md`; completed runs remain in `runs.jsonl` and the failing run's `failure.json`, and a rerun needs a fresh output directory. Clone, checkout, setup and probe each have an `environment.seconds` deadline; Git checks/patch extraction add bounded 10-second stages. Evaluation has its own deadline, including Docker image builds. Only agent-stage deadlines are retained as outcomes; setup, mapping and evaluation deadlines still fail the experiment. POSIX process groups are terminated at deadlines and reaped after stage completion. Windows isolation is not supported.
+
+Reports include per-arm means/medians, mean and median differences with **paired task-cluster percentile bootstrap 90% CIs** (10,000 samples in the real config), and per-task descriptive rows for every metric. Repeats stay together when resampling tasks. Missing arms, unequal repeats and duplicate runs are errors. Resolution is a fraction; differences are Ix minus baseline. All scheduled runs remain in the resolution denominator, including budget-limited runs. For metrics with missing totals, per-arm summaries and CIs use only complete paired tasks; reports show paired-task coverage and observed-run counts. If no paired usage is available, usage estimates/CIs are explicitly unavailable. This conditional usage comparison may be biased by missingness and is not evidence of a cost advantage among timed-out tasks. `wall_seconds` is agent execution time, including synchronous hooks; setup/evaluation/total times are also recorded. Small sets can have degenerate intervals and cannot establish effectiveness. Real-task resolve rates remain unverified until a real run completes.
+
+Reproduce from the same saved manifest/export, config, tool versions, Ix/harness commits, backend/image digests and agent model. Remote aliases can drift. CIs quantify task sampling uncertainty, not model drift, environment bias or billing prices. Review logs before publication. Local input data and results are gitignored.
diff --git a/bench/agent-eval/agent.mjs b/bench/agent-eval/agent.mjs
new file mode 100644
index 00000000..289ce6f6
--- /dev/null
+++ b/bench/agent-eval/agent.mjs
@@ -0,0 +1,21 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { spawn } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { execute } from './process.mjs';
+import { nativeArgs } from './integration.mjs';
+
+// Native CLI adapter. CLI/plugin versions must be pinned and independently probed.
+const request = JSON.parse(readFileSync(process.argv[2], 'utf8'));
+const { agent, task } = request;
+if (!['claude', 'codex'].includes(agent.family)) throw new Error('Unsupported native agent');
+const binary = agent.binary ?? agent.family;
+const version = await execute([binary, '--version'], { seconds: 10 });
+if (!version.stdout.trim().split(/\s+/).includes(agent.version)) throw new Error('Installed agent version differs from pinned version');
+const args = nativeArgs(request);
+// The problem statement is the only dataset text exposed to the solver.
+const child = spawn(binary, args, { stdio: ['pipe', 'inherit', 'inherit'] });
+child.stdin.on('error', () => {});
+child.stdin.end(task.problem_statement + '\n');
+child.on('error', () => { console.error('Unable to start native agent'); process.exitCode = 1; });
+child.on('close', (code) => { process.exitCode = code ?? 1; });
diff --git a/bench/agent-eval/config.example.json b/bench/agent-eval/config.example.json
new file mode 100644
index 00000000..fce8c601
--- /dev/null
+++ b/bench/agent-eval/config.example.json
@@ -0,0 +1,38 @@
+{
+ "version": 1,
+ "repeats": 2,
+ "seed": 20261013,
+ "bootstrap_samples": 10000,
+ "dataset_export": "bench/agent-eval/local/verified.json",
+ "repo_cache": "bench/agent-eval/local/repos",
+ "agent": {
+ "family": "claude",
+ "version": "REPLACE_WITH_INSTALLED_VERSION",
+ "model": "REPLACE_WITH_EXACT_MODEL_ID",
+ "effort": "medium",
+ "telemetry": "claude",
+ "command": ["node", "bench/agent-eval/agent.mjs"],
+ "args": ["--permission-mode", "acceptEdits"],
+ "allowed_tools": ["Bash"]
+ },
+ "budget": { "max_turns": 30, "max_tokens": 200000, "seconds": 1200 },
+ "environment": {
+ "plugin_revision": "REPLACE_WITH_40_HEX_IX_SOURCE_COMMIT",
+ "seconds": 600,
+ "source_path": ".",
+ "ix_cli": "ix-cli/dist/cli/main.js",
+ "ix_version": "REPLACE_WITH_BUILT_IX_VERSION",
+ "endpoint": "http://127.0.0.1:8090",
+ "setup": ["node", "bench/agent-eval/provision.mjs", "setup"],
+ "probe": ["node", "bench/agent-eval/provision.mjs", "probe"]
+ },
+ "evaluator": {
+ "kind": "swe-bench",
+ "revision": "REPLACE_WITH_40_HEX_SWE_BENCH_COMMIT",
+ "harness_path": "bench/agent-eval/local/SWE-bench",
+ "python": "bench/agent-eval/local/venv/bin/python",
+ "test_seconds": 900,
+ "seconds": 1800,
+ "command": ["node", "bench/agent-eval/swebench.mjs"]
+ }
+}
diff --git a/bench/agent-eval/config.mjs b/bench/agent-eval/config.mjs
new file mode 100644
index 00000000..2cf8cce5
--- /dev/null
+++ b/bench/agent-eval/config.mjs
@@ -0,0 +1,63 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { positiveInteger } from './manifest.mjs';
+import { random, shuffled } from './stats.mjs';
+import { allowedTools, extraArgs } from './integration.mjs';
+
+export function command(value, name) {
+ if (!Array.isArray(value) || !value.length || value.some((v) => typeof v !== 'string' || !v.length)) throw new Error(`${name} must be a nonempty argv array`);
+ return value;
+}
+export function validateConfig(config, synthetic = false) {
+ if (config.version !== 1) throw new Error('Unsupported config version');
+ positiveInteger(config.repeats, 'repeats');
+ positiveInteger(config.bootstrap_samples, 'bootstrap_samples');
+ if (config.bootstrap_samples < 100 || !Number.isSafeInteger(config.seed)) throw new Error('Invalid bootstrap settings');
+ const agent = config.agent;
+ if (!agent || !['claude', 'codex', ...(synthetic ? ['stub'] : [])].includes(agent.family)) throw new Error('Invalid agent family');
+ for (const field of ['model', 'effort', 'version']) if (typeof agent[field] !== 'string' || !agent[field].trim()) throw new Error(`Missing agent.${field}`);
+ command(agent.command, 'agent.command');
+ extraArgs(agent); allowedTools(agent);
+ if (!['normalized', 'claude', 'codex'].includes(agent.telemetry)) throw new Error('Invalid telemetry format');
+ for (const key of ['max_turns', 'max_tokens', 'seconds']) positiveInteger(config.budget?.[key], `budget.${key}`);
+ for (const stage of ['setup', 'probe']) command(config.environment?.[stage], `environment.${stage}`);
+ positiveInteger(config.environment?.seconds, 'environment.seconds');
+ if (!synthetic && !/^[a-f0-9]{40}$/.test(config.environment?.plugin_revision ?? '')) throw new Error('Pin environment.plugin_revision to a commit SHA');
+ // Checked before paths are resolved, so `provision.mjs` with or without a directory counts.
+ const provisioned = config.environment.setup.some((arg) => /(^|[\\/])provision\.mjs$/.test(arg));
+ if (provisioned) for (const key of ['source_path', 'ix_cli', 'ix_version']) if (typeof config.environment[key] !== 'string' || !config.environment[key]) throw new Error(`Missing environment.${key}`);
+ // The ix arm's launcher exports IX_ENDPOINT whenever ix_cli is set, whichever setup runs.
+ if (provisioned || config.environment.ix_cli !== undefined || config.environment.endpoint !== undefined) {
+ let endpoint;
+ try { endpoint = new URL(config.environment.endpoint); } catch { throw new Error('Local provisioning requires a loopback Ix endpoint without credentials'); }
+ if (!['http:', 'https:'].includes(endpoint.protocol) || !['127.0.0.1', 'localhost', '[::1]'].includes(endpoint.hostname) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) throw new Error('Local provisioning requires a loopback Ix endpoint without credentials');
+ }
+ if (config.environment.tool_paths && (!Array.isArray(config.environment.tool_paths) || config.environment.tool_paths.some((path) => typeof path !== 'string' || !path))) throw new Error('tool_paths must be an array of directories');
+ positiveInteger(config.evaluator?.seconds, 'evaluator.seconds');
+ command(config.evaluator?.command, 'evaluator.command');
+ if (!synthetic && (config.evaluator.kind !== 'swe-bench' || !/^[a-f0-9]{40}$/.test(config.evaluator.revision ?? ''))) throw new Error('Real runs require a revision-pinned SWE-bench evaluator');
+ if (config.work_root !== undefined && (typeof config.work_root !== 'string' || !config.work_root)) throw new Error('work_root must be a directory path');
+ if (!synthetic && (typeof config.dataset_export !== 'string' || typeof config.repo_cache !== 'string')) throw new Error('Real runs require dataset_export and repo_cache');
+ return config;
+}
+
+export function schedule(tasks, repeats = 2, seed = 20261013) {
+ positiveInteger(repeats, 'repeats');
+ const rng = random(seed), jobs = [];
+ for (const task of shuffled(tasks, rng)) for (let repeat = 0; repeat < repeats; repeat++) {
+ for (const arm of shuffled(['baseline', 'ix'], rng)) jobs.push({ task, repeat, arm });
+ }
+ return jobs;
+}
+
+export function validateProbe(probe, request) {
+ if (probe.version !== 1 || probe.repo_path !== request.repo_path || probe.base_commit !== request.task.base_commit || probe.agent_version !== request.agent.version) throw new Error('Environment identity/version mismatch');
+ for (const key of ['ix_available', 'mapped', 'plugin_installed', 'skills_installed', 'hooks_enabled']) {
+ if (probe[key] !== (request.arm === 'ix')) throw new Error(`Invalid ${request.arm} environment: ${key}`);
+ }
+ if (request.arm === 'ix') {
+ if (probe.mapped_commit !== request.task.base_commit || probe.plugin_revision !== request.environment.plugin_revision) throw new Error('Stale map or plugin revision mismatch');
+ if (!Array.isArray(probe.evidence) || !probe.evidence.length) throw new Error('Plugin/skill/hook evidence required');
+ }
+ return probe;
+}
diff --git a/bench/agent-eval/evaluation.mjs b/bench/agent-eval/evaluation.mjs
new file mode 100644
index 00000000..53bb9674
--- /dev/null
+++ b/bench/agent-eval/evaluation.mjs
@@ -0,0 +1,22 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+/** Instance-log markers for evaluation errors the official run report scores as unresolved.
+ * Any other error (image build, Docker, harness crash) stays fatal.
+ */
+export const EVALUATION_ERRORS = { patch_apply_failed: '>>>>> Patch Apply Failed', test_timeout: 'Test timed out' };
+
+export function evaluationError(log) {
+ for (const [reason, marker] of Object.entries(EVALUATION_ERRORS)) if (log.includes(marker)) return reason;
+ throw new Error('Official evaluation errored without a patch-apply or test-timeout marker; inspect the harness logs');
+}
+
+/** Check official task reports or the harness's explicit empty-patch/error summary. */
+export function checkResolution(report, receipt, instanceId, patch) {
+ if (receipt.report_kind === 'empty-patch-summary') {
+ if (patch !== '' || receipt.resolved !== false || !Array.isArray(report.empty_patch_ids) || !report.empty_patch_ids.includes(instanceId)) throw new Error('Invalid official empty-patch evidence');
+ } else if (receipt.report_kind === 'error-summary') {
+ if (patch === '' || receipt.resolved !== false || !Object.hasOwn(EVALUATION_ERRORS, receipt.evaluation_error ?? '') || !Array.isArray(report.error_ids) || !report.error_ids.includes(instanceId)) throw new Error('Invalid official evaluation-error evidence');
+ } else if (report[instanceId]?.resolved !== receipt.resolved) {
+ throw new Error('Resolution differs from official report');
+ }
+}
diff --git a/bench/agent-eval/hook.mjs b/bench/agent-eval/hook.mjs
new file mode 100644
index 00000000..937f4d1d
--- /dev/null
+++ b/bench/agent-eval/hook.mjs
@@ -0,0 +1,54 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { execute } from './process.mjs';
+import { sha256 } from './manifest.mjs';
+import { MAP_STATE, PENDING } from './integration.mjs';
+
+/** Fingerprint of the checkout's changes: tracked content via the diff, untracked files by size and mtime. */
+async function treeState(cwd, seconds) {
+ const git = async (...args) => (await execute(['git', '--no-optional-locks', ...args], { cwd, seconds })).stdout;
+ const status = await git('status', '--porcelain=v1', '-z', '--untracked-files=all');
+ const untracked = status.split('\0').filter((entry) => entry.startsWith('?? ')).map((entry) => {
+ const stat = statSync(join(cwd, entry.slice(3)), { throwIfNoEntry: false });
+ return `${entry}\0${stat?.size}\0${stat?.mtimeMs}`;
+ });
+ return sha256([status, await git('diff', '--binary', 'HEAD'), ...untracked].join('\0'));
+}
+
+// Claude: PostToolUse. Codex: native notify on agent-turn-complete.
+const request = JSON.parse(readFileSync(process.env.AGENT_EVAL_REQUEST, 'utf8'));
+if (request.arm !== 'ix') throw new Error('Ix hook activated in baseline');
+let calls = 0, mapped = false; const started = performance.now();
+const pending = join(request.run_path, PENDING, String(process.pid));
+try {
+ const mode = process.argv[2];
+ if (mode === 'codex' && JSON.parse(process.argv[3] ?? '{}').type !== 'agent-turn-complete') process.exit(0);
+ // A marker that outlives the hook means it was killed mid-run; run.mjs then refuses the run's hook telemetry.
+ mkdirSync(join(request.run_path, PENDING), { recursive: true });
+ writeFileSync(pending, `${mode}\n`);
+ // Like the product's change-triggered refresh, re-map only when the checkout changed since the last map
+ // (a read-only Bash call costs two git calls, not a map). The probe always maps: it exercises the hook.
+ const state = join(request.run_path, MAP_STATE), { repo_path: cwd, environment: { seconds } } = request;
+ const before = await treeState(cwd, seconds);
+ mapped = mode === 'probe' || !existsSync(state) || readFileSync(state, 'utf8') !== before;
+ if (mapped) {
+ calls++;
+ await execute(['ix', 'map', '--silent'], { cwd, seconds });
+ // Taken after the map, so files the map itself writes do not trigger the next one.
+ writeFileSync(state, await treeState(cwd, seconds));
+ }
+ if (mode === 'claude') {
+ let input = ''; for await (const chunk of process.stdin) input += chunk;
+ calls++;
+ const result = await execute(['ix', 'hook', 'claude-post-edit'], { cwd: request.repo_path, seconds: request.environment.seconds, input });
+ process.stdout.write(result.stdout);
+ }
+ appendFileSync(join(request.run_path, 'hooks.jsonl'), JSON.stringify({ type: 'hook', mode, mapped, ix_calls: calls, seconds: (performance.now() - started) / 1000 }) + '\n');
+} catch {
+ appendFileSync(join(request.run_path, 'hooks.jsonl'), JSON.stringify({ type: 'ix_error', code: 'HOOK_FAILED', mapped, ix_calls: calls, seconds: (performance.now() - started) / 1000 }) + '\n');
+ process.exitCode = 1;
+} finally {
+ rmSync(pending, { force: true });
+}
diff --git a/bench/agent-eval/integration.mjs b/bench/agent-eval/integration.mjs
new file mode 100644
index 00000000..ba2cfa3e
--- /dev/null
+++ b/bench/agent-eval/integration.mjs
@@ -0,0 +1,56 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// Names shared by provisioning, the native agent argv and telemetry.
+export const PLUGIN_NAME = 'ix-agent-eval';
+export const MCP_SERVER = 'ix-memory';
+// Claude names plugin MCP tools `mcp__plugin_<plugin>_<server>__<tool>`; a server-level rule allows all of them.
+export const CLAUDE_IX_MCP_RULE = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER}`;
+// Map refresh and claude-post-edit each have an environment.seconds deadline; the hook must outlast both.
+// Directory (under the run path) of markers for Ix hooks that have started but not finished.
+export const PENDING = 'hooks.pending';
+// File (under the run path) holding the checkout fingerprint the last hook map refresh saw.
+export const MAP_STATE = 'hooks.map-state';
+export const hookTimeoutSeconds = (environment) => 2 * environment.seconds + 30;
+// The script both agents' Ix hooks run (Claude PostToolUse, Codex notify), as `node <HOOK_SCRIPT> <mode>`.
+export const HOOK_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), 'hook.mjs');
+/** A command line (`ps` args) that runs the hook script. When the agent exits, only these and their children may
+ * keep running; they read the checkout but never write it. A shell wrapping the hook does not match, which is fine:
+ * the hook it started keeps running without it.
+ */
+export const isHookProcess = (args) => args === HOOK_SCRIPT || args.includes(` ${HOOK_SCRIPT} `) || args.endsWith(` ${HOOK_SCRIPT}`);
+
+// Arm integrations (plugins, MCP, settings, hooks, tool permissions) belong to the harness, never to shared args.
+const OVERRIDES = /plugin|mcp|settings|notify|allowed-?tools|CODEX_HOME|CLAUDE_CONFIG_DIR/i;
+
+export function extraArgs(agent) {
+ const extra = agent.args ?? [];
+ if (!Array.isArray(extra) || extra.some((v) => typeof v !== 'string')) throw new Error('agent.args must be an argv array');
+ if (extra.some((arg) => OVERRIDES.test(arg))) throw new Error('agent.args must not override arm integrations; use agent.allowed_tools for shared tool permissions');
+ return extra;
+}
+
+/** Shared Claude tool rules; the harness adds the Ix MCP rule for the ix arm only. */
+export function allowedTools(agent) {
+ const tools = agent.allowed_tools ?? [];
+ if (!Array.isArray(tools) || tools.some((v) => typeof v !== 'string' || !v.trim() || v.includes(','))) throw new Error('agent.allowed_tools must be an array of tool rules without commas');
+ if (tools.length && agent.family !== 'claude') throw new Error('agent.allowed_tools is supported for Claude Code only');
+ if (tools.some((tool) => /mcp|plugin/i.test(tool))) throw new Error('agent.allowed_tools must not grant MCP tools; the ix arm integration does');
+ return tools;
+}
+
+export function nativeArgs(request) {
+ const { agent, budget } = request, extra = extraArgs(agent);
+ if (agent.family === 'codex') {
+ allowedTools(agent);
+ return ['exec', '--json', '--model', agent.model, '-c', `model_reasoning_effort=${JSON.stringify(agent.effort)}`, ...extra, '-'];
+ }
+ if (agent.family !== 'claude') throw new Error('Unsupported native agent');
+ const ix = request.arm === 'ix';
+ const tools = [...allowedTools(agent), ...(ix ? [CLAUDE_IX_MCP_RULE] : [])];
+ const integration = ['--setting-sources', '', ...(ix ? ['--plugin-dir', join(request.run_path, 'plugin')] : ['--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}'])];
+ return ['--print', '--verbose', '--output-format', 'stream-json', '--model', agent.model, '--effort', agent.effort, '--max-turns', String(budget.max_turns),
+ ...integration, ...(tools.length ? ['--allowedTools', tools.join(',')] : []), ...extra];
+}
diff --git a/bench/agent-eval/isolation.mjs b/bench/agent-eval/isolation.mjs
new file mode 100644
index 00000000..bc8832a0
--- /dev/null
+++ b/bench/agent-eval/isolation.mjs
@@ -0,0 +1,46 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { accessSync, constants, existsSync, mkdirSync, readdirSync, realpathSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
+import { delimiter, join, resolve } from 'node:path';
+
+export function findBinary(binary, searchPath = process.env.PATH) {
+ const candidates = binary.includes('/') ? [resolve(binary)] : searchPath.split(delimiter).map((dir) => join(dir, binary));
+ for (const file of candidates) {
+ try { accessSync(file, constants.X_OK); return realpathSync(file); } catch { /* next directory */ }
+ }
+ throw new Error(`Executable unavailable: ${binary}`);
+}
+
+// Claude Code authentication and provider routing; identical in both arms. Other CLAUDE_CODE_* (parent session, IDE) is dropped.
+const CLAUDE_AUTH = /^CLAUDE_CODE_(?:OAUTH_TOKEN|USE_(?:BEDROCK|VERTEX|FOUNDRY)|SKIP_(?:BEDROCK|VERTEX|FOUNDRY)_AUTH|CLIENT_(?:CERT|KEY|KEY_PASSPHRASE))$/;
+
+/** A private executable directory, rather than a setup process attempting to export PATH. */
+export function armEnvironment(request, inherited = process.env) {
+ if (process.platform === 'win32') throw new Error('Arm isolation currently requires POSIX; use Linux for SWE-bench');
+ const { home, run_path, arm, environment } = request;
+ const bin = join(run_path, 'bin'); mkdirSync(bin);
+ const seen = new Set();
+ for (const dir of environment.tool_paths ?? inherited.PATH.split(delimiter)) {
+ if (!existsSync(dir)) continue;
+ for (const name of readdirSync(dir)) {
+ if (name === 'ix' || name.startsWith('ix.') || seen.has(name)) continue;
+ const file = join(dir, name);
+ try { if (!statSync(file).isFile()) continue; accessSync(file, constants.X_OK); symlinkSync(resolve(file), join(bin, name)); seen.add(name); } catch { /* non-executable or duplicate */ }
+ }
+ }
+ // The native adapter and hooks use this exact Node executable in both arms.
+ if (!seen.has('node')) symlinkSync(process.execPath, join(bin, 'node'));
+ const env = { ...inherited, PATH: bin, HOME: home, USERPROFILE: home, CODEX_HOME: join(home, '.codex'),
+ CLAUDE_CONFIG_DIR: join(home, '.claude'), IX_HOME: join(home, '.ix'), XDG_CONFIG_HOME: join(home, '.config'),
+ XDG_CACHE_HOME: join(home, '.cache'), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(home, '.gitconfig'),
+ AGENT_EVAL_REQUEST: join(run_path, 'request.json') };
+ for (const key of Object.keys(env)) if (/^(IX_|JARVIS_IX_|CLAUDE_CODE_|CLAUDE_PROJECT_|CODEX_THREAD_)/.test(key) && key !== 'IX_HOME' && !CLAUDE_AUTH.test(key)) delete env[key];
+ if (arm === 'ix' && environment.ix_cli) {
+ env.IX_ENDPOINT = environment.endpoint;
+ const launcher = `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(environment.ix_cli)} "$@"\n`;
+ writeFileSync(join(bin, 'ix'), launcher, { mode: 0o755 });
+ }
+ return env;
+}
+
+export const shellQuote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
diff --git a/bench/agent-eval/manifest.mjs b/bench/agent-eval/manifest.mjs
new file mode 100644
index 00000000..72cd8450
--- /dev/null
+++ b/bench/agent-eval/manifest.mjs
@@ -0,0 +1,75 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { extname, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+export const sha256 = (text) => createHash('sha256').update(text).digest('hex');
+export function positiveInteger(value, name) {
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
+ return value;
+}
+export function validateManifest(manifest) {
+ if (manifest.version !== 1 || !['swe-bench-verified', 'synthetic'].includes(manifest.dataset)) {
+ throw new Error('Unsupported manifest version or dataset');
+ }
+ if (!Array.isArray(manifest.tasks) || !manifest.tasks.length) throw new Error('Empty task set');
+ const ids = new Set();
+ for (const task of manifest.tasks) {
+ if (!task || typeof task.instance_id !== 'string' || !/^[\w.-]+$/.test(task.instance_id) || ['.', '..'].includes(task.instance_id) || ids.has(task.instance_id)) throw new Error('Invalid or duplicate instance_id');
+ if (typeof task.repo !== 'string' || !/^[\w.-]+\/[\w.-]+$/.test(task.repo) || task.repo.split('/').some((p) => ['.', '..'].includes(p)) || typeof task.base_commit !== 'string' || !/^[a-f0-9]{40}$/.test(task.base_commit)) {
+ throw new Error(`Invalid repo or base_commit: ${task.instance_id}`);
+ }
+ if (typeof task.problem_statement !== 'string' || !task.problem_statement.trim()) throw new Error('Missing problem_statement');
+ ids.add(task.instance_id);
+ }
+ if (manifest.dataset !== 'synthetic' && !/^[a-f0-9]{64}$/.test(manifest.source_sha256 ?? '')) throw new Error('Missing source_sha256');
+ return manifest;
+}
+export const loadManifest = (file) => validateManifest(JSON.parse(readFileSync(file, 'utf8')));
+
+/** SWE-bench's loader picks its parser by file extension, so a named export must match its format. */
+export function parseExport(text, path) {
+ let rows, format = 'json';
+ try { rows = JSON.parse(text); } catch { rows = text.trim().split(/\r?\n/).map((line) => JSON.parse(line)); format = 'jsonl'; }
+ if (!Array.isArray(rows)) throw new Error('Export must be a JSON array or JSONL');
+ if (path && extname(path) !== `.${format}`) throw new Error(`A ${format === 'json' ? 'JSON array' : 'JSONL'} export must be named *.${format}; the official evaluator picks its parser by extension`);
+ return rows;
+}
+
+export function checkManifestSource(manifest, text, path) {
+ if (sha256(text) !== manifest.source_sha256) throw new Error('Dataset export hash mismatch');
+ const rows = parseExport(text, path);
+ const byId = new Map(rows.map((row) => [row.instance_id, row]));
+ if (byId.size !== rows.length) throw new Error('Duplicate source task ids');
+ for (const task of manifest.tasks) {
+ const row = byId.get(task.instance_id);
+ if (!row || ['repo', 'base_commit', 'problem_statement'].some((field) => row[field] !== task[field])) throw new Error(`Manifest task differs from source export: ${task.instance_id}`);
+ }
+}
+
+/** Stable hash ordering avoids dependence on export row order or JS sort/random versions. */
+export function importVerified(text, { count = 50, minRepos = 5, seed = 20261013, path } = {}) {
+ positiveInteger(count, 'count'); positiveInteger(minRepos, 'minRepos');
+ if (!Number.isSafeInteger(seed) || minRepos > count) throw new Error('Invalid seed or repository coverage');
+ const rows = parseExport(text, path);
+ const tasks = rows.map(({ instance_id, repo, base_commit, problem_statement }) => ({ instance_id, repo, base_commit, problem_statement }));
+ validateManifest({ version: 1, dataset: 'swe-bench-verified', source_sha256: sha256(text), tasks });
+ const ranked = tasks.sort((a, b) => sha256(`${seed}:${a.instance_id}`).localeCompare(sha256(`${seed}:${b.instance_id}`)));
+ if (ranked.length < count || new Set(ranked.map((task) => task.repo)).size < minRepos) throw new Error('Insufficient tasks or repositories');
+ const selected = [], repos = new Set();
+ for (const task of ranked) {
+ if (repos.size < minRepos && !repos.has(task.repo)) { selected.push(task); repos.add(task.repo); }
+ }
+ for (const task of ranked) if (selected.length < count && !selected.includes(task)) selected.push(task);
+ return validateManifest({ version: 1, dataset: 'swe-bench-verified', source_sha256: sha256(text), selection: { count, minRepos, seed }, tasks: selected });
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ try {
+ const [input, output, count = '50', minRepos = '5', seed = '20261013'] = process.argv.slice(2);
+ if (!input || !output) throw new Error('Usage: node manifest.mjs EXPORT.json|EXPORT.jsonl MANIFEST.json [count=50] [minRepos=5] [seed=20261013]');
+ writeFileSync(output, JSON.stringify(importVerified(readFileSync(input, 'utf8'), { count: Number(count), minRepos: Number(minRepos), seed: Number(seed), path: input }), null, 2) + '\n', { flag: 'wx' });
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
+}
diff --git a/bench/agent-eval/metrics.mjs b/bench/agent-eval/metrics.mjs
new file mode 100644
index 00000000..c0f39a0b
--- /dev/null
+++ b/bench/agent-eval/metrics.mjs
@@ -0,0 +1,256 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+export const METRICS = ['resolved', 'input_tokens', 'output_tokens', 'cached_tokens', 'turns', 'tool_calls', 'search_calls', 'rg_calls', 'grep_calls', 'find_calls', 'native_search_calls', 'ix_calls', 'ix_errors', 'hook_ix_calls', 'hook_ix_errors', 'wall_seconds', 'hook_seconds', 'setup_seconds', 'eval_seconds', 'total_wall_seconds'];
+const counter = (value, label) => {
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Missing or invalid ${label}`);
+ return value;
+};
+
+/** Token ceiling usage: uncached input plus output, comparable across Claude and Codex.
+ * Cache reads re-send context already counted and would otherwise dominate long sessions.
+ */
+export const budgetTokens = (usage) => usage.input_tokens - usage.cached_tokens + usage.output_tokens;
+
+/** Tokenize direct shell commands, preserving quoted separators as argument text.
+ * `separators[i]` holds the control operators between commands i and i + 1; `trailing` those after the last.
+ * Scripts, aliases and dynamic expansions require normalized tool telemetry.
+ * Never throws: an unbalanced quote keeps what was parsed, so one malformed agent command cannot stop a run.
+ */
+function shellCommands(text) {
+ const commands = [], separators = [], heredocs = []; let words = [], word = '', quote = '', active = false, operators = '';
+ const flush = () => { if (active) words.push(word); word = ''; active = false; };
+ const boundary = () => {
+ flush();
+ if (words.length) { if (commands.length) separators.push(operators); operators = ''; commands.push(words); }
+ words = [];
+ };
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i];
+ if (c === '\\' && quote !== "'") {
+ if (text[i + 1] !== '\n') { word += text[++i] ?? ''; active = true; } else i++;
+ } else if (quote) {
+ // ANSI-C `$'...'` closes on a single quote but, unlike '...', honours backslash escapes (above).
+ if (c === quote.at(-1)) quote = ''; else word += c;
+ } else if (c === '$' && text[i + 1] === "'") { quote = "$'"; active = true; i++; }
+ else if (c === "'" || c === '"') { quote = c; active = true; }
+ else if (c === '#' && !active) { while (i < text.length && text[i] !== '\n') i++; i--; }
+ else if (text.startsWith('<<<', i)) { flush(); i += 2; } // A here-string is a single word of input.
+ else if (text.startsWith('<<', i)) {
+ // Heredoc bodies are data (scripts, fixtures), never commands; skip them at the next newline.
+ flush(); i += 2;
+ const strip = text[i] === '-'; if (strip) i++;
+ while (text[i] === ' ' || text[i] === '\t') i++;
+ let delimiter = '';
+ for (; i < text.length && !/[\s;&|()<>]/.test(text[i]); i++) if (!`'"\\`.includes(text[i])) delimiter += text[i];
+ i--;
+ if (delimiter) heredocs.push({ delimiter, strip });
+ } else if (c === '\n' && heredocs.length) {
+ boundary(); operators += c;
+ for (const { delimiter, strip } of heredocs.splice(0)) {
+ let end = i;
+ do {
+ const start = end + 1; end = text.indexOf('\n', start); if (end < 0) end = text.length;
+ const line = text.slice(start, end);
+ if ((strip ? line.replace(/^\t+/, '') : line) === delimiter) break;
+ } while (end < text.length);
+ i = end;
+ }
+ }
+ // `>&`, `<&` and `&>` are redirections, not background/list operators.
+ else if (c === '&' && ('<>'.includes(text[i - 1]) || text[i + 1] === '>')) { word += c; active = true; }
+ else if (';&|\n'.includes(c)) { boundary(); operators += c; }
+ else if ('()'.includes(c)) boundary();
+ else if (/\s/.test(c)) flush();
+ else { word += c; active = true; }
+ }
+ boundary(); return { commands, separators, trailing: operators };
+}
+/** The program a command runs, and the script it hands to `sh`/`bash`/`zsh -c` (native Codex wraps commands in bash -lc). */
+function program(words) {
+ let i = 0;
+ if (words[i] === 'env') i++;
+ while (/^[A-Za-z_][\w]*=/.test(words[i] ?? '')) i++;
+ while (['command', 'exec'].includes(words[i])) i++;
+ const name = words[i]?.split('/').at(-1);
+ const script = ['sh', 'bash', 'zsh'].includes(name) && /^-[a-z]*c[a-z]*$/.test(words[i + 1] ?? '') ? words[i + 2] ?? '' : undefined;
+ return { name, script };
+}
+export function commandCounts(command) {
+ const counts = { search_calls: 0, rg_calls: 0, grep_calls: 0, find_calls: 0, ix_calls: 0 };
+ for (const words of shellCommands(command).commands) {
+ const { name, script } = program(words);
+ if (['rg', 'grep', 'find', 'ix'].includes(name)) {
+ counts[`${name}_calls`]++; if (name !== 'ix') counts.search_calls++;
+ }
+ if (script !== undefined) {
+ const nested = commandCounts(script);
+ for (const key of Object.keys(counts)) counts[key] += nested[key];
+ }
+ }
+ return counts;
+}
+
+/** What a command's exit status says about the `ix` calls in it.
+ * `sole`: the command is one `ix` invocation, so its failure is an Ix failure (`ix map && npm test` failing is not).
+ * `confirmed`: an `&&` chain containing `ix`, so its success means `ix` ran and succeeded
+ * (`ix … || echo`, `ix … | head`, `ix …; echo` and `ix … &` succeed even when `ix` never ran).
+ */
+export function ixExitScope(command) {
+ const { commands, separators, trailing } = shellCommands(command);
+ // A newline after `&&` continues the chain; a bare newline is a `;`.
+ const chained = separators.every((ops) => ops.replace(/\n/g, '') === '&&') && !/[&|]/.test(trailing);
+ const scopes = commands.map((words) => {
+ const { name, script } = program(words);
+ return name === 'ix' ? { sole: true, confirmed: true } : script !== undefined ? ixExitScope(script) : { sole: false, confirmed: false };
+ });
+ return { sole: chained && scopes.length === 1 && scopes[0].sole, confirmed: chained && scopes.some((scope) => scope.confirmed) };
+}
+
+// Claude Code's built-in search tools; they run no shell command, so commandCounts never sees them.
+const CLAUDE_SEARCH_TOOLS = new Set(['Grep', 'Glob']);
+
+/** Claude names MCP tools `mcp__<server>__<tool>`; plugin servers (our `--plugin-dir`
+ * arm) become `mcp__plugin_<plugin>_<server>__<tool>`. Plugin names are kebab-case.
+ */
+export function isIxMcpTool(name) {
+ const server = /^mcp__(.+?)__/.exec(name ?? '')?.[1] ?? '';
+ return /^(?:plugin_[a-z0-9-]+_)?ix(?:[._-]|$)/i.test(server);
+}
+
+// Claude's tool_result text when --print denies a tool that was not allowed.
+const CLAUDE_DENIAL = /requested permissions to use .*(?:haven't|have not) granted/is;
+// bash/dash/zsh/env messages for an `ix` that could not be started.
+const IX_MISSING = /(?:^|[\s'"/])ix'?: (?:(?:command )?not found|No such file or directory)|command not found: ix(?:\s|$)/m;
+
+function ixErrorCode(text) {
+ try { return JSON.parse(text).error?.code; } catch {
+ return String(text ?? '').match(/(?:^|\n)error\s+code=(?:"([\w.-]+)"|([\w.-]+))/)?.slice(1).find(Boolean);
+ }
+}
+/** An Ix failure visible in the output, even when `2>&1 | head` or `|| fallback` made the command exit 0. */
+function ixFailureCode(text) {
+ return ixErrorCode(text) ?? (IX_MISSING.test(String(text ?? '')) ? 'COMMAND_NOT_FOUND' : undefined);
+}
+const resultText = (content) => typeof content === 'string' ? content : Array.isArray(content) ? content.map((part) => part?.text ?? '').join('\n') : '';
+
+/** Strict by default; budget-interrupted totals remain unknown, never fabricated zeroes. */
+export function parseMetrics(text, format, { allowIncomplete = false } = {}) {
+ const lines = text.trim().split(/\r?\n/).filter(Boolean), events = []; let truncated = false;
+ for (const [i, line] of lines.entries()) {
+ try { events.push(JSON.parse(line)); } catch (error) {
+ if (!allowIncomplete || i !== lines.length - 1) throw error;
+ truncated = true; // A deadline can interrupt the last JSONL write.
+ }
+ }
+ if (!['normalized', 'claude', 'codex'].includes(format)) throw new Error('Unknown telemetry format');
+ let usage;
+ const turns = new Set(), tools = new Set(), ixTools = new Set(), failedTools = new Set(), ixDenied = new Set(), errors = Object.create(null);
+ // Ix tool calls whose exit status is Ix's own (soleIx) or proves Ix succeeded (confirmedIx); nonzero: tools that exited nonzero.
+ const soleIx = new Set(), confirmedIx = new Set(), nonzero = new Set();
+ let search_calls = 0, rg_calls = 0, grep_calls = 0, find_calls = 0, native_search_calls = 0, ix_calls = 0, permission_denials = 0;
+ const tool = (id, command = '', isIx = false, nativeSearch = false) => {
+ if (!id) throw new Error('Tool event missing id');
+ if (tools.has(id)) return;
+ tools.add(id);
+ const counts = commandCounts(command);
+ search_calls += counts.search_calls + Number(nativeSearch); native_search_calls += Number(nativeSearch);
+ rg_calls += counts.rg_calls; grep_calls += counts.grep_calls; find_calls += counts.find_calls;
+ ix_calls += counts.ix_calls + Number(isIx);
+ if (counts.ix_calls || isIx) {
+ ixTools.add(id);
+ const scope = isIx ? { sole: true, confirmed: true } : ixExitScope(command);
+ if (scope.sole) soleIx.add(id);
+ if (scope.confirmed) confirmedIx.add(id);
+ }
+ };
+ const ixError = (code) => { const key = String(code ?? 'unknown'); errors[key] = (errors[key] ?? 0) + 1; };
+ const toolError = (id, code) => { if (!failedTools.has(id)) { failedTools.add(id); ixError(code); } };
+ let completed = false, budgetReason;
+ for (const event of events) {
+ if (event.type === 'ix_error') ixError(event.code);
+ if (format === 'normalized') {
+ if (event.type === 'turn') { if (!event.id) throw new Error('Missing turn id'); turns.add(event.id); }
+ if (event.type === 'tool') tool(event.id, event.command, event.ix === true);
+ if (event.type === 'usage') {
+ if (usage) throw new Error('Duplicate normalized usage');
+ usage = { input_tokens: event.input_tokens, output_tokens: event.output_tokens, cached_tokens: event.cached_tokens };
+ }
+ if (event.type === 'done') completed = true;
+ }
+ if (format === 'claude') {
+ if (event.type === 'user') for (const content of event.message?.content ?? []) {
+ if (content.type === 'tool_result' && ixTools.has(content.tool_use_id)) {
+ const text = resultText(content.content), code = ixFailureCode(text);
+ // A permission denial is a harness misconfiguration, not an Ix failure.
+ if (content.is_error && CLAUDE_DENIAL.test(text)) ixDenied.add(content.tool_use_id);
+ else {
+ if (content.is_error) nonzero.add(content.tool_use_id);
+ if (code || (content.is_error && soleIx.has(content.tool_use_id))) toolError(content.tool_use_id, code);
+ }
+ }
+ }
+ if (event.type === 'assistant') {
+ if (!event.message?.id) throw new Error('Assistant event missing message id');
+ // A subagent's messages (Task/Explore) carry the id of the tool call that started it. They are not turns of the
+ // main agent, which is what --max-turns limits; their tool calls still count below.
+ if (!event.parent_tool_use_id && event.isSidechain !== true) turns.add(event.message.id);
+ for (const content of event.message.content ?? []) {
+ if (content.type === 'tool_use') tool(content.id, content.input?.command ?? '', isIxMcpTool(content.name), CLAUDE_SEARCH_TOOLS.has(content.name));
+ }
+ }
+ if (event.type === 'result') {
+ if (event.subtype === 'error_max_turns') budgetReason = 'turn_budget';
+ for (const denial of event.permission_denials ?? []) {
+ permission_denials++;
+ if (isIxMcpTool(denial.tool_name) || commandCounts(denial.tool_input?.command ?? '').ix_calls) ixDenied.add(denial.tool_use_id ?? denial.tool_name);
+ }
+ if (budgetReason && !event.usage) { completed = true; continue; }
+ if (usage) throw new Error('Duplicate Claude result');
+ const u = event.usage ?? {};
+ const fresh = counter(u.input_tokens, 'input_tokens');
+ const cached = counter(u.cache_read_input_tokens, 'cache_read_input_tokens');
+ const created = counter(u.cache_creation_input_tokens, 'cache_creation_input_tokens');
+ usage = { input_tokens: fresh + cached + created, output_tokens: u.output_tokens, cached_tokens: cached };
+ completed = true;
+ }
+ }
+ if (format === 'codex') {
+ if (event.type === 'turn.started') turns.add(`turn-${turns.size}`);
+ if (event.type === 'item.completed') {
+ const item = event.item;
+ if (item?.type === 'command_execution') {
+ tool(item.id, item.command);
+ const code = ixFailureCode(item.aggregated_output), failed = item.exit_code !== 0 && item.exit_code != null;
+ if (failed) nonzero.add(item.id);
+ if (ixTools.has(item.id) && (code || (failed && soleIx.has(item.id)))) toolError(item.id, code);
+ }
+ if (item?.type === 'mcp_tool_call') tool(item.id, '', /^ix(?:[._-]|$)/.test(item.server ?? ''));
+ if (['file_change', 'web_search'].includes(item?.type)) tool(item.id);
+ if (item?.type === 'mcp_tool_call' && /^ix(?:[._-]|$)/.test(item.server ?? '') && item.error) toolError(item.id, item.error.code);
+ }
+ if (event.type === 'turn.completed') {
+ const u = event.usage ?? {};
+ const delta = { input_tokens: counter(u.input_tokens, 'input_tokens'), output_tokens: counter(u.output_tokens, 'output_tokens'), cached_tokens: counter(u.cached_input_tokens, 'cached_input_tokens') };
+ usage ??= { input_tokens: 0, output_tokens: 0, cached_tokens: 0 };
+ for (const key of Object.keys(delta)) usage[key] += delta[key];
+ completed = true;
+ }
+ if (event.type === 'turn.failed' || event.type === 'error') throw new Error('Agent failed; transcript is incomplete');
+ }
+ }
+ const terminal = { normalized: 'done', claude: 'result', codex: 'turn.completed' }[format];
+ const complete = Boolean(completed && usage && turns.size && !truncated && events.at(-1)?.type === terminal);
+ if (!complete && !allowIncomplete && !budgetReason) throw new Error('Incomplete transcript: terminal event, turns and usage required');
+ if (usage) {
+ for (const key of ['input_tokens', 'output_tokens', 'cached_tokens']) counter(usage[key], key);
+ if (usage.cached_tokens > usage.input_tokens) throw new Error('Cached tokens exceed total input tokens');
+ }
+ // Partial usage is a lower bound, never silently billed as a complete total.
+ const tokens = complete ? usage : { input_tokens: null, output_tokens: null, cached_tokens: null };
+ return { ...tokens, usage_complete: complete, telemetry_complete: complete, observed_usage: usage ?? null, budget_reason: budgetReason ?? null,
+ // Ix calls that certainly ran and succeeded: an Ix MCP call or an `&&` chain with `ix` that exited 0, with no Ix failure
+ // in its output. Normalized telemetry has no per-call outcome, so its confirmed calls all count.
+ ix_succeeded: [...confirmedIx].filter((id) => !nonzero.has(id) && !failedTools.has(id) && !ixDenied.has(id)).length,
+ turns: turns.size, tool_calls: tools.size, ix_permission_denials: ixDenied.size, permission_denials, search_calls, rg_calls, grep_calls, find_calls, native_search_calls, ix_calls,
+ ix_errors: Object.values(errors).reduce((a, b) => a + b, 0), ix_errors_by_code: { ...errors } };
+}
diff --git a/bench/agent-eval/process.mjs b/bench/agent-eval/process.mjs
new file mode 100644
index 00000000..4b69b0f4
--- /dev/null
+++ b/bench/agent-eval/process.mjs
@@ -0,0 +1,90 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { spawn, spawnSync } from 'node:child_process';
+import { writeFileSync } from 'node:fs';
+import { performance } from 'node:perf_hooks';
+
+const groupAlive = (pid) => {
+ try { process.kill(-pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
+};
+
+/** Members of process group `pgid`: pid, parent pid and command line. Undefined when `ps` is unavailable. */
+function groupMembers(pgid) {
+ const ps = spawnSync('ps', ['-A', '-ww', '-o', 'pid=,ppid=,pgid=,args='], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+ if (ps.status !== 0) return undefined;
+ return ps.stdout.split('\n').map((line) => /^\s*(\d+)\s+(\d+)\s+(\d+)\s?(.*)$/.exec(line)).filter((m) => m && Number(m[3]) === pgid)
+ .map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), args: m[4] }));
+}
+
+/** When the adapter exits, stop its whole group at once and kill every member except `keep` processes and their
+ * descendants, then resume those. Nothing else the adapter left behind runs on, whatever the arm.
+ * Repeats until no other member is left (a fork racing the stop). Without `ps`, the whole group is killed.
+ */
+export function reapExcept(pgid, keep) {
+ const signal = (target, name) => { try { process.kill(target, name); return true; } catch { return false; } };
+ if (!signal(-pgid, 'SIGSTOP')) return; // Group already gone.
+ try {
+ for (let pass = 0; pass < 5; pass++) {
+ const members = groupMembers(pgid);
+ if (!members) { signal(-pgid, 'SIGKILL'); return; }
+ const kept = new Set(members.filter((m) => keep(m.args)).map((m) => m.pid));
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const m of members) if (!kept.has(m.pid) && kept.has(m.ppid)) { kept.add(m.pid); grew = true; }
+ }
+ const others = members.filter((m) => !kept.has(m.pid));
+ if (!others.length) return;
+ for (const m of others) signal(m.pid, 'SIGKILL');
+ }
+ signal(-pgid, 'SIGKILL'); // Still forking after repeated passes: keep nothing.
+ } finally { signal(-pgid, 'SIGCONT'); }
+}
+
+/** One deadline, no retries. Only the agent caller opts into retaining timeout/exit receipts.
+ * drainSeconds lets `keep` descendants that outlive the adapter (an Ix hook, matched on its command line) finish
+ * before the group is reaped; every other descendant is killed the moment the adapter exits.
+ * The deadline and stage time end when the adapter exits, even if a descendant still holds its stdout open.
+ */
+export function execute(argv, { cwd, env = process.env, seconds = 60, log, input, allowTimeout = false, captureExit = false, drainSeconds = 0, keep = () => false } = {}) {
+ return new Promise((resolve, reject) => {
+ const started = performance.now();
+ const detached = process.platform !== 'win32' && process.env.AGENT_EVAL_CHILD !== '1';
+ const child = spawn(argv[0], argv.slice(1), { cwd, env: { ...env, AGENT_EVAL_CHILD: '1' }, detached, stdio: ['pipe', 'pipe', 'pipe'] });
+ child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8');
+ let stdout = '', stderr = '', failure, timedOut = false, exitedAt, drainTimer, cut = false;
+ const kill = () => {
+ try { if (detached) process.kill(-child.pid, 'SIGKILL'); else child.kill('SIGKILL'); } catch { /* already exited */ }
+ };
+ const timer = setTimeout(() => { timedOut = true; failure = new Error(`Stage deadline exceeded (${seconds}s)`); kill(); }, seconds * 1000);
+ const capture = (stream, chunk) => {
+ if (stream === 'stdout') stdout += chunk; else stderr += chunk;
+ if (Buffer.byteLength(stdout) + Buffer.byteLength(stderr) > 64 * 1024 * 1024) { failure = new Error('Stage output exceeds 64 MiB'); kill(); }
+ };
+ child.stdout.on('data', (chunk) => capture('stdout', chunk));
+ child.stderr.on('data', (chunk) => capture('stderr', chunk));
+ child.stdin.on('error', () => {});
+ child.stdin.end(input);
+ child.on('error', (error) => { clearTimeout(timer); reject(error); });
+ // Only drained processes outlive the adapter; anything else could still change the checkout before it is recorded.
+ const cutAtExit = () => { if (!cut && detached && !timedOut && drainSeconds > 0) { cut = true; reapExcept(child.pid, keep); } };
+ child.on('exit', () => {
+ exitedAt = performance.now(); clearTimeout(timer); cutAtExit();
+ // A descendant that inherited stdout keeps 'close' from firing; reap it once the drain ends. Buffered output is still read.
+ if (!timedOut) drainTimer = setTimeout(kill, drainSeconds * 1000);
+ });
+ child.on('close', async (code) => {
+ clearTimeout(timer); clearTimeout(drainTimer);
+ exitedAt ??= performance.now(); cutAtExit();
+ const elapsed = (exitedAt - started) / 1000; // Excludes the drain.
+ if (detached && !timedOut && drainSeconds > 0) {
+ const deadline = exitedAt + drainSeconds * 1000;
+ while (groupAlive(child.pid) && performance.now() < deadline) await new Promise((done) => setTimeout(done, 100));
+ }
+ if (detached) kill(); // Also reap descendants that outlived their adapter (and the drain).
+ if (log) { writeFileSync(`${log}.stdout`, stdout); writeFileSync(`${log}.stderr`, stderr); }
+ if (failure && !(allowTimeout && timedOut && failure.message.startsWith('Stage deadline'))) return reject(failure);
+ if (code !== 0 && !captureExit && !(allowTimeout && timedOut)) return reject(new Error(`Stage exited ${code}; inspect stage logs`));
+ resolve({ stdout, stderr, seconds: elapsed, timed_out: timedOut, exit_code: code });
+ });
+ });
+}
diff --git a/bench/agent-eval/provision.mjs b/bench/agent-eval/provision.mjs
new file mode 100644
index 00000000..5e522aeb
--- /dev/null
+++ b/bench/agent-eval/provision.mjs
@@ -0,0 +1,166 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { execute } from './process.mjs';
+import { sha256 } from './manifest.mjs';
+import { findBinary, shellQuote } from './isolation.mjs';
+import { HOOK_SCRIPT, MCP_SERVER, PLUGIN_NAME, hookTimeoutSeconds } from './integration.mjs';
+
+const json = (value) => JSON.stringify(value, null, 2) + '\n';
+const write = (path, text) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); };
+const run = (request, argv, input) => execute(argv, { cwd: request.repo_path, seconds: request.environment.seconds, input });
+
+export function integrationFiles(request) {
+ const plugin = join(request.run_path, 'plugin');
+ const hook = [process.execPath, HOOK_SCRIPT];
+ // Claude's default hook timeout is shorter than the two ix deadlines the hook runs.
+ const hookTimeout = hookTimeoutSeconds(request.environment);
+ if (request.agent.family === 'claude') return {
+ [join(plugin, '.claude-plugin', 'plugin.json')]: json({ name: PLUGIN_NAME, version: '1.0.0', description: 'Pinned local Ix benchmark integration' }),
+ [join(plugin, '.mcp.json')]: json({ mcpServers: { [MCP_SERVER]: { command: 'ix', args: ['mcp'] } } }),
+ [join(plugin, 'hooks', 'hooks.json')]: json({ hooks: { PostToolUse: [{ matcher: 'Edit|MultiEdit|Write|Bash', hooks: [{ type: 'command', command: hook.map(shellQuote).join(' ') + ' claude', timeout: hookTimeout }] }] } }),
+ };
+ if (request.agent.family === 'codex') {
+ const endpoint = request.environment.endpoint;
+ if (typeof endpoint !== 'string' || !endpoint) throw new Error('Codex provisioning requires environment.endpoint');
+ // Codex starts stdio MCP servers with an allowlisted environment, so the endpoint is passed explicitly.
+ return {
+ [join(request.home, '.codex', 'config.toml')]: `notify = ${JSON.stringify([...hook, 'codex'])}\n[mcp_servers.${MCP_SERVER}]\ncommand = "ix"\nargs = ["mcp"]\nenv = { IX_ENDPOINT = ${JSON.stringify(endpoint)} }\n`,
+ [join(plugin, 'plugin.json')]: json({ name: PLUGIN_NAME, family: 'codex', source_revision: request.environment.plugin_revision, transport: 'ix mcp', hook: 'notify:agent-turn-complete' }),
+ };
+ }
+ throw new Error('Local provisioning requires Claude Code or Codex');
+}
+
+async function pinnedSkills(request) {
+ const { source_path: source, plugin_revision: revision } = request.environment;
+ const head = (await run(request, ['git', '-C', source, 'rev-parse', 'HEAD'])).stdout.trim();
+ if (head !== revision) throw new Error('Ix source revision differs from plugin pin');
+ await run(request, ['git', '-C', source, 'diff', '--exit-code', revision, '--', 'ix-cli/src', 'skills/ix']);
+ const names = (await run(request, ['git', '-C', source, 'ls-tree', '-r', '--name-only', revision, '--', 'skills/ix'])).stdout.trim().split('\n');
+ if (!names.includes('skills/ix/SKILL.md')) throw new Error('Pinned source has no Ix skill');
+ // Codex: $CODEX_HOME/skills, the location the product installer uses (ix-cli/scripts/skill-harnesses.mjs).
+ const base = request.agent.family === 'claude' ? join(request.run_path, 'plugin', 'skills', 'ix') : join(request.home, '.codex', 'skills', 'ix');
+ const files = {};
+ for (const name of names) {
+ if (!/^skills\/ix\/[\w./-]+$/.test(name) || name.split('/').includes('..')) throw new Error('Invalid pinned skill path');
+ files[join(base, name.slice('skills/ix/'.length))] = (await run(request, ['git', '-C', source, 'show', `${revision}:${name}`])).stdout;
+ }
+ return files;
+}
+
+/** Reject upstream agent configuration instead of silently modifying task files. */
+export function checkTaskIsolation(request) {
+ if (!request.synthetic) {
+ for (let parent = dirname(request.repo_path); ; parent = dirname(parent)) {
+ for (const name of ['AGENTS.md', 'CLAUDE.md', '.claude', '.codex', '.agents', '.mcp.json']) {
+ // Developer homes usually hold ~/.claude or ~/.codex, so name the culprit.
+ if (existsSync(join(parent, name))) throw new Error(`Ambient ancestor agent configuration at ${join(parent, name)}; choose an output directory outside that project and outside any home directory holding agent configuration`);
+ }
+ if (parent === dirname(parent)) break;
+ }
+ }
+ for (const name of ['.claude', '.codex', '.agents', '.mcp.json', 'CLAUDE.md', 'AGENTS.md']) {
+ if (existsSync(join(request.repo_path, name))) throw new Error(`Task contains ambient agent configuration: ${name}`);
+ }
+}
+
+/** Whether `codex debug prompt-input` output lists a skill by name; that is the model-visible skill list. */
+export function codexSkillListed(promptInput, name) {
+ const texts = [];
+ const walk = (value) => {
+ if (typeof value === 'string') texts.push(value);
+ else if (value && typeof value === 'object') for (const item of Object.values(value)) walk(item);
+ };
+ walk(JSON.parse(promptInput));
+ const entry = new RegExp(`^- ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}: `, 'm');
+ return texts.some((text) => entry.test(text));
+}
+
+export function assertMapped(status, stats) {
+ if (status.graphCompleted !== true || status.mapCompleted !== true || status.staleFiles !== 0 ||
+ (status.replayedFiles ?? []).length || (status.parseTimeouts ?? []).length ||
+ status.graphHealth?.status !== 'ok' || !(stats.nodes?.total > 0)) {
+ throw new Error('Ix is unmapped, stale, incomplete or unhealthy in this checkout');
+ }
+}
+
+/**
+ * Isolation is a PATH; a login shell (Codex runs `bash -lc`, Claude Code starts from the user's $SHELL) may reset it in
+ * /etc/profile. Only the shells those agents launch are probed: Claude Code runs bash or zsh, so a `$SHELL` such as
+ * /bin/sh is never used and its profile does not matter.
+ */
+export async function checkLoginShells(request, env = process.env) {
+ const launcher = request.arm === 'ix' ? join(request.run_path, 'bin', 'ix') : '';
+ const shells = new Set();
+ for (const name of ['bash', env.SHELL]) {
+ if (!name || !/(^|\/)(ba|z)sh$/.test(name)) continue;
+ try { shells.add(findBinary(name, env.PATH)); } catch { /* not installed */ }
+ }
+ for (const shell of shells) {
+ // The marker keeps login banners or profile output out of the answer.
+ const { stdout: out, stderr, exit_code } = await execute([shell, '-lc', 'printf "\\nix-path=%s\\n" "$(command -v ix)"'], { cwd: request.repo_path, env, seconds: request.environment.seconds, captureExit: true });
+ if (exit_code !== 0) throw new Error(`A login shell (${shell} -l) exited ${exit_code} under the ${request.arm} arm's PATH, so the agent's commands would fail too: ${stderr.trim().split('\n').slice(-5).join(' | ') || 'no stderr'}`);
+ const found = out.match(/^ix-path=(.*)$/m)?.[1];
+ if (found !== launcher) throw new Error(`A login shell (${shell} -l) resolves ix to ${found ? found : 'nothing'}, expected ${launcher || 'nothing'}; its profile resets PATH and undoes the ${request.arm} arm's isolation`);
+ }
+}
+
+export async function setup(request) {
+ checkTaskIsolation(request);
+ if (request.arm === 'baseline') return;
+ const files = { ...integrationFiles(request), ...await pinnedSkills(request) };
+ for (const [path, text] of Object.entries(files)) write(path, text);
+ await run(request, ['ix', 'map', '--silent']);
+}
+
+export async function probe(request) {
+ checkTaskIsolation(request);
+ const head = (await run(request, ['git', 'rev-parse', 'HEAD'])).stdout.trim();
+ if (head !== request.task.base_commit) throw new Error('Task checkout moved from pinned base');
+ const version = (await run(request, [request.agent.binary ?? request.agent.family, '--version'])).stdout.trim();
+ if (!version.split(/\s+/).includes(request.agent.version)) throw new Error('Agent version differs from pin');
+ let available = false;
+ try { findBinary('ix'); available = true; } catch { /* baseline must have no launcher */ }
+ const ix = request.arm === 'ix';
+ if (available !== ix) throw new Error('Ix PATH isolation is incorrect');
+ await checkLoginShells(request);
+ const evidence = [];
+ if (ix) {
+ const ixVersion = (await run(request, ['ix', '--version'])).stdout.trim();
+ if (!ixVersion.split(/\s+/).includes(request.environment.ix_version)) throw new Error('Ix CLI version differs from pin');
+ const files = { ...integrationFiles(request), ...await pinnedSkills(request) };
+ for (const [path, expected] of Object.entries(files)) {
+ if (readFileSync(path, 'utf8') !== expected) throw new Error(`Integration content differs: ${path}`);
+ evidence.push({ path, sha256: sha256(expected) });
+ }
+ // File presence is not discovery: ask the pinned Codex which skills it puts in front of the model (no model call).
+ if (request.agent.family === 'codex' && !codexSkillListed((await run(request, [request.agent.binary ?? 'codex', 'debug', 'prompt-input'])).stdout, 'ix')) {
+ throw new Error('Codex does not list the installed Ix skill (codex debug prompt-input)');
+ }
+ // Exercise the configured hook executable; config presence alone is insufficient.
+ await run(request, [process.execPath, HOOK_SCRIPT, 'probe']);
+ const status = JSON.parse((await run(request, ['ix', 'status', '--format', 'json', '--root', request.repo_path])).stdout);
+ const stats = JSON.parse((await run(request, ['ix', 'stats', '--format', 'json'])).stdout);
+ assertMapped(status, stats);
+ for (const [name, data] of [['map-status.json', status], ['map-stats.json', stats]]) {
+ const path = join(request.run_path, name); write(path, json(data)); evidence.push({ path, sha256: sha256(json(data)) });
+ }
+ } else {
+ if (existsSync(join(request.run_path, 'plugin')) || existsSync(join(request.home, '.codex', 'config.toml')) || existsSync(join(request.home, '.codex', 'skills'))) throw new Error('Baseline contains Ix integration');
+ }
+ return { version: 1, repo_path: request.repo_path, base_commit: head, agent_version: request.agent.version,
+ ix_available: available, mapped: ix, plugin_installed: ix, skills_installed: ix, hooks_enabled: ix,
+ ...(ix ? { mapped_commit: head, plugin_revision: request.environment.plugin_revision } : {}), evidence };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ try {
+ const [stage, file] = process.argv.slice(2), request = JSON.parse(readFileSync(file, 'utf8'));
+ if (stage === 'setup') await setup(request);
+ else if (stage === 'probe') console.log(json(await probe(request)));
+ else throw new Error('Usage: provision.mjs setup|probe REQUEST.json');
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
+}
diff --git a/bench/agent-eval/run.mjs b/bench/agent-eval/run.mjs
new file mode 100644
index 00000000..b54bdbe6
--- /dev/null
+++ b/bench/agent-eval/run.mjs
@@ -0,0 +1,188 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { validateConfig, validateProbe, schedule } from './config.mjs';
+import { checkManifestSource, loadManifest, sha256 } from './manifest.mjs';
+import { budgetTokens, parseMetrics } from './metrics.mjs';
+import { execute } from './process.mjs';
+import { markdown, summarize } from './stats.mjs';
+import { checkResolution } from './evaluation.mjs';
+import { armEnvironment, findBinary } from './isolation.mjs';
+import { PENDING, hookTimeoutSeconds, isHookProcess } from './integration.mjs';
+
+const root = dirname(fileURLToPath(import.meta.url));
+const json = (file, value) => writeFileSync(file, JSON.stringify(value, null, 2) + '\n');
+const contained = (parent, child) => { const rel = relative(parent, child); return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); };
+export function resolveConfigPaths(config, base = process.cwd()) {
+ config = structuredClone(config);
+ // argv entries representing files are resolved before changing into task checkouts.
+ const argv = (args) => args?.map((arg, i) => typeof arg === 'string' && !arg.startsWith('-') && ((i === 0 && arg.includes('/')) || /\.(mjs|cjs|js|py|sh|json)$/.test(arg)) ? resolve(base, arg) : arg);
+ if (config.agent) {
+ config.agent.command = argv(config.agent.command);
+ if (config.agent.binary?.includes('/')) config.agent.binary = resolve(base, config.agent.binary);
+ }
+ if (config.environment) for (const stage of ['setup', 'probe']) config.environment[stage] = argv(config.environment[stage]);
+ if (config.evaluator) {
+ config.evaluator.command = argv(config.evaluator.command);
+ if (config.evaluator.harness_path) config.evaluator.harness_path = resolve(base, config.evaluator.harness_path);
+ if (config.evaluator.python?.includes('/')) config.evaluator.python = resolve(base, config.evaluator.python);
+ }
+ if (config.environment) {
+ for (const field of ['source_path', 'ix_cli']) if (config.environment[field]) config.environment[field] = resolve(base, config.environment[field]);
+ if (config.environment.tool_paths) config.environment.tool_paths = config.environment.tool_paths.map((dir) => resolve(base, dir));
+ }
+ for (const field of ['dataset_export', 'repo_cache', 'work_root']) if (config[field]) config[field] = resolve(base, config[field]);
+ return config;
+}
+export function dryConfig() {
+ const stub = [process.execPath, join(root, 'stub.mjs')];
+ return { version: 1, repeats: 2, seed: 20261013, bootstrap_samples: 1000,
+ agent: { family: 'stub', version: 'synthetic-v1', model: 'stub', effort: 'medium', telemetry: 'normalized', command: [...stub, 'agent'] },
+ budget: { max_turns: 20, max_tokens: 100000, seconds: 30 },
+ environment: { seconds: 30, plugin_revision: 'synthetic-v1', setup: [...stub, 'setup'], probe: [...stub, 'probe'] },
+ evaluator: { seconds: 30, kind: 'synthetic', command: [...stub, 'evaluate'] } };
+}
+
+/** No shell interpolation: all adapters receive exactly one final request-file argument. */
+export async function runBenchmark({ manifestPath, config, out, dryRun = false }) {
+ const manifest = loadManifest(manifestPath);
+ if (dryRun !== (manifest.dataset === 'synthetic')) throw new Error('Synthetic manifests require --dry-run; real datasets forbid it');
+ validateConfig(config, dryRun);
+ config = resolveConfigPaths(config);
+ if (!dryRun && config.agent.command[1]?.endsWith('/agent.mjs')) config.agent.binary = findBinary(config.agent.binary ?? config.agent.family);
+ out = resolve(out);
+ if (existsSync(out)) throw new Error('Output directory already exists; choose a fresh path');
+ if (!dryRun) {
+ const dataset = readFileSync(config.dataset_export, 'utf8');
+ checkManifestSource(manifest, dataset, config.dataset_export);
+ }
+ // Agent-facing checkouts live outside the output tree, so a solver cannot browse earlier runs' patches and reports.
+ const workRoot = realpathSync(config.work_root ?? tmpdir());
+ if (!dryRun && contained(workRoot, out)) throw new Error('Output directory is inside the agent work root; choose an output directory outside it or set work_root elsewhere');
+ mkdirSync(out, { recursive: true });
+ const jobs = schedule(manifest.tasks, config.repeats, config.seed);
+ json(join(out, 'harness.json'), { version: 1, files: Object.fromEntries(readdirSync(root).filter((name) => name.endsWith('.mjs')).sort().map((name) => [name, sha256(readFileSync(join(root, name)))])) });
+ json(join(out, 'manifest.json'), manifest); json(join(out, 'config.json'), config);
+ json(join(out, 'schedule.json'), jobs.map(({ task, ...job }) => ({ ...job, instance_id: task.instance_id })));
+ const runs = [];
+ for (const [index, job] of jobs.entries()) {
+ const runPath = join(out, `${String(index).padStart(4, '0')}-${job.task.instance_id}-${job.repeat}-${job.arm}`);
+ mkdirSync(runPath);
+ // The work directory holds everything the solver can reach: checkout, home, integrations, hook telemetry.
+ const workPath = mkdtempSync(join(workRoot, 'agent-eval-'));
+ const repoPath = join(workPath, 'repo'), home = join(workPath, 'home');
+ mkdirSync(home, { recursive: true });
+ const task = { instance_id: job.task.instance_id, repo: job.task.repo, base_commit: job.task.base_commit, problem_statement: job.task.problem_statement };
+ // Setup, probe, agent and hooks never see the dataset export (gold patches), the evaluator or the output directory.
+ const request = { version: 1, synthetic: dryRun, ...job, task, run_path: workPath, repo_path: repoPath, home, agent: config.agent, budget: config.budget, environment: config.environment };
+ const env = armEnvironment(request);
+ const requestPath = join(workPath, 'request.json'); json(requestPath, request);
+ const evaluateRequestPath = join(runPath, 'evaluate-request.json');
+ const stage = (name, argv, seconds, { cwd = repoPath, file = requestPath, ...options } = {}) => execute([...argv, file], { cwd, env, seconds, log: join(runPath, name), ...options });
+ const setupStart = performance.now();
+ try {
+ if (dryRun) mkdirSync(repoPath); else {
+ const cached = resolve(config.repo_cache, `${job.task.repo.replace('/', '__')}.git`);
+ if (!contained(resolve(config.repo_cache), realpathSync(cached))) throw new Error('Repository cache escapes configured root');
+ await execute(['git', 'clone', '--no-hardlinks', '--no-checkout', cached, repoPath], { env, seconds: config.environment.seconds, log: join(runPath, 'clone') });
+ await execute(['git', 'checkout', '--detach', job.task.base_commit], { cwd: repoPath, env, seconds: config.environment.seconds, log: join(runPath, 'checkout') });
+ }
+ await stage('setup', config.environment.setup, config.environment.seconds);
+ const probe = JSON.parse((await stage('probe', config.environment.probe, config.environment.seconds)).stdout);
+ validateProbe(probe, request);
+ for (const evidence of probe.evidence ?? []) {
+ const file = realpathSync(resolve(workPath, evidence.path));
+ if (!contained(workPath, file) || sha256(readFileSync(file)) !== evidence.sha256) throw new Error('Invalid environment evidence');
+ }
+ if (!dryRun) {
+ const head = await execute(['git', 'rev-parse', 'HEAD'], { cwd: repoPath, env, seconds: 10 });
+ if (head.stdout.trim() !== job.task.base_commit) throw new Error('Setup changed pinned checkout');
+ // Keep setup-created integration files out of the solution patch.
+ const diff = await execute(['git', 'diff', '--binary', 'HEAD'], { cwd: repoPath, env, seconds: 10 });
+ if (diff.stdout) throw new Error('Setup modified tracked task files');
+ }
+ const setupSeconds = (performance.now() - setupStart) / 1000;
+ const hookLog = join(workPath, 'hooks.jsonl'), pending = join(workPath, PENDING);
+ if (existsSync(hookLog)) writeFileSync(hookLog, ''); // Exclude setup/probe hook calls.
+ rmSync(pending, { recursive: true, force: true });
+ // A Codex notify hook can still be refreshing the map when the native CLI exits; let it finish before reaping.
+ // Both arms are reaped alike: when the agent exits, every leftover process except Ix hooks is killed at once, so
+ // nothing the agent started can change the checkout after exit in either arm. The baseline has no hooks to wait for.
+ const agent = await stage('agent', config.agent.command, config.budget.seconds, { allowTimeout: true, captureExit: true, drainSeconds: hookTimeoutSeconds(config.environment), keep: isHookProcess });
+ if (!agent.timed_out && existsSync(pending) && readdirSync(pending).length) throw new Error('An Ix hook was still running when the agent stage was reaped; its telemetry is incomplete');
+ const metrics = parseMetrics(agent.stdout, config.agent.telemetry, { allowIncomplete: agent.timed_out || agent.exit_code !== 0 });
+ const overTurns = metrics.turns > config.budget.max_turns;
+ const usage = metrics.observed_usage;
+ const overTokens = usage && budgetTokens(usage) > config.budget.max_tokens;
+ const termination = agent.timed_out ? 'time_budget' : overTokens ? 'token_budget' : (overTurns ? 'turn_budget' : metrics.budget_reason ?? 'completed');
+ if (agent.exit_code !== 0 && termination === 'completed') throw new Error('Agent stage failed without a recognized budget outcome');
+ if (metrics.ix_permission_denials) throw new Error('Agent was denied Ix tools; the comparison would be biased against Ix. Check the ix arm --allowedTools integration');
+ // The probe proved the baseline PATH has no launcher, so a failed `ix` attempt is an observation; a working one is a leak.
+ if (job.arm === 'baseline' && metrics.ix_succeeded) throw new Error('Baseline ix call succeeded; inspect isolation before comparing arms');
+ let patch = '';
+ if (!dryRun) {
+ await execute(['git', 'add', '-N', '--', '.'], { cwd: repoPath, env, seconds: 10 });
+ patch = (await execute(['git', 'diff', '--binary', job.task.base_commit, '--', '.', ':(exclude).claude', ':(exclude).agents', ':(exclude).codex', ':(exclude).ix', ':(exclude).mcp.json'], { cwd: repoPath, env, seconds: 10 })).stdout;
+ }
+ writeFileSync(join(runPath, 'prediction.patch'), patch);
+ let hookSeconds = 0;
+ // Hook calls follow tool-call volume, not the agent's choice to use Ix, so they stay out of ix_calls/ix_errors.
+ metrics.hook_ix_calls = 0; metrics.hook_ix_errors = 0;
+ if (existsSync(hookLog)) {
+ const hooks = readFileSync(hookLog, 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line));
+ for (const hook of hooks) {
+ if (!Number.isSafeInteger(hook.ix_calls) || hook.ix_calls < 0 || !(Number.isFinite(hook.seconds) && hook.seconds >= 0)) throw new Error('Invalid hook telemetry');
+ hookSeconds += hook.seconds;
+ metrics.hook_ix_calls += hook.ix_calls;
+ if (hook.type === 'ix_error') metrics.hook_ix_errors++;
+ }
+ }
+ if (!dryRun && job.arm === 'ix' && config.environment.setup.includes(join(root, 'provision.mjs')) && termination === 'completed' && patch && (!existsSync(hookLog) || !readFileSync(hookLog, 'utf8').trim())) throw new Error('Agent changed code without firing the configured Ix hook');
+ json(join(runPath, 'prediction.json'), [{ instance_id: job.task.instance_id, model_name_or_path: 'agent-eval', model_patch: patch }]);
+ // Only the evaluator gets the dataset export; it runs after the solver has exited.
+ json(evaluateRequestPath, { ...request, run_path: runPath, evaluator: config.evaluator, dataset_export: config.dataset_export && resolve(config.dataset_export) });
+ // The evaluator is the same for both arms and needs the host's Docker client configuration (~/.docker contexts), so it
+ // runs with the inherited environment rather than the solver's isolated HOME and PATH.
+ const evaluation = await stage('evaluate', config.evaluator.command, config.evaluator.seconds, { cwd: runPath, file: evaluateRequestPath, env: process.env });
+ const result = JSON.parse(evaluation.stdout);
+ if (result.instance_id !== job.task.instance_id || typeof result.resolved !== 'boolean' || result.evaluator !== config.evaluator.kind || (!dryRun && result.revision !== config.evaluator.revision)) throw new Error('Invalid official evaluation receipt');
+ if (!dryRun) {
+ const reportPath = realpathSync(result.report_path);
+ if (!contained(runPath, reportPath) || sha256(readFileSync(reportPath)) !== result.report_sha256) throw new Error('Invalid official report evidence');
+ const official = JSON.parse(readFileSync(reportPath, 'utf8'));
+ checkResolution(official, result, job.task.instance_id, patch);
+ }
+ const run = { instance_id: job.task.instance_id, repo: job.task.repo, base_commit: job.task.base_commit, repeat: job.repeat, arm: job.arm, ...metrics, termination, official_resolved: Number(result.resolved), resolved: Number(result.resolved && !overTurns && !overTokens), wall_seconds: agent.seconds, hook_seconds: hookSeconds, setup_seconds: setupSeconds, eval_seconds: evaluation.seconds, total_wall_seconds: (performance.now() - setupStart) / 1000 };
+ json(join(runPath, 'result.json'), run); runs.push(run);
+ writeFileSync(join(out, 'runs.jsonl'), runs.map((r) => JSON.stringify(r)).join('\n') + '\n');
+ for (const name of ['request.json', 'hooks.jsonl', 'map-status.json', 'map-stats.json']) {
+ if (existsSync(join(workPath, name))) copyFileSync(join(workPath, name), join(runPath, name === 'request.json' ? 'agent-request.json' : name));
+ }
+ rmSync(workPath, { recursive: true, force: true });
+ } catch (error) {
+ // The work directory is kept for inspection; a fatal error ends the experiment, so no later solver sees it.
+ json(join(runPath, 'failure.json'), { stage_error: error.message, work_path: workPath });
+ throw new Error(`Run ${index} (${job.task.instance_id}/${job.arm}) invalid: ${error.message}`);
+ }
+ }
+ const report = summarize(runs, { samples: config.bootstrap_samples, seed: config.seed });
+ json(join(out, 'report.json'), report); writeFileSync(join(out, 'summary.md'), markdown(report, dryRun));
+ return report;
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ try {
+ const args = process.argv.slice(2), options = {};
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--dry-run') options.dryRun = true;
+ else if (['--manifest', '--config', '--out'].includes(args[i]) && args[i + 1] && !args[i + 1].startsWith('--')) options[args[i].slice(2)] = args[++i];
+ else throw new Error('Usage: node run.mjs [--dry-run] [--manifest FILE] [--config FILE] --out NEW_DIRECTORY');
+ }
+ if (!options.out || (!options.dryRun && (!options.manifest || !options.config))) throw new Error('An output path and, for real runs, manifest/config are required');
+ await runBenchmark({ out: options.out, dryRun: options.dryRun ?? false, manifestPath: options.manifest ?? join(root, 'smoke.json'), config: options.config ? JSON.parse(readFileSync(options.config, 'utf8')) : dryConfig() });
+ console.log('Completed paired runs; see summary.md and report.json in the output directory.');
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
+}
diff --git a/bench/agent-eval/smoke.json b/bench/agent-eval/smoke.json
new file mode 100644
index 00000000..2f202e83
--- /dev/null
+++ b/bench/agent-eval/smoke.json
@@ -0,0 +1,10 @@
+{
+ "version": 1,
+ "dataset": "synthetic",
+ "description": "Synthetic placeholders for orchestration only. These are not SWE-bench tasks or real repository SHAs.",
+ "tasks": [
+ { "instance_id": "synthetic-one", "repo": "synthetic/one", "base_commit": "1111111111111111111111111111111111111111", "problem_statement": "Write the synthetic solution fixture." },
+ { "instance_id": "synthetic-two", "repo": "synthetic/two", "base_commit": "2222222222222222222222222222222222222222", "problem_statement": "Write the synthetic solution fixture." },
+ { "instance_id": "synthetic-three", "repo": "synthetic/three", "base_commit": "3333333333333333333333333333333333333333", "problem_statement": "Write the synthetic solution fixture." }
+ ]
+}
diff --git a/bench/agent-eval/stats.mjs b/bench/agent-eval/stats.mjs
new file mode 100644
index 00000000..770cb18a
--- /dev/null
+++ b/bench/agent-eval/stats.mjs
@@ -0,0 +1,88 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { METRICS } from './metrics.mjs';
+import { positiveInteger } from './manifest.mjs';
+
+export function random(seed) {
+ if (!Number.isSafeInteger(seed)) throw new Error('seed must be an integer');
+ let state = seed >>> 0;
+ return () => { state += 0x6D2B79F5; let x = state; x = Math.imul(x ^ x >>> 15, x | 1); x ^= x + Math.imul(x ^ x >>> 7, x | 61); return ((x ^ x >>> 14) >>> 0) / 4294967296; };
+}
+export function shuffled(items, rng) {
+ const result = [...items];
+ for (let i = result.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [result[i], result[j]] = [result[j], result[i]]; }
+ return result;
+}
+export const mean = (values) => values.reduce((a, b) => a + b, 0) / values.length;
+export const median = (values) => { const v = [...values].sort((a, b) => a - b); return (v[Math.floor(v.length / 2)] + v[Math.floor((v.length - 1) / 2)]) / 2; };
+const quantile = (values, p) => {
+ const v = [...values].sort((a, b) => a - b), pos = (v.length - 1) * p, lo = Math.floor(pos);
+ return v[lo] + (v[Math.ceil(pos)] - v[lo]) * (pos - lo);
+};
+
+/** Paired task-cluster bootstrap: repeats stay within their task when resampled. */
+export function summarize(runs, { samples = 10000, seed = 20261013 } = {}) {
+ positiveInteger(samples, 'samples');
+ if (samples < 100) throw new Error('At least 100 bootstrap samples required');
+ const tasks = new Map();
+ for (const run of runs) {
+ if (!['baseline', 'ix'].includes(run.arm) || !Number.isSafeInteger(run.repeat) || run.repeat < 0) throw new Error('Invalid run identity');
+ for (const metric of METRICS) {
+ if (run[metric] === null && run.usage_complete === false && ['input_tokens', 'output_tokens', 'cached_tokens'].includes(metric)) continue;
+ if (!Number.isFinite(run[metric]) || run[metric] < 0) throw new Error(`Invalid metric ${metric}`);
+ }
+ if (![0, 1].includes(run.resolved)) throw new Error('Invalid resolution');
+ const arms = tasks.get(run.instance_id) ?? { baseline: new Map(), ix: new Map() };
+ if (arms[run.arm].has(run.repeat)) throw new Error('Duplicate run');
+ arms[run.arm].set(run.repeat, run); tasks.set(run.instance_id, arms);
+ }
+ if (!tasks.size) throw new Error('No runs');
+ const perTask = [], groups = [];
+ let expectedRepeats;
+ for (const [instance_id, arms] of tasks) {
+ const repeats = [...arms.baseline.keys()].sort((a, b) => a - b);
+ if (!repeats.length || repeats.length !== arms.ix.size || repeats.some((r, i) => r !== i || !arms.ix.has(r))) throw new Error('Unpaired or incomplete arms');
+ expectedRepeats ??= repeats.length;
+ if (repeats.length !== expectedRepeats) throw new Error('Unequal task weighting');
+ const group = { baseline: [...arms.baseline.values()], ix: [...arms.ix.values()] };
+ groups.push(group);
+ perTask.push({ instance_id, metrics: Object.fromEntries(METRICS.map((m) => {
+ const b = group.baseline.map((r) => r[m]), x = group.ix.map((r) => r[m]);
+ const baseline = b.includes(null) ? null : mean(b), ix = x.includes(null) ? null : mean(x);
+ return [m, { baseline, ix, difference: baseline === null || ix === null ? null : ix - baseline }];
+ })) });
+ }
+ const rng = random(seed), metrics = {};
+ for (const metric of METRICS) {
+ const paired = groups.filter((g) => [...g.baseline, ...g.ix].every((r) => r[metric] !== null));
+ const values = (arm, selected = paired) => selected.flatMap((g) => g[arm].map((r) => r[metric]));
+ const bootMean = [], bootMedian = [];
+ for (let i = 0; i < samples && paired.length; i++) {
+ const selected = paired.map(() => paired[Math.floor(rng() * paired.length)]);
+ const b = values('baseline', selected), x = values('ix', selected);
+ bootMean.push(mean(x) - mean(b)); bootMedian.push(median(x) - median(b));
+ }
+ const b = values('baseline'), x = values('ix');
+ metrics[metric] = {
+ coverage: { paired_tasks: paired.length, total_tasks: groups.length, baseline_observed_runs: groups.flatMap((g) => g.baseline).filter((r) => r[metric] !== null).length, ix_observed_runs: groups.flatMap((g) => g.ix).filter((r) => r[metric] !== null).length },
+ baseline: { mean: b.length ? mean(b) : null, median: b.length ? median(b) : null }, ix: { mean: x.length ? mean(x) : null, median: x.length ? median(x) : null },
+ mean_difference: { estimate: b.length ? mean(x) - mean(b) : null, ci90: bootMean.length ? [quantile(bootMean, .05), quantile(bootMean, .95)] : null },
+ median_difference: { estimate: b.length ? median(x) - median(b) : null, ci90: bootMedian.length ? [quantile(bootMedian, .05), quantile(bootMedian, .95)] : null },
+ };
+ }
+ const errorsByArm = { baseline: Object.create(null), ix: Object.create(null) };
+ for (const run of runs) for (const [code, count] of Object.entries(run.ix_errors_by_code ?? {})) errorsByArm[run.arm][code] = (errorsByArm[run.arm][code] ?? 0) + count;
+ return { tasks: tasks.size, repeats: expectedRepeats, bootstrap: { samples, seed, confidence: .90, unit: 'task', difference: 'ix minus baseline' }, metrics, per_task: perTask, ix_errors_by_code: errorsByArm, terminations: Object.fromEntries(['baseline', 'ix'].map((arm) => [arm, runs.filter((r) => r.arm === arm).reduce((counts, r) => { const reason = r.termination ?? 'completed'; counts[reason] = (counts[reason] ?? 0) + 1; return counts; }, {})])) };
+}
+
+export function markdown(report, synthetic = false) {
+ const fmt = (v) => v === null ? 'unavailable' : Number(v.toFixed(3));
+ const diff = (d) => d.ci90 === null ? 'unavailable' : `${fmt(d.estimate)} [${d.ci90.map(fmt).join(', ')}]`;
+ const lines = ['# Agent evaluation', '', synthetic ? '**Synthetic dry run — not product evidence.**' : 'Paired agent evaluation; no causal or product claim is inferred automatically.', '', `${report.tasks} tasks × ${report.repeats} repeats per arm. Differences are ix minus baseline. Percentile 90% CIs resample whole tasks; repeats are clustered.`, '', '| Metric | Baseline mean / median | Ix mean / median | Mean difference [90% CI] | Median difference [90% CI] | Paired tasks used |', '|---|---:|---:|---:|---:|---:|'];
+ for (const [name, m] of Object.entries(report.metrics)) lines.push(`| ${name} | ${fmt(m.baseline.mean)} / ${fmt(m.baseline.median)} | ${fmt(m.ix.mean)} / ${fmt(m.ix.median)} | ${diff(m.mean_difference)} | ${diff(m.median_difference)} | ${m.coverage.paired_tasks}/${m.coverage.total_tasks} |`);
+ lines.push('', 'Resolution is a fraction (1 = resolved). Small sets can have degenerate intervals; these intervals do not cover model drift or environment bias.', '', '## Per-task means and differences', '', '| Task | Metric | Baseline | Ix | Difference |', '|---|---|---:|---:|---:|');
+ for (const task of report.per_task) for (const [metric, m] of Object.entries(task.metrics)) lines.push(`| ${task.instance_id} | ${metric} | ${fmt(m.baseline)} | ${fmt(m.ix)} | ${fmt(m.difference)} |`);
+ lines.push('', 'Missing usage is unavailable, never zero. Per-metric summaries/CIs use complete paired tasks only; missingness can bias usage comparisons. Resolution includes every scheduled task. Interrupted tool/turn counts are observed lower bounds.', '', '## Termination outcomes', '', '```json', JSON.stringify(report.terminations, null, 2), '```');
+ lines.push('', 'Per-task differences are descriptive; uncertainty is reported in the aggregate table.', '', '## Ix errors by code', '', '```json', JSON.stringify(report.ix_errors_by_code, null, 2), '```', '');
+ return lines.join('\n');
+}
diff --git a/bench/agent-eval/stub.mjs b/bench/agent-eval/stub.mjs
new file mode 100644
index 00000000..2f3d1f1f
--- /dev/null
+++ b/bench/agent-eval/stub.mjs
@@ -0,0 +1,20 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { sha256 } from './manifest.mjs';
+
+const [stage, file] = process.argv.slice(2), request = JSON.parse(readFileSync(file, 'utf8'));
+if (!request.synthetic) throw new Error('Stub only accepts explicitly synthetic tasks');
+const ix = request.arm === 'ix';
+if (stage === 'setup') writeFileSync(join(request.repo_path, 'synthetic-environment.txt'), `${request.arm}\n`);
+else if (stage === 'probe') {
+ const evidence = join(request.repo_path, 'synthetic-environment.txt');
+ console.log(JSON.stringify({ version: 1, repo_path: request.repo_path, base_commit: request.task.base_commit, agent_version: request.agent.version, ix_available: ix, mapped: ix, plugin_installed: ix, skills_installed: ix, hooks_enabled: ix, mapped_commit: request.task.base_commit, plugin_revision: request.environment.plugin_revision, evidence: ix ? [{ path: evidence, sha256: sha256(readFileSync(evidence)) }] : [] }));
+} else if (stage === 'agent') {
+ writeFileSync(join(request.repo_path, 'solution.txt'), 'synthetic solution\n');
+ for (const event of [{ type: 'turn', id: 'turn-1' }, { type: 'tool', id: 'tool-1', command: ix ? 'ix locate example' : 'rg example' }, { type: 'usage', input_tokens: ix ? 90 : 100, output_tokens: 20, cached_tokens: 10 }, { type: 'done' }]) console.log(JSON.stringify(event));
+} else if (stage === 'evaluate') {
+ const resolved = readFileSync(join(request.repo_path, 'solution.txt'), 'utf8') === 'synthetic solution\n';
+ console.log(JSON.stringify({ instance_id: request.task.instance_id, resolved, evaluator: 'synthetic' }));
+} else throw new Error('Unknown stub stage');
diff --git a/bench/agent-eval/swebench.mjs b/bench/agent-eval/swebench.mjs
new file mode 100644
index 00000000..cabb949c
--- /dev/null
+++ b/bench/agent-eval/swebench.mjs
@@ -0,0 +1,44 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { execute } from './process.mjs';
+import { sha256 } from './manifest.mjs';
+import { checkResolution, evaluationError } from './evaluation.mjs';
+
+const request = JSON.parse(readFileSync(process.argv[2], 'utf8'));
+if (request.synthetic || request.evaluator.kind !== 'swe-bench') throw new Error('Official evaluator requires real SWE-bench tasks');
+const { evaluator, task, run_path } = request;
+if (!evaluator.harness_path) throw new Error('Set evaluator.harness_path to a pinned local SWE-bench checkout');
+const revision = (await execute(['git', '-C', evaluator.harness_path, 'rev-parse', 'HEAD'], { seconds: 10 })).stdout.trim();
+if (revision !== evaluator.revision) throw new Error('SWE-bench revision mismatch');
+const dirty = await execute(['git', '-C', evaluator.harness_path, 'status', '--porcelain', '--untracked-files=no'], { seconds: 10 });
+if (dirty.stdout) throw new Error('SWE-bench evaluator has tracked modifications');
+const python = evaluator.python ?? 'python';
+const runId = 'agent-eval';
+// Force imports from the pinned checkout rather than a different pip installation.
+await execute([python, '-m', 'swebench.harness.run_evaluation', '--dataset_name', request.dataset_export,
+ '--predictions_path', join(run_path, 'prediction.json'), '--instance_ids', task.instance_id,
+ '--run_id', runId, '--max_workers', '1', '--timeout', String(evaluator.test_seconds ?? 1800)], {
+ cwd: run_path, seconds: evaluator.seconds,
+ env: { ...process.env, PYTHONPATH: evaluator.harness_path }, log: join(run_path, 'official-harness'),
+});
+const instanceLogs = join(run_path, 'logs', 'run_evaluation', runId, 'agent-eval', task.instance_id);
+const patch = readFileSync(join(run_path, 'prediction.patch'), 'utf8');
+let reportPath = join(instanceLogs, 'report.json');
+let reportKind = 'task', failure = {};
+if (!existsSync(reportPath)) {
+ // No task report: the run summary lists the instance as an empty patch or an evaluation error.
+ reportPath = join(run_path, 'agent-eval.agent-eval.json');
+ reportKind = patch === '' ? 'empty-patch-summary' : 'error-summary';
+ if (reportKind === 'error-summary') {
+ const log = readFileSync(join(instanceLogs, 'run_instance.log'), 'utf8');
+ failure = { evaluation_error: evaluationError(log), log_sha256: sha256(log) };
+ }
+}
+const text = readFileSync(reportPath, 'utf8'), report = JSON.parse(text);
+const resolved = reportKind === 'task' ? report[task.instance_id]?.resolved : false;
+if (typeof resolved !== 'boolean') throw new Error('Official report absent or missing resolution');
+const receipt = { instance_id: task.instance_id, resolved, evaluator: 'swe-bench', revision, report_kind: reportKind, report_path: reportPath, report_sha256: sha256(text), ...failure };
+checkResolution(report, receipt, task.instance_id, patch);
+console.log(JSON.stringify(receipt));
diff --git a/bench/agent-eval/test/eval.test.mjs b/bench/agent-eval/test/eval.test.mjs
new file mode 100644
index 00000000..539c7f07
--- /dev/null
+++ b/bench/agent-eval/test/eval.test.mjs
@@ -0,0 +1,1029 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import assert from 'node:assert/strict';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { delimiter, join, normalize, resolve, sep } from 'node:path';
+import { tmpdir } from 'node:os';
+import { fileURLToPath } from 'node:url';
+import { after, test } from 'node:test';
+import { checkManifestSource, importVerified, loadManifest, parseExport, sha256, validateManifest } from '../manifest.mjs';
+import { schedule, validateConfig, validateProbe } from '../config.mjs';
+import { budgetTokens, commandCounts, isIxMcpTool, ixExitScope, parseMetrics, METRICS } from '../metrics.mjs';
+import { markdown, summarize } from '../stats.mjs';
+import { dryConfig, resolveConfigPaths, runBenchmark } from '../run.mjs';
+import { execute } from '../process.mjs';
+import { checkResolution, evaluationError } from '../evaluation.mjs';
+import { armEnvironment, shellQuote } from '../isolation.mjs';
+import { assertMapped, checkLoginShells, checkTaskIsolation, codexSkillListed, integrationFiles } from '../provision.mjs';
+import { CLAUDE_IX_MCP_RULE, HOOK_SCRIPT, MCP_SERVER, PLUGIN_NAME, isHookProcess, nativeArgs } from '../integration.mjs';
+
+const root = fileURLToPath(new URL('../', import.meta.url));
+// Worktree-local scratch also keeps the CI smoke independent of machine config.
+const scratch = mkdtempSync(join(root, 'results-test-'));
+// Run work directories default to os.tmpdir(); failed runs keep theirs, so point it at a private, removed root.
+const workRoot = mkdtempSync(join(tmpdir(), 'agent-eval-tests-'));
+const inheritedTmp = process.env.TMPDIR; process.env.TMPDIR = workRoot;
+after(() => {
+ if (inheritedTmp === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = inheritedTmp;
+ rmSync(scratch, { recursive: true, force: true }); rmSync(workRoot, { recursive: true, force: true });
+});
+const smoke = join(root, 'smoke.json');
+const rows = Array.from({ length: 60 }, (_, i) => ({ instance_id: `fixture__repo-${i}`, repo: `fixture/repo-${i % 6}`, base_commit: sha256(`fixture-${i}`).slice(0, 40), problem_statement: `Synthetic export fixture ${i}`, patch: 'HIDDEN GOLD', test_patch: 'HIDDEN TESTS' }));
+const integrationTest = (name, fn) => test(name, { skip: process.platform === 'win32' || process.env.AGENT_EVAL_PORTABLE_ONLY === '1' }, fn);
+const ndjson = (events) => events.map((e) => JSON.stringify(e)).join('\n');
+
+test('manifest importer pins 50 tasks, covers 5 repos, and is stable across input ordering', () => {
+ const text = JSON.stringify(rows), manifest = importVerified(text);
+ assert.equal(manifest.tasks.length, 50);
+ assert.ok(new Set(manifest.tasks.map((t) => t.repo)).size >= 5);
+ assert.equal(manifest.source_sha256, sha256(text));
+ assert.deepEqual(manifest.tasks, importVerified(JSON.stringify([...rows].reverse())).tasks);
+ assert.deepEqual(manifest.tasks, importVerified(rows.map((r) => JSON.stringify(r)).join('\n')).tasks);
+ assert.ok(!JSON.stringify(manifest).includes('HIDDEN'));
+ const path = join(scratch, 'manifest.json'); writeFileSync(path, JSON.stringify(manifest));
+ assert.deepEqual(loadManifest(path), manifest);
+ assert.equal(importVerified(text, { count: 3, minRepos: 3, seed: 7 }).tasks.length, 3);
+});
+
+test('manifest rejects missing fields, traversal, duplicates and insufficient coverage', () => {
+ for (const field of ['instance_id', 'repo', 'base_commit', 'problem_statement']) {
+ const row = { ...rows[0] }; delete row[field];
+ assert.throws(() => importVerified(JSON.stringify([row]), { count: 1, minRepos: 1 }));
+ }
+ assert.throws(() => importVerified(JSON.stringify([rows[0], rows[0]]), { count: 1, minRepos: 1 }), /duplicate/);
+ assert.throws(() => importVerified(JSON.stringify(rows), { count: 61 }), /Insufficient/);
+ assert.throws(() => importVerified('{}'), /array/);
+ assert.throws(() => importVerified(JSON.stringify(rows), { count: 1, minRepos: 2 }), /coverage/);
+ assert.throws(() => validateManifest({ ...loadManifest(smoke), tasks: [{ ...rows[0], repo: '../repo' }] }), /Invalid repo/);
+ assert.throws(() => validateManifest({ ...loadManifest(smoke), tasks: [{ ...rows[0], instance_id: '..' }] }), /instance_id/);
+});
+
+test('shared arm configuration and randomized schedule are reproducible and balanced', () => {
+ const config = dryConfig(); validateConfig(config, true);
+ assert.throws(() => validateConfig(config), /family/);
+ const invalid = structuredClone(config); invalid.budget.seconds = 0;
+ assert.throws(() => validateConfig(invalid, true), /positive/);
+ const jobs = schedule(rows.slice(0, 3));
+ assert.equal(jobs.length, 12);
+ assert.deepEqual(jobs, schedule(rows.slice(0, 3)));
+ assert.notDeepEqual(jobs, schedule(rows.slice(0, 3), 2, 9));
+ for (const task of rows.slice(0, 3)) for (const repeat of [0, 1]) assert.deepEqual(jobs.filter((j) => j.task === task && j.repeat === repeat).map((j) => j.arm).sort(), ['baseline', 'ix']);
+ const paths = resolveConfigPaths({ agent: { command: ['node', 'bench/agent-eval/agent.mjs'] }, evaluator: { python: 'local/python', harness_path: 'local/harness' } }, scratch);
+ assert.equal(paths.agent.command[1], resolve(scratch, 'bench/agent-eval/agent.mjs'));
+ assert.equal(paths.evaluator.python, resolve(scratch, 'local/python'));
+});
+
+test('the loopback endpoint check applies to every provision.mjs spelling and to any config that routes the ix launcher', () => {
+ const example = JSON.parse(readFileSync(join(root, 'config.example.json'), 'utf8'));
+ example.environment.plugin_revision = 'a'.repeat(40); example.evaluator.revision = 'b'.repeat(40);
+ validateConfig(example);
+ const variant = (environment) => { const c = structuredClone(example); Object.assign(c.environment, environment); return c; };
+ for (const script of ['bench/agent-eval/provision.mjs', 'provision.mjs', './provision.mjs', resolve(root, 'provision.mjs')]) {
+ assert.throws(() => validateConfig(variant({ endpoint: 'https://ix.example.com', setup: ['node', script, 'setup'] })), /loopback/, script);
+ }
+ assert.throws(() => validateConfig(variant({ endpoint: undefined })), /loopback/);
+ // A custom setup still gets the launcher (and IX_ENDPOINT) from ix_cli.
+ const custom = { setup: ['./my-setup.sh'], source_path: undefined, ix_version: undefined };
+ assert.throws(() => validateConfig(variant({ ...custom, endpoint: 'https://ix.example.com' })), /loopback/);
+ assert.throws(() => validateConfig(variant({ ...custom, endpoint: undefined })), /loopback/);
+ validateConfig(variant({ ...custom, ix_cli: undefined, endpoint: undefined }));
+});
+
+test('probe rejects unmapped ix, stale maps, plugin drift and baseline contamination', () => {
+ const request = { arm: 'ix', repo_path: '/fixture/repo', task: rows[0], agent: { version: 'v1' }, environment: { plugin_revision: 'pin' } };
+ const probe = { version: 1, repo_path: request.repo_path, base_commit: rows[0].base_commit, agent_version: 'v1', ix_available: true, mapped: true, plugin_installed: true, skills_installed: true, hooks_enabled: true, mapped_commit: rows[0].base_commit, plugin_revision: 'pin', evidence: [{ path: 'plugin', sha256: 'hash' }] };
+ validateProbe(probe, request);
+ for (const key of ['ix_available', 'mapped', 'plugin_installed', 'skills_installed', 'hooks_enabled']) assert.throws(() => validateProbe({ ...probe, [key]: false }, request), /environment/);
+ assert.throws(() => validateProbe({ ...probe, mapped_commit: 'stale' }, request), /Stale/);
+ assert.throws(() => validateProbe({ ...probe, plugin_revision: 'wrong' }, request), /revision/);
+ assert.throws(() => validateProbe(probe, { ...request, arm: 'baseline' }), /environment/);
+});
+
+test('normalized telemetry deduplicates tool ids and counts direct shell searches and ix errors', () => {
+ assert.deepEqual(commandCounts('echo rg; rg needle | grep x && /bin/find .; env A=b ix locate Foo'), { search_calls: 3, rg_calls: 1, grep_calls: 1, find_calls: 1, ix_calls: 1 });
+ const metrics = parseMetrics(ndjson([{ type: 'turn', id: 'a' }, { type: 'tool', id: 't', command: 'rg foo; ix locate Foo' }, { type: 'tool', id: 't', command: 'rg foo' }, { type: 'ix_error', code: 'STALE_MAP' }, { type: 'usage', input_tokens: 100, output_tokens: 10, cached_tokens: 20 }, { type: 'done' }]), 'normalized');
+ assert.equal(metrics.tool_calls, 1); assert.equal(metrics.search_calls, 1); assert.equal(metrics.ix_calls, 1);
+ assert.deepEqual(metrics.ix_errors_by_code, { STALE_MAP: 1 });
+ assert.throws(() => parseMetrics('{bad}', 'normalized'));
+ assert.throws(() => parseMetrics(ndjson([{ type: 'done' }]), 'normalized'), /Incomplete/);
+ assert.throws(() => parseMetrics(ndjson([{ type: 'turn', id: 'a' }, { type: 'usage', input_tokens: 10, output_tokens: 1 }, { type: 'done' }]), 'normalized'), /cached_tokens/);
+});
+
+test('Claude parses terminal usage including cache creation, deduplicated message ids and ix tool failures', () => {
+ const assistant = { type: 'assistant', message: { id: 'a', content: [{ type: 'tool_use', id: 't', name: 'Bash', input: { command: 'ix locate Foo' } }, { type: 'tool_use', id: 'm', name: 'mcp__ix-memory__locate', input: {} }] } };
+ const metrics = parseMetrics(ndjson([assistant, assistant, { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', is_error: true, content: '{"error":{"code":"UNMAPPED"}}' }] } }, { type: 'result', usage: { input_tokens: 10, output_tokens: 20, cache_read_input_tokens: 30, cache_creation_input_tokens: 40 } }]), 'claude');
+ assert.equal(metrics.input_tokens, 80); assert.equal(metrics.cached_tokens, 30);
+ assert.equal(metrics.turns, 1); assert.equal(metrics.tool_calls, 2); assert.equal(metrics.ix_calls, 2);
+ assert.deepEqual(metrics.ix_errors_by_code, { UNMAPPED: 1 });
+});
+
+test('only a command line that runs hook.mjs counts as an Ix hook process', () => {
+ for (const args of [`${process.execPath} ${HOOK_SCRIPT} claude`, `node ${HOOK_SCRIPT} codex {"type":"agent-turn-complete"}`, `node ${HOOK_SCRIPT}`]) assert.ok(isHookProcess(args), args);
+ for (const args of ['node build.mjs', `node ${HOOK_SCRIPT}x claude`, `node /elsewhere/hook.mjs claude`, `node ${HOOK_SCRIPT.slice(0, -1)}`]) assert.ok(!isHookProcess(args), args);
+});
+
+test('Claude turns count only the main agent: subagent (sidechain) messages do not reach max_turns', () => {
+ const usage = { type: 'result', usage: { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } };
+ const task = { type: 'tool_use', id: 'task', name: 'Task', input: { prompt: 'explore' } };
+ const sub = (id, extra = {}) => ({ type: 'assistant', parent_tool_use_id: 'task', ...extra, message: { id, content: [{ type: 'tool_use', id: `g-${id}`, name: 'Grep', input: {} }] } });
+ const events = [{ type: 'assistant', parent_tool_use_id: null, message: { id: 'main-1', content: [task] } },
+ sub('sub-1'), sub('sub-2'), sub('sub-3', { isSidechain: true }), { type: 'assistant', isSidechain: true, message: { id: 'side-4', content: [] } },
+ { type: 'user', parent_tool_use_id: null, message: { content: [{ type: 'tool_result', tool_use_id: 'task', content: 'found' }] } },
+ { type: 'assistant', message: { id: 'main-2', content: [{ type: 'text', text: 'done' }] } }, usage];
+ const metrics = parseMetrics(ndjson(events), 'claude');
+ assert.equal(metrics.turns, 2, 'only the two main-agent messages are turns');
+ // The subagent's work is still the agent's work: its tool calls and searches count.
+ assert.equal(metrics.tool_calls, 4); assert.equal(metrics.native_search_calls, 3);
+});
+
+test('Claude Ix MCP calls count under both direct and plugin-scoped tool names', () => {
+ for (const name of ['mcp__ix-memory__locate', 'mcp__ix__search', 'mcp__plugin_ix-agent-eval_ix-memory__locate', 'mcp__plugin_ix_ix__explain']) assert.equal(isIxMcpTool(name), true, name);
+ for (const name of ['Bash', 'mcp__github__search', 'mcp__plugin_ix-agent-eval_github__search', 'mcp__plugin_tools_ixl__x', 'mcp__ixl__x']) assert.equal(isIxMcpTool(name), false, name);
+ const tool = { type: 'tool_use', id: 'p', name: 'mcp__plugin_ix-agent-eval_ix-memory__locate', input: {} };
+ const metrics = parseMetrics(ndjson([{ type: 'assistant', message: { id: 'a', content: [tool] } }, { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'p', is_error: true, content: [{ type: 'text', text: '{"error":{"code":"UNMAPPED"}}' }] }] } }, { type: 'result', usage: { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } }]), 'claude');
+ assert.equal(metrics.ix_calls, 1); assert.deepEqual(metrics.ix_errors_by_code, { UNMAPPED: 1 });
+});
+
+test('token ceiling counts uncached input and output, not cache reads', () => {
+ // A long Claude session re-reads its cached context every turn; that must not exhaust the ceiling.
+ assert.equal(budgetTokens({ input_tokens: 250_000, cached_tokens: 240_000, output_tokens: 5_000 }), 15_000);
+ assert.equal(budgetTokens({ input_tokens: 10, cached_tokens: 0, output_tokens: 2 }), 12);
+});
+
+test('example config grants edits and shell; only the ix arm is allowed the Ix MCP server', () => {
+ const { agent, budget } = JSON.parse(readFileSync(join(root, 'config.example.json'), 'utf8'));
+ // Claude --print denies anything that would prompt, so both arms need explicit tool permissions.
+ const argv = (arm) => nativeArgs({ arm, run_path: '/run', agent, budget });
+ const allowed = (args) => args.filter((arg, i) => args[i - 1] === '--allowedTools');
+ assert.deepEqual(allowed(argv('ix')), [`Bash,${CLAUDE_IX_MCP_RULE}`]);
+ assert.deepEqual(allowed(argv('baseline')), ['Bash']);
+ assert.ok(argv('ix').includes('acceptEdits'));
+ // The rule must match the provisioned plugin/server names and the telemetry matcher.
+ assert.equal(CLAUDE_IX_MCP_RULE, `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER}`);
+ assert.ok(isIxMcpTool(`${CLAUDE_IX_MCP_RULE}__locate`));
+ // Keys are platform paths (backslashes on Windows), so look them up with path.join, not POSIX literals.
+ const runPath = resolve('/run'), files = integrationFiles({ agent, run_path: runPath, home: resolve('/home'), environment: { seconds: 1 } });
+ const file = (...parts) => { const text = files[join(runPath, ...parts)]; assert.equal(typeof text, 'string', `missing ${join(...parts)}`); return JSON.parse(text); };
+ assert.deepEqual(Object.keys(file('plugin', '.mcp.json').mcpServers), [MCP_SERVER]);
+ assert.equal(file('plugin', '.claude-plugin', 'plugin.json').name, PLUGIN_NAME);
+ assert.ok(Object.keys(files).every((key) => key === normalize(key) && key.startsWith(join(runPath, 'plugin'))));
+ const ixArgs = argv('ix');
+ assert.equal(normalize(ixArgs[ixArgs.indexOf('--plugin-dir') + 1]), join('/run', 'plugin'));
+ assert.throws(() => integrationFiles({ agent: { family: 'codex' }, run_path: '/run', home: '/home', environment: { seconds: 1 } }), /endpoint/);
+ // Shared args and tool rules cannot grant or override integrations.
+ for (const args of [['--allowedTools', 'Bash'], ['--allowed-tools=Bash'], ['--mcp-config', '{}']]) assert.throws(() => nativeArgs({ arm: 'ix', run_path: '/run', agent: { ...agent, args }, budget }), /override/);
+ assert.throws(() => nativeArgs({ arm: 'baseline', run_path: '/run', agent: { ...agent, allowed_tools: [CLAUDE_IX_MCP_RULE] }, budget }), /MCP/);
+ assert.throws(() => nativeArgs({ arm: 'ix', run_path: '/run', agent: { ...agent, family: 'codex', allowed_tools: ['Bash'] }, budget }), /Claude Code only/);
+ assert.equal(nativeArgs({ arm: 'ix', run_path: '/run', agent: { ...agent, family: 'codex', allowed_tools: [] }, budget }).includes('--allowedTools'), false);
+});
+
+test('Codex skill discovery reads the model-visible skill list from codex debug prompt-input', () => {
+ // Shape recorded from codex-cli 0.162.1 `debug prompt-input` with a skill in $CODEX_HOME/skills (no model call).
+ const prompt = (skills) => JSON.stringify([{ type: 'message', role: 'developer', content: [{ type: 'input_text', text: `<skills_instructions>\n## Skills\n${skills}\n</skills_instructions>` }] }, { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Mention - ix: in prose' }] }]);
+ const installer = '- skill-installer: Install Codex skills into $CODEX_HOME/skills from a curated list. (file: r1/skill-installer/SKILL.md)';
+ assert.equal(codexSkillListed(prompt(`${installer}\n- ix: Answer structural questions about a codebase (file: r0/ix/SKILL.md)`), 'ix'), true);
+ assert.equal(codexSkillListed(prompt(`${installer}\n- ixproj: Fixture (file: r2/ixproj/SKILL.md)`), 'ix'), false);
+ assert.equal(codexSkillListed(prompt(installer), 'ix'), false);
+ assert.throws(() => codexSkillListed('not json', 'ix'));
+});
+
+test('Claude Ix permission denials are reported separately from Ix errors', () => {
+ const tool = { type: 'tool_use', id: 'p', name: `${CLAUDE_IX_MCP_RULE}__locate`, input: {} };
+ const denied = { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'p', is_error: true, content: `Claude requested permissions to use ${CLAUDE_IX_MCP_RULE}__locate, but you haven't granted it yet.` }] } };
+ const result = (extra) => ({ type: 'result', usage: { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }, ...extra });
+ const assistant = { type: 'assistant', message: { id: 'a', content: [tool] } };
+ let metrics = parseMetrics(ndjson([assistant, denied, result({ permission_denials: [{ tool_name: tool.name, tool_use_id: 'p', tool_input: {} }] })]), 'claude');
+ assert.equal(metrics.ix_permission_denials, 1); assert.equal(metrics.ix_errors, 0);
+ metrics = parseMetrics(ndjson([assistant, result({ permission_denials: [{ tool_name: 'Bash', tool_use_id: 'b', tool_input: { command: 'ix locate Foo' } }, { tool_name: 'WebFetch', tool_use_id: 'w', tool_input: {} }] })]), 'claude');
+ assert.equal(metrics.ix_permission_denials, 1);
+ metrics = parseMetrics(ndjson([assistant, result({ permission_denials: [] })]), 'claude');
+ assert.equal(metrics.ix_permission_denials, 0);
+});
+
+test('Codex sums completed turn usage and captures command/MCP errors by code', () => {
+ // One `codex exec` prompt is normally one turn; `turns` counts exec turns, not model requests.
+ const single = parseMetrics(ndjson([{ type: 'thread.started' }, { type: 'turn.started' }, { type: 'item.completed', item: { id: 'a', type: 'command_execution', command: 'rg foo', exit_code: 0 } }, { type: 'item.completed', item: { id: 'b', type: 'file_change' } }, { type: 'turn.completed', usage: { input_tokens: 10, output_tokens: 2, cached_input_tokens: 4 } }]), 'codex');
+ assert.equal(single.turns, 1); assert.equal(single.tool_calls, 2); assert.equal(single.input_tokens, 10);
+ const usage = { type: 'turn.completed', usage: { input_tokens: 100, output_tokens: 20, cached_input_tokens: 50 } };
+ const metrics = parseMetrics(ndjson([{ type: 'turn.started' }, { type: 'item.completed', item: { id: 't', type: 'command_execution', command: 'rg foo; ix locate Foo', exit_code: 1, aggregated_output: '{"error":{"code":"NOT_FOUND"}}' } }, usage, { type: 'turn.started' }, { type: 'item.completed', item: { id: 'm', type: 'mcp_tool_call', server: 'ix-memory', error: { code: 'DOWN' } } }, usage]), 'codex');
+ assert.equal(metrics.input_tokens, 200); assert.equal(metrics.cached_tokens, 100); assert.equal(metrics.turns, 2);
+ assert.equal(metrics.search_calls, 1); assert.equal(metrics.ix_calls, 2);
+ assert.deepEqual(metrics.ix_errors_by_code, { NOT_FOUND: 1, DOWN: 1 });
+ assert.throws(() => parseMetrics(ndjson([{ type: 'turn.started' }, { type: 'turn.failed' }]), 'codex'), /failed/);
+ assert.throws(() => parseMetrics(ndjson([{ type: 'turn.started' }, usage, { type: 'turn.started' }]), 'codex'), /Incomplete/);
+});
+
+test('Ix failures hidden behind a zero exit status still count as failures, not successes', () => {
+ const usage = { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
+ const claude = (command, content) => parseMetrics(ndjson([{ type: 'assistant', message: { id: 'a', content: [{ type: 'tool_use', id: 't', name: 'Bash', input: { command } }] } },
+ { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', is_error: false, content }] } }, { type: 'result', usage }]), 'claude');
+ for (const text of ['sh: 1: ix: not found', 'bash: line 1: ix: command not found', 'zsh: command not found: ix', "env: 'ix': No such file or directory", 'bash: /usr/local/bin/ix: No such file or directory']) {
+ const metrics = claude('ix search foo 2>&1 | head -5', text);
+ assert.equal(metrics.ix_succeeded, 0, text); assert.deepEqual(metrics.ix_errors_by_code, { COMMAND_NOT_FOUND: 1 }, text);
+ }
+ // Ix arm: `--format llm` errors piped through head are still Ix errors; array content is read in full.
+ const piped = claude('ix search foo --format llm 2>&1 | head', [{ type: 'text', text: 'notice' }, { type: 'text', text: 'error code=unmapped message="run ix map"' }]);
+ assert.equal(piped.ix_succeeded, 0); assert.deepEqual(piped.ix_errors_by_code, { unmapped: 1 });
+ const ok = claude('ix search foo | head', 'Foo src/foo.ts:1');
+ // A pipeline's status is head's, so it cannot prove ix ran: not an error, not a confirmed success either.
+ assert.equal(ok.ix_succeeded, 0); assert.equal(ok.ix_errors, 0); assert.equal(ok.ix_calls, 1);
+ const codex = (command, aggregated_output) => parseMetrics(ndjson([{ type: 'turn.started' }, { type: 'item.completed', item: { id: 'c', type: 'command_execution', command, exit_code: 0, aggregated_output } },
+ { type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1, cached_input_tokens: 0 } }]), 'codex');
+ const fallback = codex('bash -lc "ix search foo || rg foo"', 'bash: line 1: ix: command not found\nsrc/foo.ts:1:foo');
+ assert.equal(fallback.ix_succeeded, 0); assert.deepEqual(fallback.ix_errors_by_code, { COMMAND_NOT_FOUND: 1 });
+ assert.equal(codex('bash -lc "ix search foo || rg foo"', 'src/foo.ts:1:foo').ix_succeeded, 0);
+ assert.equal(codex('bash -lc "cd src && ix search foo"', 'Foo src/foo.ts:1').ix_succeeded, 1);
+});
+
+test('only an ix call that certainly ran counts as a success; only a lone ix call owns its exit status', () => {
+ const usage = { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
+ const claude = (command, is_error, content) => parseMetrics(ndjson([{ type: 'assistant', message: { id: 'a', content: [{ type: 'tool_use', id: 't', name: 'Bash', input: { command } }] } },
+ { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', is_error, content }] } }, { type: 'result', usage }]), 'claude');
+ // Baseline probes and fallbacks that exit 0 whether or not ix exists are not isolation leaks.
+ for (const command of ['ix --version 2>/dev/null || echo "no ix"', 'command -v ix || ix search foo', 'rg foo src || ix text foo', 'ls; ix status 2>/dev/null; echo done', 'ix status &', 'ix search foo | head']) {
+ const metrics = claude(command, false, 'no ix');
+ assert.equal(metrics.ix_succeeded, 0, command); assert.equal(metrics.ix_errors, 0, command);
+ }
+ // A lone ix call, or an && chain containing one, that exits 0 proves ix ran.
+ for (const command of ['ix search foo', 'ix search foo 2>&1', 'cd src &&\n ix search foo', 'env A=b ix map && ix search foo > out.txt', '(ix search foo)']) {
+ assert.equal(claude(command, false, 'Foo src/foo.ts:1').ix_succeeded, 1, command);
+ }
+ // A failing compound command is not an Ix error unless its output shows one.
+ for (const command of ['ix map && npm test', 'ix map; npm test', 'cd src && ix search foo']) {
+ const metrics = claude(command, true, '1 failing test');
+ assert.equal(metrics.ix_errors, 0, command); assert.equal(metrics.ix_succeeded, 0, command);
+ }
+ assert.deepEqual(claude('ix map && npm test', true, 'error code=STALE_MAP message="x"').ix_errors_by_code, { STALE_MAP: 1 });
+ assert.deepEqual(claude('ix search foo 2>&1', true, 'boom').ix_errors_by_code, { unknown: 1 });
+ const codex = (command, exit_code) => parseMetrics(ndjson([{ type: 'turn.started' }, { type: 'item.completed', item: { id: 'c', type: 'command_execution', command, exit_code, aggregated_output: 'failed' } },
+ { type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1, cached_input_tokens: 0 } }]), 'codex');
+ assert.equal(codex("/bin/bash -lc 'ix map && npm test'", 1).ix_errors, 0);
+ assert.equal(codex("/bin/bash -lc 'ix search foo'", 1).ix_errors, 1);
+ assert.deepEqual(ixExitScope('ix a; echo $\'x && y\''), { sole: false, confirmed: false });
+ assert.deepEqual(ixExitScope('bash -lc "ix a"'), { sole: true, confirmed: true });
+ assert.deepEqual(ixExitScope('rg x && bash -lc "ix a || true"'), { sole: false, confirmed: false });
+});
+
+test('Claude built-in Grep and Glob calls count as searches; permission denials are counted', () => {
+ const usage = { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
+ const content = [{ type: 'tool_use', id: 'g', name: 'Grep', input: { pattern: 'foo' } }, { type: 'tool_use', id: 'l', name: 'Glob', input: { pattern: '**/*.ts' } }, { type: 'tool_use', id: 'r', name: 'Bash', input: { command: 'rg foo' } }, { type: 'tool_use', id: 'e', name: 'Read', input: { file_path: 'a' } }];
+ const metrics = parseMetrics(ndjson([{ type: 'assistant', message: { id: 'a', content } }, { type: 'result', usage, permission_denials: [{ tool_name: 'WebFetch', tool_use_id: 'w', tool_input: {} }] }]), 'claude');
+ assert.deepEqual([metrics.search_calls, metrics.native_search_calls, metrics.rg_calls, metrics.grep_calls, metrics.find_calls, metrics.tool_calls], [3, 2, 1, 0, 0, 4]);
+ assert.equal(metrics.permission_denials, 1); assert.equal(metrics.ix_permission_denials, 0);
+ assert.ok(METRICS.includes('native_search_calls'));
+});
+
+test('shell telemetry handles ANSI-C quotes and never aborts on an unbalanced quote', () => {
+ assert.equal(commandCounts("echo $'it\\'s'; ix locate A").ix_calls, 1);
+ assert.equal(commandCounts("echo $'a; ix b'").ix_calls, 0);
+ for (const command of ["echo 'unterminated; ix x", 'echo "open', "rg x; echo $'tail"]) assert.doesNotThrow(() => commandCounts(command), command);
+ assert.equal(commandCounts("rg x; echo 'open; ix y").rg_calls, 1);
+ const metrics = parseMetrics(ndjson([{ type: 'assistant', message: { id: 'a', content: [{ type: 'tool_use', id: 't', name: 'Bash', input: { command: "grep -r 'oops" } }] } },
+ { type: 'result', usage: { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } }]), 'claude');
+ assert.equal(metrics.tool_calls, 1); assert.equal(metrics.grep_calls, 1);
+});
+
+function fixtureRuns() {
+ return [0, 1].flatMap((task) => [0, 1].flatMap((repeat) => ['baseline', 'ix'].map((arm) => ({ instance_id: `fixture-${task}`, arm, repeat, ...Object.fromEntries(METRICS.map((m) => [m, m === 'resolved' ? 1 : arm === 'ix' ? task * 2 : 0])) }))));
+}
+test('paired task bootstrap has fixture bounds and rejects duplicate/incomplete repeats', () => {
+ const runs = fixtureRuns(), report = summarize(runs, { samples: 1000, seed: 17 });
+ assert.equal(report.metrics.input_tokens.mean_difference.estimate, 1);
+ assert.deepEqual(report.metrics.input_tokens.mean_difference.ci90, [0, 2]);
+ assert.deepEqual(report.metrics.resolved.mean_difference.ci90, [0, 0]);
+ assert.deepEqual(report, summarize(runs, { samples: 1000, seed: 17 }));
+ assert.equal(report.bootstrap.unit, 'task');
+ assert.match(markdown(report), /90% CI/);
+ assert.throws(() => summarize([...runs, runs[0]]), /Duplicate/);
+ assert.throws(() => summarize(runs.slice(1)), /Unpaired/);
+ assert.throws(() => summarize([{ ...runs[0], input_tokens: NaN }]), /Invalid metric/);
+});
+
+integrationTest('three-task stub dry run executes all stages for both arms and persists reports', async () => {
+ const out = join(scratch, 'smoke');
+ const report = await runBenchmark({ manifestPath: smoke, config: dryConfig(), out, dryRun: true });
+ assert.equal(report.tasks, 3); assert.equal(report.repeats, 2);
+ const runs = readFileSync(join(out, 'runs.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
+ assert.equal(runs.length, 12);
+ assert.ok(runs.every((r) => r.resolved === 1));
+ assert.ok(runs.filter((r) => r.arm === 'baseline').every((r) => r.ix_calls === 0 && r.search_calls === 1));
+ assert.ok(runs.filter((r) => r.arm === 'ix').every((r) => r.ix_calls === 1));
+ assert.deepEqual(report.metrics.input_tokens.mean_difference.ci90, [-10, -10]);
+ assert.match(readFileSync(join(out, 'summary.md'), 'utf8'), /Synthetic dry run/);
+ assert.ok(existsSync(join(out, 'schedule.json')));
+ await assert.rejects(runBenchmark({ manifestPath: smoke, config: dryConfig(), out, dryRun: true }), /already exists/);
+});
+
+integrationTest('CLI dry-run works from the repository root without Docker or a paid agent', () => {
+ const out = join(scratch, 'cli');
+ const stdout = execFileSync(process.execPath, [join(root, 'run.mjs'), '--dry-run', '--out', out], { encoding: 'utf8' });
+ assert.match(stdout, /Completed/); assert.ok(existsSync(join(out, 'summary.md')));
+});
+
+integrationTest('budget exhaustion retains outcomes and completes the comparison report', async () => {
+ const config = dryConfig(); config.budget.max_tokens = 1;
+ const out = join(scratch, 'budget');
+ const report = await runBenchmark({ manifestPath: smoke, config, out, dryRun: true });
+ const runs = readFileSync(join(out, 'runs.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
+ assert.equal(runs.length, 12);
+ assert.ok(runs.every((run) => run.termination === 'token_budget' && run.resolved === 0 && run.official_resolved === 1));
+ assert.ok(runs.every((run) => Number.isFinite(run.hook_seconds)));
+ assert.equal(report.metrics.resolved.baseline.mean, 0);
+ assert.ok(existsSync(join(out, 'summary.md')));
+});
+
+integrationTest('invalid environments still stop loudly without a comparison report', async () => {
+ const badProbe = join(scratch, 'bad-probe.mjs');
+ writeFileSync(badProbe, "console.log(JSON.stringify({version: 1, mapped: false}))\n");
+ const badConfig = dryConfig(); badConfig.environment.probe = [process.execPath, badProbe];
+ await assert.rejects(runBenchmark({ manifestPath: smoke, config: badConfig, out: join(scratch, 'probe'), dryRun: true }), /identity/);
+ await assert.rejects(runBenchmark({ manifestPath: smoke, config: dryConfig(), out: join(scratch, 'wrong-mode') }), /require --dry-run/);
+});
+
+test('subprocess errors and deadlines fail rather than producing partial metrics', async () => {
+ await assert.rejects(execute([process.execPath, '-e', 'process.exit(7)'], { seconds: 2 }), /exited 7/);
+ await assert.rejects(execute([process.execPath, '-e', 'setInterval(() => {}, 1000)'], { seconds: .1 }), /deadline/);
+});
+
+test('empty solutions need explicit official summary evidence, never a guessed failure', () => {
+ const receipt = { report_kind: 'empty-patch-summary', resolved: false };
+ checkResolution({ empty_patch_ids: ['fixture'] }, receipt, 'fixture', '');
+ assert.throws(() => checkResolution({ empty_patch_ids: [] }, receipt, 'fixture', ''), /evidence/);
+ assert.throws(() => checkResolution({ empty_patch_ids: ['fixture'] }, receipt, 'fixture', 'nonempty'), /evidence/);
+ assert.throws(() => checkResolution({}, { resolved: false }, 'fixture', ''), /differs/);
+});
+
+test('patch-apply and test-timeout evaluation errors score unresolved; other errors stay fatal', () => {
+ const receipt = { report_kind: 'error-summary', resolved: false, evaluation_error: 'patch_apply_failed' };
+ checkResolution({ error_ids: ['fixture'] }, receipt, 'fixture', 'diff');
+ assert.throws(() => checkResolution({ error_ids: [] }, receipt, 'fixture', 'diff'), /evidence/);
+ assert.throws(() => checkResolution({ error_ids: ['fixture'] }, receipt, 'fixture', ''), /evidence/);
+ assert.throws(() => checkResolution({ error_ids: ['fixture'] }, { ...receipt, resolved: true }, 'fixture', 'diff'), /evidence/);
+ assert.throws(() => checkResolution({ error_ids: ['fixture'] }, { ...receipt, evaluation_error: 'docker' }, 'fixture', 'diff'), /evidence/);
+ assert.equal(evaluationError('x\n>>>>> Patch Apply Failed:\nerror: corrupt patch'), 'patch_apply_failed');
+ assert.equal(evaluationError('EvaluationError: Evaluation error in fixture: Test timed out after 900 seconds.'), 'test_timeout');
+ assert.throws(() => evaluationError('BuildImageError: docker daemon unavailable'), /inspect the harness logs/);
+});
+
+integrationTest('SWE-bench adapter turns a logged patch-apply error into an unresolved receipt', () => {
+ const harness = join(scratch, 'swe-harness'), python = join(scratch, 'fake-python.cjs');
+ mkdirSync(harness, { recursive: true });
+ // Isolated from developer signing/hooks config, like the other fixtures.
+ const git = (...args) => execFileSync('git', ['-C', harness, ...args], { encoding: 'utf8', env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(scratch, 'no-global-config') } });
+ git('init', '-q'); writeFileSync(join(harness, 'README'), 'fixture');
+ git('add', '.'); git('-c', 'user.name=t', '-c', 'user.email=t@t', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'fixture');
+ const revision = git('rev-parse', 'HEAD').trim();
+ // Mimics the official harness: no task report, the instance listed in error_ids, the cause in run_instance.log.
+ writeFileSync(python, `#!${process.execPath}
+ const { mkdirSync, writeFileSync } = require('node:fs');
+ const id = process.argv[process.argv.indexOf('--instance_ids') + 1], dir = 'logs/run_evaluation/agent-eval/agent-eval/' + id;
+ mkdirSync(dir, { recursive: true }); writeFileSync(dir + '/run_instance.log', process.env.FAKE_INSTANCE_LOG);
+ writeFileSync('agent-eval.agent-eval.json', JSON.stringify({ error_ids: [id], empty_patch_ids: [], resolved_ids: [] }));
+ `.replace(/^\s+/gm, ''), { mode: 0o755 });
+ const evaluate = (name, log) => {
+ const run_path = join(scratch, `swe-${name}`); mkdirSync(run_path, { recursive: true });
+ writeFileSync(join(run_path, 'prediction.patch'), 'diff --git a/x b/x\n');
+ const request = { synthetic: false, dataset_export: 'fixture.json', run_path, task: { instance_id: 'fixture__repo-1' }, evaluator: { kind: 'swe-bench', revision, harness_path: harness, python, seconds: 30 } };
+ writeFileSync(join(run_path, 'request.json'), JSON.stringify(request));
+ return spawnSync(process.execPath, [join(root, 'swebench.mjs'), join(run_path, 'request.json')], { encoding: 'utf8', env: { ...process.env, FAKE_INSTANCE_LOG: log } });
+ };
+ const applied = evaluate('apply', '>>>>> Patch Apply Failed:\npatch: **** malformed patch');
+ assert.equal(applied.status, 0, applied.stderr);
+ const receipt = JSON.parse(applied.stdout);
+ assert.equal(receipt.resolved, false); assert.equal(receipt.report_kind, 'error-summary'); assert.equal(receipt.evaluation_error, 'patch_apply_failed');
+ const docker = evaluate('docker', 'BuildImageError: docker daemon unavailable');
+ assert.notEqual(docker.status, 0); assert.match(docker.stderr, /inspect the harness logs/);
+});
+
+integrationTest('real-run plumbing checks dataset pins and official evidence and includes new solution files', async () => {
+ // All data/evaluation here are synthetic fixtures; this does not exercise Docker.
+ const source = join(scratch, 'source'), cache = join(scratch, 'cache');
+ mkdirSync(source); mkdirSync(cache);
+ const git = (...args) => execFileSync('git', args, { cwd: source, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(scratch, 'no-global-config') } });
+ git('init', '-q'); writeFileSync(join(source, 'source.txt'), 'before\n'); git('add', '.');
+ git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'fixture');
+ const base = git('rev-parse', 'HEAD').trim();
+ git('clone', '--bare', source, join(cache, 'fixture__repo.git'));
+ const exportPath = join(scratch, 'real-fixture-export.json');
+ const text = JSON.stringify([{ ...rows[0], repo: 'fixture/repo', base_commit: base }]);
+ writeFileSync(exportPath, text);
+ const manifestPath = join(scratch, 'real-fixture-manifest.json');
+ writeFileSync(manifestPath, JSON.stringify(importVerified(text, { count: 1, minRepos: 1 })));
+ const adapter = join(scratch, 'fixture-adapter.mjs');
+ const lateWriter = `const [parent, file] = process.argv.slice(1); const wait = () => { try { process.kill(Number(parent), 0); setTimeout(wait, 20); } catch { setTimeout(() => require('node:fs').writeFileSync(file, 'late\\n'), 300); } }; wait();`;
+ writeFileSync(adapter, `
+ import {mkdirSync, readFileSync, writeFileSync} from 'node:fs';
+ import {join} from 'node:path';
+ import {createHash} from 'node:crypto';
+ const [stage,file] = process.argv.slice(2), r = JSON.parse(readFileSync(file, 'utf8'));
+ const hash = text => createHash('sha256').update(text).digest('hex');
+ const ix = r.arm === 'ix', evidence = join(r.home, 'fixture-evidence.json'), OUTS = ${JSON.stringify(['real-fixture', 'bad-official', 'bad-hash'].map((name) => join(scratch, name) + sep))};
+ if(stage === 'setup') {
+ writeFileSync(evidence, '{}'); mkdirSync(join(r.repo_path, '.claude'));
+ writeFileSync(join(r.repo_path, '.claude', 'settings.json'), '{}');
+ } else if(stage === 'probe') console.log(JSON.stringify({version:1, repo_path:r.repo_path, base_commit:r.task.base_commit, agent_version:r.agent.version, ix_available:ix, mapped:ix, plugin_installed:ix, skills_installed:ix, hooks_enabled:ix, mapped_commit:r.task.base_commit, plugin_revision:r.environment.plugin_revision, evidence:ix ? [{path:evidence, sha256:hash('{}')}] : []}));
+ else if(stage === 'agent') {
+ // The solver must not see the gold-patch export, the evaluator config or the output tree with earlier runs.
+ const visible = readFileSync(file, 'utf8') + readFileSync(process.env.AGENT_EVAL_REQUEST, 'utf8') + JSON.stringify(process.env);
+ if (visible.includes(${JSON.stringify(exportPath)}) || OUTS.some((out) => visible.includes(out)) || 'dataset_export' in r || 'evaluator' in r) process.exit(9);
+ writeFileSync(join(r.repo_path, 'source.txt'), 'after\\n'); writeFileSync(join(r.repo_path, 'added.txt'), 'new solution\\n');
+ const {execFileSync} = await import('node:child_process');
+ execFileSync('git', ['add', 'source.txt', 'added.txt']);
+ execFileSync('git', ['-c','user.name=Fixture','-c','[email protected]','-c','commit.gpgsign=false','commit','-qm','agent fix']);
+ for(const e of [{type:'turn',id:'a'}, {type:'tool',id:'t',command:'rg fixture'}, {type:'usage',input_tokens:10,output_tokens:10,cached_tokens:0}, {type:'done'}]) console.log(JSON.stringify(e));
+ // A background process the agent leaves behind: it edits the checkout once the agent has exited.
+ const {spawn} = await import('node:child_process');
+ spawn(process.execPath, ['-e', ${JSON.stringify(lateWriter)}, String(process.pid), join(r.repo_path, 'late.txt')], {stdio: 'ignore'}).unref();
+ } else if(stage === 'evaluate') {
+ if (r.dataset_export !== ${JSON.stringify(exportPath)} || !OUTS.some((out) => r.run_path.startsWith(out))) process.exit(9);
+ const report_path = join(r.run_path,'fixture-official-report.json');
+ const report = JSON.stringify({[r.task.instance_id]:{resolved:true}}); writeFileSync(report_path,report);
+ console.log(JSON.stringify({instance_id:r.task.instance_id,resolved:!r.evaluator.mismatch,evaluator:'swe-bench',revision:r.evaluator.revision,report_path,report_sha256:hash(report)}));
+ }
+ `);
+ const config = dryConfig();
+ config.agent = { ...config.agent, family: 'claude', command: [process.execPath, adapter, 'agent'] };
+ config.environment = { ...config.environment, plugin_revision: base, setup: [process.execPath, adapter, 'setup'], probe: [process.execPath, adapter, 'probe'] };
+ config.evaluator = { ...config.evaluator, kind: 'swe-bench', revision: base, command: [process.execPath, adapter, 'evaluate'] };
+ config.dataset_export = exportPath; config.repo_cache = cache;
+ const out = join(scratch, 'real-fixture');
+ const report = await runBenchmark({ manifestPath, config, out });
+ assert.equal(report.metrics.resolved.baseline.mean, 1);
+ const jobs = JSON.parse(readFileSync(join(out, 'schedule.json'), 'utf8'));
+ const first = jobs[0], runPath = join(out, `0000-${first.instance_id}-${first.repeat}-${first.arm}`);
+ const patch = readFileSync(join(runPath, 'prediction.patch'), 'utf8');
+ assert.match(patch, /source.txt/); assert.match(patch, /added.txt/); assert.doesNotMatch(patch, /settings.json/);
+ // Nothing the agent left running may change the checkout after it exits, in either arm: the recorded patch is the agent's.
+ for (const [index, job] of jobs.entries()) {
+ const recorded = readFileSync(join(out, `${String(index).padStart(4, '0')}-${job.instance_id}-${job.repeat}-${job.arm}`, 'prediction.patch'), 'utf8');
+ assert.match(recorded, /added.txt/); assert.doesNotMatch(recorded, /late.txt/, `${job.arm} patch includes a post-exit write`);
+ }
+ assert.deepEqual(new Set(jobs.map((job) => job.arm)), new Set(['baseline', 'ix']));
+ // Each solver worked outside the output tree, in a work directory removed once its run was recorded.
+ const agentRequest = JSON.parse(readFileSync(join(runPath, 'agent-request.json'), 'utf8'));
+ assert.ok(!agentRequest.run_path.startsWith(out) && !existsSync(agentRequest.run_path));
+ await assert.rejects(runBenchmark({ manifestPath, config: { ...config, work_root: scratch }, out: join(scratch, 'inside-work-root') }), /inside the agent work root/);
+ config.evaluator.mismatch = true;
+ await assert.rejects(runBenchmark({ manifestPath, config, out: join(scratch, 'bad-official') }), /differs from official/);
+ writeFileSync(exportPath, text + '\n');
+ await assert.rejects(runBenchmark({ manifestPath, config, out: join(scratch, 'bad-hash') }), /hash mismatch/);
+});
+
+ test('quoted command examples are not counted as executed Ix calls', () => {
+ for (const cmd of ["echo 'example; ix locate Foo '", 'echo "example && ix locate Foo"', "printf '%s\\n' 'rg a | grep b'", 'echo escaped\\; ixample']) {
+ assert.equal(commandCounts(cmd).ix_calls, 0);
+ assert.equal(commandCounts(cmd).search_calls, 0);
+ }
+ assert.equal(commandCounts('"ix" locate Foo; echo "ix locate Bar"').ix_calls, 1);
+ });
+ test('example real configuration ships its setup and probe adapters', () => {
+ const config = JSON.parse(readFileSync(join(root, 'config.example.json'), 'utf8'));
+ for (const stage of ['setup', 'probe']) assert.ok(existsSync(resolve(root, '../..', config.environment[stage][1])), `missing ${stage}`);
+ });
+
+
+test('quote-aware command counting handles shell wrappers, escapes and comments', () => {
+ assert.equal(commandCounts("/bin/bash -lc 'rg needle; ix locate Foo'").ix_calls, 1);
+ assert.equal(commandCounts("/bin/bash -lc 'echo \"example; ix locate Foo\"'").ix_calls, 0);
+ assert.equal(commandCounts('echo escaped\\;ix locate Foo').ix_calls, 0);
+ assert.equal(commandCounts('# ix locate Foo\nrg needle').rg_calls, 1);
+ assert.equal(commandCounts('echo "a|grep x"; "grep" needle').grep_calls, 1);
+});
+
+test('heredoc bodies are data, not ix or search commands', () => {
+ // A typical agent repro script: Python names like `ix` and lines starting with grep are file content.
+ const repro = "cat > reproduce.py << 'EOF'\nimport numpy as np\nix = np.arange(3)\nprint(ix)\ngrep = \"don't\"\ngrep foo bar\nEOF\npython reproduce.py && rg needle";
+ assert.deepEqual(commandCounts(repro), { search_calls: 1, rg_calls: 1, grep_calls: 0, find_calls: 0, ix_calls: 0 });
+ assert.equal(commandCounts('cat <<-EOF > x\n\tix locate A\n\tEOF\nix locate B').ix_calls, 1);
+ assert.equal(commandCounts('cat <<A <<B\nix 1\nA\nix 2\nB\nix locate C').ix_calls, 1);
+ assert.equal(commandCounts('python - <<EOF\nix\n').ix_calls, 0);
+ assert.equal(commandCounts('cat <<EOF; ix locate same-line\nix body\nEOF').ix_calls, 1);
+ assert.equal(commandCounts('echo a <<< "ix locate x"; ix locate y').ix_calls, 1);
+ assert.equal(commandCounts('bash -lc "cat > f <<EOF\nix bad\nEOF\nix good"').ix_calls, 1);
+ const tool = { type: 'tool_use', id: 'h', name: 'Bash', input: { command: repro } };
+ const metrics = parseMetrics(ndjson([{ type: 'assistant', message: { id: 'a', content: [tool] } }, { type: 'result', usage: { input_tokens: 1, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } }]), 'claude');
+ assert.equal(metrics.ix_calls, 0); assert.equal(metrics.grep_calls, 0);
+});
+
+// Emits a Claude stream-json transcript; the mode argument picks the arm-specific Ix behaviour.
+function claudeTranscriptAgent() {
+ const script = join(scratch, 'claude-transcript-agent.mjs');
+ writeFileSync(script, `
+ import { readFileSync, writeFileSync } from 'node:fs';
+ import { join } from 'node:path';
+ const [mode, file] = process.argv.slice(2), r = JSON.parse(readFileSync(file, 'utf8'));
+ writeFileSync(join(r.repo_path, 'solution.txt'), 'synthetic solution\\n');
+ const bash = { type: 'tool_use', id: 'b', name: 'Bash', input: { command: 'ix locate Foo' } };
+ const mcp = { type: 'tool_use', id: 'm', name: ${JSON.stringify(CLAUDE_IX_MCP_RULE + '__locate')}, input: {} };
+ const events = [], result = { type: 'result', usage: { input_tokens: 10, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } };
+ if (mode === 'denied' && r.arm === 'ix') {
+ events.push({ type: 'assistant', message: { id: 'a', content: [mcp] } });
+ result.permission_denials = [{ tool_name: mcp.name, tool_use_id: 'm', tool_input: {} }];
+ } else if (mode.startsWith('baseline') && r.arm === 'baseline') {
+ events.push({ type: 'assistant', message: { id: 'a', content: [bash] } });
+ const failed = mode === 'baseline-attempt', masked = mode === 'baseline-masked';
+ if (masked) bash.input.command = 'ix locate Foo 2>&1 | head -5';
+ events.push({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'b', is_error: failed, content: failed ? 'bash: ix: command not found' : masked ? 'sh: 1: ix: not found' : 'Foo src/foo.ts:1' }] } });
+ } else events.push({ type: 'assistant', message: { id: 'a', content: [{ type: 'text', text: 'done' }] } });
+ for (const event of [...events, result]) console.log(JSON.stringify(event));
+ `);
+ return (mode) => { const config = dryConfig(); config.agent = { ...config.agent, telemetry: 'claude', command: [process.execPath, script, mode] }; return config; };
+}
+
+integrationTest('an Ix permission denial fails the run; a failed baseline ix attempt does not, a working one does', async () => {
+ const config = claudeTranscriptAgent();
+ await assert.rejects(runBenchmark({ manifestPath: smoke, config: config('denied'), out: join(scratch, 'ix-denied'), dryRun: true }), /denied Ix tools/);
+ const out = join(scratch, 'baseline-attempt');
+ await runBenchmark({ manifestPath: smoke, config: config('baseline-attempt'), out, dryRun: true });
+ const runs = readFileSync(join(out, 'runs.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
+ assert.ok(runs.filter((run) => run.arm === 'baseline').every((run) => run.ix_calls === 1 && run.ix_errors === 1 && run.ix_succeeded === 0));
+ // A pipeline exiting 0 still shows the shell's not-found message; that is an attempt, not a leak.
+ const masked = join(scratch, 'baseline-masked');
+ await runBenchmark({ manifestPath: smoke, config: config('baseline-masked'), out: masked, dryRun: true });
+ const maskedRuns = readFileSync(join(masked, 'runs.jsonl'), 'utf8').trim().split('\n').map(JSON.parse).filter((run) => run.arm === 'baseline');
+ assert.ok(maskedRuns.every((run) => run.ix_succeeded === 0 && run.ix_errors_by_code.COMMAND_NOT_FOUND === 1));
+ await assert.rejects(runBenchmark({ manifestPath: smoke, config: config('baseline-leak'), out: join(scratch, 'baseline-leak'), dryRun: true }), /Baseline ix call succeeded/);
+});
+
+integrationTest('hook-driven Ix calls are reported apart from the agent\'s own Ix calls', async () => {
+ const script = join(scratch, 'hook-agent.mjs');
+ writeFileSync(script, `
+ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
+ import { join } from 'node:path';
+ const r = JSON.parse(readFileSync(process.argv[2], 'utf8'));
+ writeFileSync(join(r.repo_path, 'solution.txt'), 'synthetic solution\\n');
+ if (r.arm === 'ix') for (const hook of [{ type: 'hook', mode: 'claude', ix_calls: 2, seconds: 0.5 }, { type: 'ix_error', code: 'HOOK_FAILED', ix_calls: 1, seconds: 0.25 }]) appendFileSync(join(r.run_path, 'hooks.jsonl'), JSON.stringify(hook) + '\\n');
+ for (const e of [{ type: 'turn', id: 't' }, { type: 'tool', id: 'x', command: r.arm === 'ix' ? 'ix locate A' : 'rg A' }, { type: 'usage', input_tokens: 10, output_tokens: 1, cached_tokens: 0 }, { type: 'done' }]) console.log(JSON.stringify(e));
+ `);
+ const config = dryConfig(); config.agent.command = [process.execPath, script];
+ const out = join(scratch, 'hook-split');
+ const report = await runBenchmark({ manifestPath: smoke, config, out, dryRun: true });
+ const runs = readFileSync(join(out, 'runs.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
+ for (const run of runs.filter((r) => r.arm === 'ix')) assert.deepEqual([run.ix_calls, run.ix_errors, run.hook_ix_calls, run.hook_ix_errors, run.hook_seconds], [1, 0, 3, 1, 0.75]);
+ for (const run of runs.filter((r) => r.arm === 'baseline')) assert.deepEqual([run.ix_calls, run.hook_ix_calls, run.hook_ix_errors], [0, 0, 0]);
+ assert.equal(report.metrics.hook_ix_calls.mean_difference.estimate, 3);
+});
+
+integrationTest('the ix hook re-maps only after the checkout changed; the probe always maps', async () => {
+ const run_path = join(scratch, 'hook-refresh'), repo_path = join(run_path, 'repo'), home = join(run_path, 'home'), log = join(run_path, 'ix.log');
+ mkdirSync(repo_path, { recursive: true }); mkdirSync(home);
+ const git = (...args) => execFileSync('git', ['-C', repo_path, ...args], { encoding: 'utf8' });
+ git('init', '-q'); writeFileSync(join(repo_path, 'a.txt'), 'a\n'); git('add', '.');
+ git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'fixture');
+ const fakeIx = join(run_path, 'fake-ix.mjs');
+ writeFileSync(fakeIx, `import { appendFileSync } from 'node:fs'; appendFileSync(${JSON.stringify(log)}, process.argv[2] + '\\n'); if (process.argv[2] === 'hook') console.log('{}');`);
+ const request = { arm: 'ix', run_path, repo_path, home, environment: { seconds: 10, ix_cli: fakeIx, endpoint: 'http://127.0.0.1:8090', tool_paths: ['/usr/bin', '/bin'] } };
+ const env = armEnvironment(request); writeFileSync(env.AGENT_EVAL_REQUEST, JSON.stringify(request));
+ const hook = async (mode) => {
+ writeFileSync(log, '');
+ await execute([process.execPath, join(root, 'hook.mjs'), mode], { cwd: repo_path, env, input: '{}' });
+ return readFileSync(log, 'utf8').trim().split('\n');
+ };
+ assert.deepEqual(await hook('probe'), ['map']);
+ assert.deepEqual(await hook('claude'), ['hook'], 'a read-only call on the probed checkout does not map');
+ writeFileSync(join(repo_path, 'a.txt'), 'b\n');
+ assert.deepEqual(await hook('claude'), ['map', 'hook']);
+ assert.deepEqual(await hook('claude'), ['hook']);
+ writeFileSync(join(repo_path, 'new.txt'), 'new\n');
+ assert.deepEqual(await hook('claude'), ['map', 'hook'], 'a new untracked file maps');
+ assert.deepEqual(await hook('claude'), ['hook']);
+ writeFileSync(join(repo_path, 'new.txt'), 'changed again\n');
+ assert.deepEqual(await hook('claude'), ['map', 'hook'], 'an edited untracked file maps');
+ assert.deepEqual(await hook('probe'), ['map'], 'the probe maps even when nothing changed');
+ const records = readFileSync(join(run_path, 'hooks.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line));
+ assert.deepEqual(records.map((r) => [r.mapped, r.ix_calls]), [[true, 1], [false, 1], [true, 2], [false, 1], [true, 2], [false, 1], [true, 2], [true, 1]]);
+});
+
+integrationTest('the probe fails when a login shell profile resets PATH and undoes arm isolation', async () => {
+ const dir = join(scratch, 'login-shell'), ambient = join(dir, 'ambient'), keeps = join(dir, 'keeps'), resets = join(dir, 'resets'), broken = join(dir, 'broken');
+ for (const d of [ambient, keeps, resets, broken]) mkdirSync(d, { recursive: true });
+ writeFileSync(join(ambient, 'ix'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ // Stand-ins for `bash -l`: one keeps the inherited PATH, one resets it the way a distro /etc/profile can.
+ writeFileSync(join(keeps, 'bash'), '#!/bin/sh\n[ "$1" = -lc ] || exit 2\necho "profile banner"\nexec /bin/sh -c "$2"\n', { mode: 0o755 });
+ writeFileSync(join(resets, 'bash'), `#!/bin/sh\n[ "$1" = -lc ] || exit 2\nPATH=${shellQuote(ambient)}:/usr/bin:/bin; export PATH\nexec /bin/sh -c "$2"\n`, { mode: 0o755 });
+ copyFileSync(join(resets, 'bash'), join(resets, 'zsh'));
+ // Stand-in for a profile.d script written for another shell, as dash reports it.
+ const failing = '#!/bin/sh\necho \'profile.d/tool.sh: 5: eval: Syntax error: "(" unexpected\' >&2\nexit 2\n';
+ for (const name of ['bash', 'sh']) writeFileSync(join(broken, name), failing, { mode: 0o755 });
+ for (const arm of ['baseline', 'ix']) {
+ const run_path = join(dir, arm), bin = join(run_path, 'bin'); mkdirSync(bin, { recursive: true });
+ if (arm === 'ix') writeFileSync(join(bin, 'ix'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ const request = { arm, run_path, repo_path: dir, environment: { seconds: 10 } };
+ // The shells are found on the arm's PATH, as in a run; SHELL is unset so only `bash` is checked.
+ const env = (shells) => ({ ...process.env, SHELL: '', PATH: [bin, shells].join(delimiter) });
+ await checkLoginShells(request, env(keeps));
+ await assert.rejects(checkLoginShells(request, env(resets)), /login shell .*resets PATH/, arm);
+ // Claude Code only runs bash or zsh: a $SHELL of zsh is probed, while sh (whose profile may not even parse) is not.
+ await assert.rejects(checkLoginShells(request, { ...env(keeps), SHELL: join(resets, 'zsh') }), /zsh -l\) resolves ix/, arm);
+ await checkLoginShells(request, { ...env(keeps), SHELL: join(broken, 'sh') });
+ // A profile that fails under the arm's PATH reports the shell's own error instead of a bare exit status.
+ await assert.rejects(checkLoginShells(request, env(broken)), /bash -l\) exited 2 .*eval: Syntax error/, arm);
+ }
+});
+
+// The adapter spawns a descendant (same process group, like a Codex notify hook) and exits at once. The descendant
+// waits for the adapter to exit, then `ms`, then writes `file`. Timing is relative to the adapter's exit rather than
+// to process start-up, so a loaded machine (the full CI suite runs alongside) does not change the outcome.
+// The descendant's command line ends with `tag`; `keep` matches the hook-fixture tag, as isHookProcess matches hook.mjs.
+const lateDescendant = (file, ms, stdio = 'ignore', tag = 'hook-fixture') => {
+ const child = `const parent = Number(process.argv[1]); const wait = () => { try { process.kill(parent, 0); setTimeout(wait, 20); } catch { setTimeout(() => { console.log('hook'); require('node:fs').writeFileSync(${JSON.stringify(file)}, 'x'); }, ${ms}); } }; wait();`;
+ return [process.execPath, '-e', `require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(child)}, String(process.pid), ${JSON.stringify(tag)}], { stdio: ${JSON.stringify(stdio)} }).unref(); console.log('agent')`];
+};
+const keep = (args) => args.endsWith(' hook-fixture');
+const timed = async (promise) => { const started = performance.now(); const result = await promise; return { result, seconds: (performance.now() - started) / 1000 }; };
+
+integrationTest('a drained stage lets an outliving descendant finish before the group is reaped, within a cap', async () => {
+ const marker = (name) => join(scratch, `drain-${name}`);
+ const drained = await timed(execute(lateDescendant(marker('drained'), 1000), { seconds: 10, drainSeconds: 10, keep }));
+ assert.ok(existsSync(marker('drained')));
+ // The descendant finished at least 1s after the adapter exited; none of that is stage time.
+ assert.ok(drained.seconds - drained.result.seconds >= 0.5, 'stage time excludes the drain');
+ await execute(lateDescendant(marker('reaped'), 1000), { seconds: 10 });
+ await new Promise((done) => setTimeout(done, 2000));
+ assert.ok(!existsSync(marker('reaped')), 'without a drain, descendants are still reaped');
+ const capped = await timed(execute(lateDescendant(marker('capped'), 30_000), { seconds: 10, drainSeconds: 0.5, keep }));
+ assert.ok(capped.seconds < 15, 'the drain is capped');
+ assert.ok(!existsSync(marker('capped')));
+});
+
+integrationTest('only kept (hook) processes and their children outlive the adapter; anything else is killed at its exit', async () => {
+ const marker = (name) => join(scratch, `cut-${name}`);
+ // A leftover that is not a hook gets no drain, even when the stage drains for hooks.
+ const other = await timed(execute(lateDescendant(marker('other'), 300, 'ignore', 'agent-leftover'), { seconds: 10, drainSeconds: 10, keep }));
+ assert.ok(other.seconds < 5, 'nothing kept, so no drain');
+ await new Promise((done) => setTimeout(done, 1000));
+ assert.ok(!existsSync(marker('other')), 'a non-hook leftover never writes after the adapter exits');
+ // One adapter leaves a hook (whose own child does the work, like the hook's `ix map`) and a leftover beside it.
+ const grandchild = `setTimeout(() => require('node:fs').writeFileSync(process.argv[1], 'x'), 300)`;
+ const hook = `const parent = Number(process.argv[1]); const wait = () => { try { process.kill(parent, 0); setTimeout(wait, 20); } catch { require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(grandchild)}, ${JSON.stringify(marker('hook-child'))}], { stdio: 'ignore' }); } }; wait();`;
+ const leftover = `const parent = Number(process.argv[1]); const wait = () => { try { process.kill(parent, 0); setTimeout(wait, 20); } catch { setTimeout(() => require('node:fs').writeFileSync(${JSON.stringify(marker('leftover'))}, 'x'), 300); } }; wait();`;
+ const spawnBoth = `const { spawn } = require('node:child_process');
+ spawn(process.execPath, ['-e', ${JSON.stringify(hook)}, String(process.pid), 'hook-fixture'], { stdio: 'ignore' }).unref();
+ spawn(process.execPath, ['-e', ${JSON.stringify(leftover)}, String(process.pid), 'agent-leftover'], { stdio: 'ignore' }).unref();`;
+ await execute([process.execPath, '-e', spawnBoth], { seconds: 10, drainSeconds: 10, keep });
+ await new Promise((done) => setTimeout(done, 1000));
+ assert.ok(existsSync(marker('hook-child')), 'the hook and the child it starts run to completion');
+ assert.ok(!existsSync(marker('leftover')), 'the leftover beside the hook was killed at the adapter exit');
+});
+
+integrationTest('a descendant holding the stage stdout open is neither stage time nor a deadline overrun', async () => {
+ const marker = (name) => join(scratch, `inherit-${name}`);
+ // Like a notify hook spawned with inherited stdio: the adapter exits, the hook keeps the stdout pipe open past the deadline.
+ const drained = await execute(lateDescendant(marker('drained'), 2500, 'inherit'), { seconds: 2, drainSeconds: 10, allowTimeout: true, keep });
+ assert.equal(drained.timed_out, false); assert.ok(drained.seconds < 2, 'stage time ends when the adapter exits');
+ assert.ok(existsSync(marker('drained'))); assert.match(drained.stdout, /agent/);
+ // The descendant would hold stdout for 6s after the adapter exits; the stage closing well before that means it was reaped.
+ const reaped = await timed(execute(lateDescendant(marker('reaped'), 6000, 'inherit'), { seconds: 10, drainSeconds: 0.5, keep }));
+ assert.equal(reaped.result.timed_out, false); assert.ok(reaped.seconds - reaped.result.seconds < 4, 'the drain is capped');
+ assert.match(reaped.result.stdout, /agent/); assert.doesNotMatch(reaped.result.stdout, /hook/, 'the descendant is reaped when the drain ends');
+});
+
+integrationTest('an ix-arm hook that outlives the agent is counted; one killed mid-run fails the run', async () => {
+ const script = join(scratch, 'late-hook-agent.mjs'), leftovers = join(scratch, 'late-hook-leftovers');
+ mkdirSync(leftovers);
+ writeFileSync(script, `
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+ import { join } from 'node:path';
+ import { spawn } from 'node:child_process';
+ const [mode, file] = process.argv.slice(2), r = JSON.parse(readFileSync(file, 'utf8'));
+ writeFileSync(join(r.repo_path, 'solution.txt'), 'synthetic solution\\n');
+ if (r.arm === 'ix' && mode === 'late') {
+ const record = JSON.stringify({ type: 'hook', mode: 'codex', ix_calls: 1, seconds: 0.5 }) + '\\n';
+ // The command line names hook.mjs, as a real hook's does; that is what lets it outlive the agent.
+ spawn(process.execPath, ['-e', 'setTimeout(() => require("node:fs").appendFileSync(process.argv[1], process.argv[2]), 500)', join(r.run_path, 'hooks.jsonl'), record, ${JSON.stringify(HOOK_SCRIPT)}], { stdio: 'ignore' }).unref();
+ }
+ // In both arms, a leftover that is not a hook must be gone by the time the drain ends.
+ if (mode === 'late') spawn(process.execPath, ['-e', 'setTimeout(() => require("node:fs").writeFileSync(process.argv[1], "x"), 500)', join(${JSON.stringify(leftovers)}, r.arm + '-' + r.repeat)], { stdio: 'ignore' }).unref();
+ if (r.arm === 'ix' && mode === 'killed') { mkdirSync(join(r.run_path, 'hooks.pending'), { recursive: true }); writeFileSync(join(r.run_path, 'hooks.pending', '1'), 'codex'); }
+ for (const e of [{ type: 'turn', id: 't' }, { type: 'usage', input_tokens: 10, output_tokens: 1, cached_tokens: 0 }, { type: 'done' }]) console.log(JSON.stringify(e));
+ `);
+ const config = (mode) => { const c = dryConfig(); c.repeats = 1; c.agent.command = [process.execPath, script, mode]; return c; };
+ const out = join(scratch, 'late-hook');
+ await runBenchmark({ manifestPath: smoke, config: config('late'), out, dryRun: true });
+ const runs = readFileSync(join(out, 'runs.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
+ assert.ok(runs.filter((r) => r.arm === 'ix').every((r) => r.hook_ix_calls === 1));
+ await new Promise((done) => setTimeout(done, 1000));
+ assert.deepEqual(readdirSync(leftovers), [], 'non-hook leftovers were killed at agent exit in both arms');
+ await assert.rejects(runBenchmark({ manifestPath: smoke, config: config('killed'), out: join(scratch, 'killed-hook'), dryRun: true }), /hook was still running/);
+});
+
+integrationTest('agent.mjs gives each Claude arm its own --allowedTools through the native binary', async () => {
+ const fake = join(scratch, 'fake-claude.cjs');
+ writeFileSync(fake, `#!${process.execPath}
+ const { writeFileSync } = require('node:fs');
+ if (process.argv[2] === '--version') console.log('9.9.9-fixture (Claude Code)');
+ else { writeFileSync(process.env.FAKE_CLAUDE_ARGV, JSON.stringify(process.argv.slice(2))); process.stdin.resume(); }
+ `.replace(/^\s+/gm, ''), { mode: 0o755 });
+ const argv = {};
+ for (const arm of ['baseline', 'ix']) {
+ const run_path = join(scratch, `allowed-${arm}`); mkdirSync(run_path, { recursive: true });
+ const request = { arm, run_path, task: { problem_statement: 'fixture' }, budget: { max_turns: 3 },
+ agent: { family: 'claude', binary: fake, version: '9.9.9-fixture', model: 'fixture-model', effort: 'medium', args: ['--permission-mode', 'acceptEdits'], allowed_tools: ['Bash'] } };
+ writeFileSync(join(run_path, 'request.json'), JSON.stringify(request));
+ const out = join(run_path, 'argv.json');
+ await execute([process.execPath, join(root, 'agent.mjs'), join(run_path, 'request.json')], { env: { ...process.env, FAKE_CLAUDE_ARGV: out }, seconds: 20 });
+ argv[arm] = JSON.parse(readFileSync(out, 'utf8'));
+ }
+ const allowed = (args) => args.filter((arg, i) => args[i - 1] === '--allowedTools');
+ assert.deepEqual(allowed(argv.ix), [`Bash,${CLAUDE_IX_MCP_RULE}`]);
+ assert.deepEqual(allowed(argv.baseline), ['Bash']);
+ assert.ok(argv.ix.includes('--plugin-dir') && !argv.baseline.includes('--plugin-dir'));
+ assert.ok(argv.baseline.includes('--strict-mcp-config'));
+});
+
+test('mapping probe rejects successful-but-empty, stale and partial maps', () => {
+ const status = { graphCompleted: true, mapCompleted: true, staleFiles: 0, graphHealth: { status: 'ok' } };
+ const stats = { nodes: { total: 3 } };
+ assertMapped(status, stats);
+ for (const patch of [{ graphCompleted: false }, { mapCompleted: null }, { staleFiles: 1 }, { graphHealth: { status: 'empty' } }, { replayedFiles: ['file.py'] }, { parseTimeouts: ['file.py'] }]) {
+ assert.throws(() => assertMapped({ ...status, ...patch }, stats), /unmapped/);
+ }
+ assert.throws(() => assertMapped(status, { nodes: { total: 0 } }), /unmapped/);
+});
+
+integrationTest('shipped provisioner installs pinned local integrations and isolates PATH in both native arms', async () => {
+ const source = join(scratch, 'ix-source'); mkdirSync(source);
+ const git = (...args) => execFileSync('git', args, { cwd: source, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(scratch, 'absent-config') } });
+ git('init', '-q'); mkdirSync(join(source, 'skills', 'ix'), { recursive: true });
+ writeFileSync(join(source, 'skills', 'ix', 'SKILL.md'), '---\nname: ix\ndescription: Fixture\n---\nPinned skill\n');
+ git('add', '.'); git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'fixture');
+ const revision = git('rev-parse', 'HEAD').trim();
+ const tools = join(scratch, 'ambient-bin'); mkdirSync(tools);
+ writeFileSync(join(tools, 'ix'), '#!/bin/sh\nexit 99\n', { mode: 0o755 });
+ // A profile-free `bash -l`: the host's /etc/profile is not under test here (the login-shell probe test covers profiles).
+ writeFileSync(join(tools, 'bash'), '#!/bin/sh\n[ "$1" = -lc ] && exec /bin/sh -c "$2"\nexec /bin/bash "$@"\n', { mode: 0o755 });
+ // execute() reports only the exit status; the provisioner's own message on stderr is the diagnosis.
+ const stage = async (argv, options) => {
+ const result = await execute(argv, { ...options, captureExit: true });
+ assert.equal(result.exit_code, 0, `${argv.slice(1, 3).join(' ')} exited ${result.exit_code}: ${result.stderr.trim() || 'no stderr'}`);
+ return result;
+ };
+ const fakeIx = join(scratch, 'fake-ix.mjs');
+ writeFileSync(fakeIx, `
+ import {existsSync,mkdirSync,writeFileSync} from 'node:fs';
+ import {join} from 'node:path';
+ const [cmd] = process.argv.slice(2), marker = join(process.env.IX_HOME,'mapped');
+ if(cmd==='--version') console.log('ix 1.0-fixture');
+ else if(cmd==='map') { mkdirSync(process.env.IX_HOME,{recursive:true}); writeFileSync(marker,process.cwd()); }
+ else if(cmd==='status') console.log(JSON.stringify({graphCompleted:existsSync(marker),mapCompleted:existsSync(marker),staleFiles:0,graphHealth:{status:'ok'}}));
+ else if(cmd==='stats') console.log(JSON.stringify({nodes:{total:existsSync(marker)?10:0}}));
+ else if(cmd==='hook') console.log('{}');
+ else process.exitCode=1;
+ `);
+ const fakeAgent = join(scratch, 'fake-native');
+ writeFileSync(fakeAgent, `#!${process.execPath}
+ import {existsSync,readdirSync,readFileSync,writeFileSync} from 'node:fs';
+ import {join} from 'node:path';
+ import {execFileSync} from 'node:child_process';
+ if(process.argv[2]==='--version') console.log('agent 1.0-fixture');
+ else if(process.argv[2]==='debug') {
+ // Mirrors codex debug prompt-input: the model-visible skill list for $CODEX_HOME/skills.
+ const dir=join(process.env.CODEX_HOME,'skills');
+ const skills=process.env.FAKE_CODEX_HIDE_SKILLS||!existsSync(dir)?[]:readdirSync(dir).map((name)=>'- '+readFileSync(join(dir,name,'SKILL.md'),'utf8').match(/^name: (.*)$/m)[1]+': Fixture (file: r0/'+name+'/SKILL.md)');
+ console.log(JSON.stringify([{type:'message',role:'developer',content:[{type:'input_text',text:'<skills_instructions>\\n'+skills.join('\\n')+'\\n</skills_instructions>'}]}]));
+ }
+ else {
+ const r=JSON.parse(readFileSync(process.env.AGENT_EVAL_REQUEST,'utf8'));
+ const args=process.argv.slice(2); writeFileSync(join(r.run_path,'native-args.json'),JSON.stringify(args));
+ if(r.arm==='ix') {
+ if(r.agent.family==='claude') {
+ const plugin=args[args.indexOf('--plugin-dir')+1];
+ const hooks=JSON.parse(readFileSync(join(plugin,'hooks','hooks.json'),'utf8'));
+ execFileSync('sh',['-c',hooks.hooks.PostToolUse[0].hooks[0].command],{input:'{}'});
+ } else {
+ const config=readFileSync(join(process.env.CODEX_HOME,'config.toml'),'utf8');
+ const notify=JSON.parse(config.split('\\n')[0].slice('notify = '.length));
+ execFileSync(notify[0],[...notify.slice(1),JSON.stringify({type:'agent-turn-complete'})]);
+ }
+ }
+ for(const e of [{type:'turn',id:'a'},{type:'usage',input_tokens:10,output_tokens:2,cached_tokens:0},{type:'done'}]) console.log(JSON.stringify(e));
+ }
+ `, { mode: 0o755 });
+ for (const family of ['claude', 'codex']) for (const arm of ['baseline', 'ix']) {
+ const run_path = join(scratch, `provision-${family}-${arm}`), repo_path = join(run_path, 'repo'), home = join(run_path, 'home');
+ mkdirSync(home, { recursive: true });
+ execFileSync('git', ['clone', '-q', source, repo_path]);
+ // This repository's skill is inert until installed in the agent-specific location.
+ const request = { synthetic: true, arm, run_path, repo_path, home, task: { base_commit: revision, problem_statement: 'fixture' }, agent: { family, binary: fakeAgent, version: '1.0-fixture', model: 'fixture-model', effort: 'medium' }, budget: { max_turns: 2 },
+ environment: { plugin_revision: revision, source_path: source, ix_cli: fakeIx, ix_version: '1.0-fixture', endpoint: 'http://127.0.0.1:8090', seconds: 10, tool_paths: [tools, '/usr/bin', '/bin'] } };
+ assert.throws(() => checkTaskIsolation({ ...request, synthetic: false }), (error) => /ancestor/.test(error.message) && error.message.includes(resolve(root, '..', '..')));
+ // SHELL is cleared so the outcome does not depend on the caller's login shell; `bash -l` is the profile-free stand-in.
+ const env = armEnvironment(request, { ...process.env, SHELL: '', IX_ENDPOINT: 'http://wrong.invalid', IX_WORKSPACE_ID: 'wrong', JARVIS_IX_SOCKET: 'wrong',
+ CLAUDE_CODE_OAUTH_TOKEN: 'fixture-not-a-token', CLAUDE_CODE_USE_BEDROCK: '1', CLAUDE_CODE_ENTRYPOINT: 'parent-session' });
+ assert.equal(env.IX_WORKSPACE_ID, undefined); assert.equal(env.JARVIS_IX_SOCKET, undefined);
+ // Native CLI auth/provider routing survives isolation in both arms; parent-session variables do not.
+ assert.equal(env.CLAUDE_CODE_OAUTH_TOKEN, 'fixture-not-a-token'); assert.equal(env.CLAUDE_CODE_USE_BEDROCK, '1'); assert.equal(env.CLAUDE_CODE_ENTRYPOINT, undefined);
+ assert.equal(env.IX_ENDPOINT, arm === 'ix' ? request.environment.endpoint : undefined);
+ const requestPath = join(run_path, 'request.json'); writeFileSync(requestPath, JSON.stringify(request));
+ const provision = join(root, 'provision.mjs');
+ await stage([process.execPath, provision, 'setup', requestPath], { cwd: repo_path, env });
+ const result = JSON.parse((await stage([process.execPath, provision, 'probe', requestPath], { cwd: repo_path, env })).stdout);
+ validateProbe(result, request);
+ const transcript = await stage([process.execPath, join(root, 'agent.mjs'), requestPath], { cwd: repo_path, env });
+ assert.equal(parseMetrics(transcript.stdout, 'normalized').turns, 1);
+ const args = JSON.parse(readFileSync(join(run_path, 'native-args.json'), 'utf8'));
+ assert.ok(args.includes('fixture-model'));
+ if (family === 'claude') assert.equal(args.includes('--plugin-dir'), arm === 'ix');
+ if (arm === 'baseline') {
+ await assert.rejects(execute(['ix', '--version'], { env }), /ENOENT/);
+ writeFileSync(join(repo_path, 'AGENTS.md'), 'ambient instructions');
+ await assert.rejects(execute([process.execPath, provision, 'probe', requestPath], { env }), /exited/);
+ } else {
+ for (const evidence of result.evidence) assert.equal(sha256(readFileSync(evidence.path)), evidence.sha256);
+ const files = integrationFiles(request), first = Object.keys(files)[0];
+ assert.deepEqual(readdirSync(join(run_path, 'hooks.pending')), []); // The probe's hook finished and cleared its marker.
+ if (family === 'codex') {
+ // Skills install where the product installer puts them, never into the task checkout.
+ assert.ok(existsSync(join(home, '.codex', 'skills', 'ix', 'SKILL.md'))); assert.ok(!existsSync(join(repo_path, '.agents')));
+ const log = join(run_path, 'hidden-skill-probe');
+ await assert.rejects(execute([process.execPath, provision, 'probe', requestPath], { env: { ...env, FAKE_CODEX_HIDE_SKILLS: '1' }, log }), /exited/);
+ assert.match(readFileSync(`${log}.stderr`, 'utf8'), /does not list the installed Ix skill/);
+ }
+ if (family === 'codex') assert.ok(files[join(home, '.codex', 'config.toml')].endsWith('[mcp_servers.ix-memory]\ncommand = "ix"\nargs = ["mcp"]\nenv = { IX_ENDPOINT = "http://127.0.0.1:8090" }\n'));
+ if (family === 'claude') {
+ const hooks = JSON.parse(files[join(run_path, 'plugin', 'hooks', 'hooks.json')]).hooks.PostToolUse[0].hooks[0];
+ assert.equal(hooks.timeout, 2 * request.environment.seconds + 30); // Outlasts both ix stage deadlines.
+ }
+ writeFileSync(first, 'tampered');
+ await assert.rejects(execute([process.execPath, provision, 'probe', requestPath], { env }), /exited/);
+ writeFileSync(first, files[first]);
+ rmSync(join(home, '.ix', 'mapped'));
+ // Direct assertMapped also covers map failures that return exit 0.
+ assert.ok(readFileSync(join(run_path, 'hooks.jsonl'), 'utf8').includes('probe'));
+ }
+ }
+ writeFileSync(join(source, 'skills', 'ix', 'SKILL.md'), 'drifted');
+ const r = join(scratch, 'provision-claude-ix', 'request.json');
+ await assert.rejects(execute([process.execPath, join(root, 'provision.mjs'), 'probe', r], { env: { ...process.env, PATH: join(scratch, 'provision-claude-ix', 'bin') } }), /exited/);
+});
+
+test('manifest pins agree with the hash-verified source export', () => {
+ const text = JSON.stringify(rows), manifest = importVerified(text);
+ checkManifestSource(manifest, text);
+ // The official evaluator picks its parser by extension, so a named export must match its format.
+ const jsonl = rows.map((row) => JSON.stringify(row)).join('\n');
+ assert.equal(parseExport(text, 'local/verified.json').length, rows.length);
+ assert.equal(parseExport(jsonl, 'local/verified.jsonl').length, rows.length);
+ assert.throws(() => parseExport(jsonl, 'local/verified.json'), /JSONL export must be named \*\.jsonl/);
+ assert.throws(() => checkManifestSource(manifest, text, 'local/verified.jsonl'), /JSON array export must be named \*\.json/);
+ assert.throws(() => importVerified(jsonl, { path: 'local/verified.json' }), /\.jsonl/);
+ for (const field of ['repo', 'base_commit', 'problem_statement']) {
+ const changed = structuredClone(manifest); changed.tasks[0][field] = 'drifted';
+ assert.throws(() => checkManifestSource(changed, text), /differs from source/);
+ }
+});
+
+test('native Ix failures retain JSON and LLM error codes', () => {
+ const metrics = parseMetrics(ndjson([{ type: 'turn.started' }, { type: 'item.completed', item: { id: 'i', type: 'command_execution', command: 'ix stats', exit_code: 1, aggregated_output: 'error code=backend_error message="unavailable"' } }, { type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1, cached_input_tokens: 0 } }]), 'codex');
+ assert.deepEqual(metrics.ix_errors_by_code, { backend_error: 1 });
+});
+
+
+test('portable subset retains unit coverage and excludes POSIX integration tests', { skip: process.env.AGENT_EVAL_PORTABLE_ONLY === '1' }, () => {
+ const env = { ...process.env, AGENT_EVAL_PORTABLE_ONLY: '1' }; delete env.NODE_TEST_CONTEXT;
+ const output = execFileSync(process.execPath, ['--test', '--test-reporter=tap', fileURLToPath(import.meta.url)], { encoding: 'utf8', timeout: 60_000, env });
+ assert.match(output, /# fail 0/);
+ const skipped = Number(output.match(/# skipped (\d+)/)?.[1]);
+ assert.ok(skipped >= 6, `POSIX integrations ran in portable subset: ${skipped} skipped`);
+ assert.ok(Number(output.match(/# pass (\d+)/)?.[1]) >= 10);
+});
+
+
+test('partial budget telemetry preserves observations without invented token totals', () => {
+ const text = ndjson([{ type: 'turn.started' }, { type: 'item.completed', item: { id: 'tool', type: 'command_execution', command: 'rg needle', exit_code: 0 } }]) + '\n{"type":';
+ assert.throws(() => parseMetrics(text, 'codex'));
+ const metrics = parseMetrics(text, 'codex', { allowIncomplete: true });
+ assert.equal(metrics.turns, 1); assert.equal(metrics.search_calls, 1);
+ assert.equal(metrics.input_tokens, null); assert.equal(metrics.usage_complete, false);
+ const turnLimit = parseMetrics(ndjson([{ type: 'assistant', message: { id: 'a', content: [] } }, { type: 'result', subtype: 'error_max_turns', is_error: true }]), 'claude', { allowIncomplete: true });
+ assert.equal(turnLimit.budget_reason, 'turn_budget'); assert.equal(turnLimit.input_tokens, null);
+});
+
+test('missing usage keeps resolution denominators and reports complete-pair coverage', () => {
+ const runs = fixtureRuns();
+ for (const run of runs.filter((r) => r.instance_id === 'fixture-0' && r.arm === 'baseline')) {
+ Object.assign(run, { input_tokens: null, output_tokens: null, cached_tokens: null, usage_complete: false, termination: 'time_budget' });
+ }
+ const report = summarize(runs, { samples: 1000 });
+ assert.equal(report.metrics.resolved.coverage.paired_tasks, 2);
+ assert.equal(report.metrics.input_tokens.coverage.paired_tasks, 1);
+ assert.equal(report.metrics.input_tokens.coverage.baseline_observed_runs, 2);
+ assert.deepEqual(report.metrics.input_tokens.mean_difference.ci90, [2, 2]);
+ assert.equal(report.per_task[0].metrics.input_tokens.difference, null);
+ for (const run of runs) Object.assign(run, { input_tokens: null, output_tokens: null, cached_tokens: null, usage_complete: false });
+ const absent = summarize(runs, { samples: 100 });
+ assert.equal(absent.metrics.input_tokens.mean_difference.ci90, null);
+ assert.match(markdown(absent), /unavailable/);
+});
+
+test('agent deadlines can preserve output while other subprocess deadlines remain strict', async () => {
+ const result = await execute([process.execPath, '-e', 'console.log("observed"); setInterval(() => {}, 1000)'], { seconds: 3, allowTimeout: true });
+ assert.equal(result.timed_out, true); assert.match(result.stdout, /observed/);
+ await assert.rejects(execute([process.execPath, '-e', 'process.exit(7)'], { allowTimeout: true }), /exited 7/);
+});
+
+integrationTest('the evaluator runs with the inherited HOME and PATH, not the solver isolation', async () => {
+ const script = join(scratch, 'env-evaluator.mjs');
+ writeFileSync(script, `
+ import { readFileSync, writeFileSync } from 'node:fs';
+ import { join } from 'node:path';
+ const r = JSON.parse(readFileSync(process.argv[2], 'utf8'));
+ writeFileSync(join(r.run_path, 'evaluator-env.json'), JSON.stringify({ HOME: process.env.HOME, PATH: process.env.PATH }));
+ console.log(JSON.stringify({ instance_id: r.task.instance_id, resolved: true, evaluator: 'synthetic' }));
+ `);
+ const config = dryConfig(); config.repeats = 1; config.evaluator.command = [process.execPath, script];
+ const out = join(scratch, 'evaluator-env');
+ await runBenchmark({ manifestPath: smoke, config, out, dryRun: true });
+ const runs = readdirSync(out).filter((name) => existsSync(join(out, name, 'evaluator-env.json')));
+ assert.equal(runs.length, 6);
+ for (const name of runs) {
+ assert.deepEqual(JSON.parse(readFileSync(join(out, name, 'evaluator-env.json'), 'utf8')), { HOME: process.env.HOME, PATH: process.env.PATH });
+ assert.notEqual(JSON.parse(readFileSync(join(out, name, 'agent-request.json'), 'utf8')).home, process.env.HOME, 'the solver home stays private');
+ }
+});
+
+integrationTest('time-budget outcome evaluates its retained solution and continues subsequent jobs', async () => {
+ const adapter = join(scratch, 'deadline-agent.mjs');
+ writeFileSync(adapter, `
+ import {readFileSync,writeFileSync} from 'node:fs';
+ import {join} from 'node:path';
+ const r=JSON.parse(readFileSync(process.argv[2],'utf8'));
+ if(r.arm==='baseline' && r.task.instance_id==='synthetic-one') {
+ writeFileSync(join(r.repo_path,'solution.txt'),'synthetic solution\\n');
+ console.log(JSON.stringify({type:'turn',id:'partial'}));
+ process.stdout.write('{"type":'); setInterval(()=>{},1000);
+ } else { process.argv.splice(2,0,'agent'); await import(${JSON.stringify(join(root, 'stub.mjs'))}); }
+ `);
+ const config = dryConfig(); config.repeats = 1; config.budget.seconds = 1;
+ config.agent.command = [process.execPath, adapter];
+ const out = join(scratch, 'time-budget'), report = await runBenchmark({ manifestPath: smoke, config, out, dryRun: true });
+ const runs = readFileSync(join(out,'runs.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
+ assert.equal(runs.length, 6);
+ const limited = runs.find((r) => r.termination === 'time_budget');
+ assert.equal(limited.resolved, 1); assert.equal(limited.input_tokens, null);
+ assert.equal(report.metrics.resolved.coverage.paired_tasks, 3);
+ assert.equal(report.metrics.input_tokens.coverage.paired_tasks, 2);
+ assert.ok(existsSync(join(out, 'summary.md')));
+});
+
+integrationTest('turn-budget overshoots are retained conservatively as unresolved', async () => {
+ const adapter = join(scratch, 'turn-agent.mjs');
+ writeFileSync(adapter, `
+ console.log(JSON.stringify({type:'turn',id:'extra'}));
+ process.argv.splice(2,0,'agent'); await import(${JSON.stringify(join(root, 'stub.mjs'))});
+ `);
+ const config = dryConfig(); config.repeats = 1; config.budget.max_turns = 1;
+ config.agent.command = [process.execPath, adapter];
+ const out = join(scratch, 'turn-budget');
+ await runBenchmark({ manifestPath: smoke, config, out, dryRun: true });
+ const runs = readFileSync(join(out,'runs.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
+ assert.equal(runs.length, 6);
+ assert.ok(runs.every((r) => r.termination === 'turn_budget' && r.resolved === 0 && r.official_resolved === 1));
+ assert.ok(existsSync(join(out, 'summary.md')));
+});
+
+
+integrationTest('subagent messages do not push a completed Claude run over max_turns', async () => {
+ const adapter = join(scratch, 'subagent-agent.mjs');
+ writeFileSync(adapter, `
+ import {readFileSync,writeFileSync} from 'node:fs'; import {join} from 'node:path';
+ const r=JSON.parse(readFileSync(process.argv[2],'utf8'));
+ writeFileSync(join(r.repo_path,'solution.txt'),'synthetic solution\\n');
+ const events=[{type:'assistant',parent_tool_use_id:null,message:{id:'main-1',content:[{type:'tool_use',id:'task',name:'Task',input:{}}]}}];
+ for (const id of ['s1','s2','s3','s4']) events.push({type:'assistant',parent_tool_use_id:'task',message:{id,content:[]}});
+ events.push({type:'assistant',parent_tool_use_id:null,message:{id:'main-2',content:[]}});
+ events.push({type:'result',usage:{input_tokens:1,output_tokens:1,cache_read_input_tokens:0,cache_creation_input_tokens:0}});
+ for (const e of events) console.log(JSON.stringify(e));
+ `);
+ const config = dryConfig(); config.repeats = 1; config.budget.max_turns = 2; config.agent.telemetry = 'claude';
+ config.agent.command = [process.execPath, adapter];
+ const out = join(scratch, 'subagent-turns');
+ await runBenchmark({ manifestPath: smoke, config, out, dryRun: true });
+ const runs = readFileSync(join(out,'runs.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
+ assert.ok(runs.every((r) => r.turns === 2 && r.termination === 'completed' && r.resolved === r.official_resolved));
+});
+
+integrationTest('native turn-limit exit receipts remain evaluable and ordinary crashes remain fatal', async () => {
+ const adapter = join(scratch, 'native-turn-limit.mjs');
+ writeFileSync(adapter, `
+ import {readFileSync,writeFileSync} from 'node:fs'; import {join} from 'node:path';
+ const r=JSON.parse(readFileSync(process.argv[2],'utf8'));
+ writeFileSync(join(r.repo_path,'solution.txt'),'synthetic solution\\n');
+ console.log(JSON.stringify({type:'assistant',message:{id:'a',content:[]}}));
+ console.log(JSON.stringify({type:'result',subtype:'error_max_turns',is_error:true}));
+ process.exitCode=1;
+ `);
+ const config = dryConfig(); config.repeats = 1; config.agent.telemetry = 'claude';
+ config.agent.command = [process.execPath, adapter];
+ const out = join(scratch, 'native-turn-limit'), report = await runBenchmark({ manifestPath: smoke, config, out, dryRun: true });
+ const runs = readFileSync(join(out,'runs.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
+ assert.equal(runs.length, 6); assert.ok(runs.every((r) => r.termination === 'turn_budget' && r.input_tokens === null));
+ assert.equal(report.metrics.resolved.baseline.mean, 1);
+ assert.equal(report.metrics.input_tokens.mean_difference.ci90, null);
+ const crash = join(scratch, 'agent-crash.mjs'); writeFileSync(crash, 'process.exitCode=7;\n');
+ config.agent.command = [process.execPath, crash];
+ const invalid = join(scratch, 'agent-crash');
+ await assert.rejects(runBenchmark({ manifestPath: smoke, config, out: invalid, dryRun: true }), /without a recognized budget/);
+ assert.ok(!existsSync(join(invalid,'summary.md')));
+});
diff --git a/ix-cli/src/cli/__tests__/agent-eval.test.ts b/ix-cli/src/cli/__tests__/agent-eval.test.ts
new file mode 100644
index 00000000..fbc93288
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/agent-eval.test.ts
@@ -0,0 +1,20 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { expect, it } from 'vitest';
+
+// Both Windows and POSIX lanes retain manifest, telemetry and statistics coverage. POSIX runs
+// the full suite once; it already re-runs the portable subset to prove what Windows skips.
+function runSuite(portable: boolean) {
+ const suite = fileURLToPath(new URL('../../../../bench/agent-eval/test/eval.test.mjs', import.meta.url));
+ const result = spawnSync(process.execPath, ['--test', '--test-reporter=tap', suite], {
+ encoding: 'utf8', timeout: 120_000,
+ env: { ...process.env, ...(portable ? { AGENT_EVAL_PORTABLE_ONLY: '1' } : {}) },
+ });
+ expect(result.status, `${result.error?.message ?? ''}\n${result.stdout}\n${result.stderr}`).toBe(0);
+ expect(result.stdout).toMatch(/# fail 0/);
+}
+
+const portable = process.platform === 'win32';
+it(portable ? 'portable agent benchmark unit tests' : 'agent benchmark unit, integration and smoke tests', () => runSuite(portable), 130_000);