From 70eb61bb93ba6759af92244eea5ffcaffd4947bb Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 24 Nov 2026 22:57:04 -0800 Subject: [PATCH 1/4] feat(agent): score shipping helper effects Signed-off-by: Nikolay Petrov (cherry picked from commit b800225aac0735b827d74f68476636337234ad0d) --- AGENTS.md | 2 + README.md | 2 +- .../20261124_030000_agent-helper-effect.md | 8 ++ dokimi/docs/coding-harnesses.md | 24 ++++ dokimi/docs/reference/cli-interface.json | 2 + dokimi/dokimi/agent_run/helpers.py | 104 +++++++++++++++ dokimi/dokimi/agent_run/runner.py | 35 ++++-- dokimi/dokimi/cli_flags.py | 1 + dokimi/dokimi/commands/agent_run.py | 28 ++++- dokimi/dokimi/schemas/agent_run.v1.json | 25 +++- dokimi/tests/data/cli_flags_allowlist.txt | 2 +- dokimi/tests/test_agent_run.py | 10 +- dokimi/tests/test_helper_effects.py | 118 ++++++++++++++++++ 13 files changed, 340 insertions(+), 21 deletions(-) create mode 100644 dokimi/changelog.d/20261124_030000_agent-helper-effect.md create mode 100644 dokimi/dokimi/agent_run/helpers.py create mode 100644 dokimi/tests/test_helper_effects.py diff --git a/AGENTS.md b/AGENTS.md index 9ff08ef0f..8a0841f91 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,6 +94,8 @@ Registries, bundled in the package (`dokimi/dokimi/`) so they ship in the wheel: For AI-Ready tasks, tag the source and run `dokimi eval check ./evals --controls --mode host --json` before including them in Usage or weighted coverage. +Measure each shipping helper on the same tasks and agents with `dokimi agent run --arms base,assets`. + ## Persisted formats - Every artifact format is a versioned JSON Schema in diff --git a/README.md b/README.md index dfd6fb264..390e5676f 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ dokimi catalog check --root /path/to/your/catalog --kind skills Then follow [reviewing a skill or repository](dokimi/docs/reviewing.md) for the next step and its cost. Agent experiments need the selected provider or logged-in harness; executable coding tasks also need their supported container environment. Check [harness support](dokimi/docs/coding-harnesses.md) before choosing a runner. -For scored coding-agent sessions and offline pilot replay, use `dokimi agent run` and `dokimi agent replay`. Use `dokimi eval check --controls` to verify the correct and look-alike wrong solutions. See [AI-Ready coding-agent tests](dokimi/docs/coding-harnesses.md#ai-ready-coding-agent-test). +For scored coding-agent sessions and offline pilot replay, use `dokimi agent run` and `dokimi agent replay`. Use `dokimi eval check --controls` to verify the correct and look-alike wrong solutions. Use the `--arms base,assets` option to measure each shipping helper. See [AI-Ready coding-agent tests](dokimi/docs/coding-harnesses.md#ai-ready-coding-agent-test). ## Read the evidence diff --git a/dokimi/changelog.d/20261124_030000_agent-helper-effect.md b/dokimi/changelog.d/20261124_030000_agent-helper-effect.md new file mode 100644 index 000000000..6b3ee3477 --- /dev/null +++ b/dokimi/changelog.d/20261124_030000_agent-helper-effect.md @@ -0,0 +1,8 @@ + + +### Added + +- Compare each shipping helper to the baseline on matched coding-agent sessions and report the effect per agent. diff --git a/dokimi/docs/coding-harnesses.md b/dokimi/docs/coding-harnesses.md index 69f2e23b9..69476d0f8 100644 --- a/dokimi/docs/coding-harnesses.md +++ b/dokimi/docs/coding-harnesses.md @@ -1591,3 +1591,27 @@ under `data.sessions` in JSON output. After changing the runner, run `pytest tests/test_agent_run.py` and repeat the archived replay for each profile. Check the historical score and the measured rubric coverage separately. + +### Measure a shipping helper + +Use `--arms base,assets` to run matched repeats with the baseline and with +each shipping helper. Supply `--helper NAME=DIR` once per helper. Keep the +helper out of the baseline task's `workspace/`. + +```bash +dokimi agent run --tasks ./evals --agent claude-code=sonnet --agent codex=gpt \ + --arms base,assets --helper docs=./helper-test --out-dir results/helpers --json +``` + +In host mode, a helper can overlay `workspace/` with the skill, `AGENTS.md`, +or docs index in the location each agent discovers. For MCP, provide +`claude-mcp.json` with a `mcpServers` object and `codex-mcp.toml` with a +`mcp_servers` table. Use environment references for credentials. + +`data.helpers` reports the Usage difference for each helper, agent and model. +Each difference uses the same scored repeats on both sides. Evidence below +70% matched rubric coverage is inconclusive. Every shipping helper needs +a nonnegative difference on every measured agent. The helper gate fails +when no helper is declared or any measured difference is negative. +`pytest tests/test_helper_effects.py` exercises overlay isolation and the +helper gate. diff --git a/dokimi/docs/reference/cli-interface.json b/dokimi/docs/reference/cli-interface.json index 7f35347ea..9a818638a 100644 --- a/dokimi/docs/reference/cli-interface.json +++ b/dokimi/docs/reference/cli-interface.json @@ -32,8 +32,10 @@ "allow_abbrev": true, "params": [ {"key": "--agent", "action": "_AppendAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": true, "type": "dokimi.commands.agent_run._agent#2c54f4024358"}, + {"key": "--arms", "action": "_StoreAction", "choices": ["'base'", "'base,assets'"], "const": null, "default": "base", "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--endpoint", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--helper", "action": "_AppendAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.commands.agent_run._helper#f72c0463880e"}, {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--key-env", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--mode", "action": "_StoreAction", "choices": ["'docker'", "'harbor'", "'host'"], "const": null, "default": "host", "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, diff --git a/dokimi/dokimi/agent_run/helpers.py b/dokimi/dokimi/agent_run/helpers.py new file mode 100644 index 000000000..1a953c244 --- /dev/null +++ b/dokimi/dokimi/agent_run/helpers.py @@ -0,0 +1,104 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Install matched helper treatments and calculate their paired Usage effect.""" + +from __future__ import annotations + +import json +import shutil +import tomllib +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from dokimi.utils import InputError + +from .scoring import usage_summary + + +@dataclass(frozen=True) +class Helper: + name: str + root: Path + + def validate(self) -> None: + workspace = self.root / "workspace" + codex = self.root / "codex-mcp.toml" + claude = self.root / "claude-mcp.json" + if not (workspace.is_dir() or claude.is_file() or codex.is_file()): + raise InputError(f"{self.name}: expected workspace/, claude-mcp.json or codex-mcp.toml") + if workspace.is_dir() and not any(workspace.iterdir()): + raise InputError(f"{self.name}: workspace/ is empty") + try: + if claude.is_file() and not _servers(json.loads(claude.read_text(encoding="utf-8")), "mcpServers"): + raise ValueError("claude-mcp.json needs mcpServers") + if codex.is_file() and not _servers(tomllib.loads(codex.read_text(encoding="utf-8")), "mcp_servers"): + raise ValueError("codex-mcp.toml needs exactly the mcp_servers table") + except (ValueError, OSError): + raise InputError(f"{self.name}: invalid MCP configuration") from None + + def applies_to(self, agent: str) -> bool: + config = {"claude-code": "claude-mcp.json", "codex": "codex-mcp.toml"}.get(agent) + return (self.root / "workspace").is_dir() or (config is not None and (self.root / config).is_file()) + + def install(self, workspace: Path, config: Path, agent: str, argv: list[str]) -> None: + overlay = self.root / "workspace" + if overlay.is_dir(): + shutil.copytree(overlay, workspace, dirs_exist_ok=True) + if agent == "claude-code" and (server := self.root / "claude-mcp.json").is_file(): + local = config / server.name + shutil.copyfile(server, local) + argv[1:1] = ["--strict-mcp-config", "--mcp-config", str(local)] + if agent == "codex" and (server := self.root / "codex-mcp.toml").is_file(): + with (config / "config.toml").open("a", encoding="utf-8") as file: + file.write("\n" + server.read_text(encoding="utf-8")) + + +def _servers(config: Any, key: str) -> bool: + return isinstance(config, dict) and set(config) == {key} and isinstance(config[key], dict) and bool(config[key]) + + +def helper_effects(rows: list[dict[str, Any]], helpers: tuple[Helper, ...], repeats: int) -> dict[str, Any]: + if not helpers: + return {"status": "FAIL", "reason": "no shipping helper declared", "comparisons": [], "qualifying_helpers": []} + per_helper = {helper.name: _paired(rows, helper.name, repeats) for helper in helpers} + qualifying = [name for name, results in per_helper.items() + if results and all(row["effect"] is not None and row["effect"] >= 0 for row in results)] + comparisons = [row for results in per_helper.values() for row in results] + if any(row["effect"] is not None and row["effect"] < 0 for row in comparisons): + status = "FAIL" + else: + status = "PASS" if len(qualifying) == len(helpers) else "INCONCLUSIVE" + return {"status": status, "comparisons": comparisons, "qualifying_helpers": qualifying} + + +def _paired(rows: list[dict[str, Any]], helper: str, repeats: int) -> list[dict[str, Any]]: + base = {_cell(r): r for r in rows if r["arm"] == "base"} + treated = {_cell(r): r for r in rows if r["arm"] == helper} + left, right = [], [] + for key, row in base.items(): + with_helper = treated.get(key, {**row, "arm": helper, "points": None}) + if not _scored(row) or not _scored(with_helper): + row = {**row, "verdict": "INCONCLUSIVE", "points": None} + with_helper = {**with_helper, "verdict": "INCONCLUSIVE", "points": None} + left.append(row) + right.append(with_helper) + before = usage_summary(left, repeats) + after = usage_summary(right, repeats) + return [_delta(a, b, helper) for a, b in zip(before, after, strict=True)] + + +def _scored(row: dict[str, Any]) -> bool: + return row["verdict"] in ("PASS", "FAIL") and row["points"] is not None + + +def _cell(row: dict[str, Any]) -> tuple[str, str, str, int]: + return row["agent"], row["model"], row["task"], row["repeat"] + + +def _delta(left: dict[str, Any], right: dict[str, Any], helper: str) -> dict[str, Any]: + baseline, treated = left["usage"], right["usage"] + effect = treated - baseline if treated is not None and baseline is not None else None + return {"helper": helper, "agent": left["agent"], "model": left["model"], "base_usage": baseline, + "helper_usage": treated, "effect": effect, "coverage": left["rubric_coverage"]} diff --git a/dokimi/dokimi/agent_run/runner.py b/dokimi/dokimi/agent_run/runner.py index e1f2dc5c2..385a77a05 100644 --- a/dokimi/dokimi/agent_run/runner.py +++ b/dokimi/dokimi/agent_run/runner.py @@ -31,6 +31,7 @@ from .checker import SYSTEM_ENV, check, inconclusive, refuse_workspace_checker, session_env from .container import claim, container_evidence, model_activity from .controls import check_controls, task_control_digest +from .helpers import Helper, helper_effects from .scoring import GROUP_WEIGHTS, usage_summary _ENV_ERROR = re.compile( @@ -59,6 +60,7 @@ class Run: repeats: int output: Path runner: process.Runner = process.run + helpers: tuple[Helper, ...] | None = None def execute(self) -> dict[str, Any]: adapters = self.validate() @@ -68,17 +70,28 @@ def execute(self) -> dict[str, Any]: raise InputError(f"output directory already exists: {self.output}") from exc controls = check_controls(self.tasks, "host" if self.mode == "host" else "docker", runner=self.runner) control_rows = {row["task"]: row for row in controls["tasks"]} - cells = itertools.product(self.tasks, self.agents, range(1, self.repeats + 1)) - rows = [self.session(task, agent, rep, adapters.get(agent.name), index, control_rows[task.name]) - for index, (task, agent, rep) in enumerate(cells, 1)] - return {"mode": self.mode, "repeats": self.repeats, "sessions": rows, - "usage": usage_summary(rows, self.repeats), "controls": controls} + arms = [None, *(self.helpers or ())] + cells = itertools.product(self.tasks, self.agents, range(1, self.repeats + 1), arms) + rows = [self.session(task, agent, rep, adapters.get(agent.name), index, control_rows[task.name], helper) + for index, (task, agent, rep, helper) in enumerate(cells, 1)] + result = {"mode": self.mode, "repeats": self.repeats, "sessions": rows, + "usage": usage_summary(rows, self.repeats), "controls": controls} + if self.helpers is not None: + result["helpers"] = helper_effects(rows, self.helpers, self.repeats) + return result def validate(self) -> dict[str, Adapter]: if len({task.name for task in self.tasks}) != len(self.tasks): raise InputError("task names must be unique") if self.mode == "docker" and any(agent.name != "claude-code" for agent in self.agents): raise InputError("--mode docker supports only claude-code; use --mode harbor for other container agents") + if self.helpers and self.mode != "host": + raise InputError("--helper needs --mode host") + names = {helper.name for helper in self.helpers or ()} + if "base" in names or len(names) != len(self.helpers or ()): + raise InputError("helper names must be unique and cannot use the reserved name base") + for helper in self.helpers or (): + helper.validate() adapters = {a.name: adapter_for(a.name) for a in self.agents} if self.mode == "host" else {} for task in self.tasks: self._validate_task(task) @@ -100,7 +113,7 @@ def _validate_task(self, task: TaskSpec) -> None: raise InputError(f"{task.name}: timeouts must be positive finite numbers") def session(self, task: TaskSpec, agent: Agent, rep: int, adapter: Adapter | None, session_id: int, - control: dict[str, Any]) -> dict[str, Any]: + control: dict[str, Any], helper: Helper | None = None) -> dict[str, Any]: result_dir = self.output / f"session-{session_id:05d}" result_dir.mkdir() start = time.monotonic() @@ -111,17 +124,19 @@ def session(self, task: TaskSpec, agent: Agent, rep: int, adapter: Adapter | Non row = inconclusive(_control_failure_reason(control)) elif task_control_digest(task.path) != control["task_digest"]: row = inconclusive("task files changed after checker controls") + elif helper is not None and not helper.applies_to(agent.name): + row = inconclusive("helper has no configuration for this agent") elif adapter is None: row = self._container(task, agent, tmp, result_dir) else: - row = self._host(task, agent, adapter, tmp, result_dir, control["task_digest"]) + row = self._host(task, agent, adapter, tmp, result_dir, control["task_digest"], helper) except Unavailable as exc: row = inconclusive(str(exc)) except (OSError, RuntimeError): row = inconclusive("runner could not prepare or launch the session") evidence = { "task": task.name, "group": task.metadata["usage_group"], "source": task.metadata.get("source"), - "agent": agent.name, "model": agent.model, "arm": "base", "repeat": rep, + "agent": agent.name, "model": agent.model, "arm": helper.name if helper is not None else "base", "repeat": rep, "claimed": None, "points": None, "cost_usd": None, "tokens_in": None, "tokens_out": None, "transcript": None, "wall_s": round(time.monotonic() - start, 3), **row, "false_success": row.get("claimed") is True and row["verdict"] == "FAIL", @@ -130,7 +145,7 @@ def session(self, task: TaskSpec, agent: Agent, rep: int, adapter: Adapter | Non return evidence def _host(self, task: TaskSpec, agent: Agent, adapter: Adapter, tmp: Path, output: Path, - task_digest: str) -> dict[str, Any]: + task_digest: str, helper: Helper | None = None) -> dict[str, Any]: workspace, config, home = (tmp / name for name in ("workspace", "config", "home")) config.mkdir() home.mkdir() @@ -140,6 +155,8 @@ def _host(self, task: TaskSpec, agent: Agent, adapter: Adapter, tmp: Path, outpu shutil.copytree(seed, workspace) else: workspace.mkdir() + if helper is not None: + helper.install(workspace, config, agent.name, cmd) venv = workspace / ".dokimi-venv" plain_env = session_env(home, venv) self._create_venv(workspace, venv, plain_env) diff --git a/dokimi/dokimi/cli_flags.py b/dokimi/dokimi/cli_flags.py index 2d48d36cf..5164f9aa3 100644 --- a/dokimi/dokimi/cli_flags.py +++ b/dokimi/dokimi/cli_flags.py @@ -101,6 +101,7 @@ class Concept: Flag("--controls-report", "PATH", "path"), Flag("--evals", "PATH", "path", meaning="the eval catalog whose need labels are already covered"), Flag("--group", "GROUP", "choice", meaning="the checklist Usage group of proposed tasks"), + Flag("--helper", "NAME=DIR", repeatable=True, meaning="a shipping helper to measure in a separate arm"), ), ), Concept( diff --git a/dokimi/dokimi/commands/agent_run.py b/dokimi/dokimi/commands/agent_run.py index d3b3a4f4c..45d767ea5 100644 --- a/dokimi/dokimi/commands/agent_run.py +++ b/dokimi/dokimi/commands/agent_run.py @@ -47,10 +47,11 @@ def _publish(args: argparse.Namespace, data: dict[str, Any], kind: str) -> None: data = {**data, "generated_at": datetime.now(UTC).isoformat()} payload = save_artifact("agent_run", data, path) if path else stamp("agent_run", data) rows = payload["sessions"] - failed = any(r["verdict"] == "FAIL" for r in rows) or any( + helper_status = payload.get("helpers", {}).get("status") + failed = helper_status == "FAIL" or any(r["verdict"] == "FAIL" for r in rows) or any( r["status"] == "FAIL" for r in data.get("controls", {}).get("tasks", []) ) - incomplete = any(r["verdict"] == "INCONCLUSIVE" for r in rows) + incomplete = helper_status == "INCONCLUSIVE" or any(r["verdict"] == "INCONCLUSIVE" for r in rows) if args.json: verdict = "fail" if failed else None if incomplete else "pass" cli_output.emit_leaf(kind, payload, status="partial" if live and incomplete else "complete", @@ -59,6 +60,8 @@ def _publish(args: argparse.Namespace, data: dict[str, Any], kind: str) -> None: for row in payload.get("pilot_usage", payload["usage"]): score = "INCONCLUSIVE" if row["usage"] is None else f"{row['usage']:.1f}" print(f"{row['agent']}={row['model']} ({row['arm']}) Usage {score}, scored {row['coverage']:.0%}") + if helper_status: + print(f"Helper effect {helper_status}") if path: print(f"Evidence written to {path}") if live: @@ -70,6 +73,7 @@ def _publish(args: argparse.Namespace, data: dict[str, Any], kind: str) -> None: def _run(args: argparse.Namespace) -> None: from dokimi.agent_run.adapters import Route + from dokimi.agent_run.helpers import Helper from dokimi.agent_run.runner import Agent, Run from dokimi.harnesses.tasks import discover_tasks, is_task_dir, load_task @@ -86,7 +90,11 @@ def _run(args: argparse.Namespace) -> None: if len(set(agents)) != len(agents): raise InputError("each agent and model pair can be selected once") route = Route(args.route, args.endpoint, args.key_env) - run = Run(tasks, agents, route, args.mode, args.reps, args.out_dir.resolve()) + if args.helper and args.arms != "base,assets": + raise InputError("--helper needs --arms base,assets") + helpers = tuple(Helper(name, Path(directory).resolve()) for name, directory in (args.helper or [])) + run = Run(tasks, agents, route, args.mode, args.reps, args.out_dir.resolve(), + helpers=helpers if args.arms == "base,assets" else None) _publish(args, run.execute(), "agent run") @@ -103,11 +111,19 @@ def _agent(value: str) -> tuple[str, str]: return name, model +def _helper(value: str) -> tuple[str, str]: + name, sep, directory = value.partition("=") + if not sep or not name or not directory: + raise argparse.ArgumentTypeError("expected NAME=DIR") + return name, directory + + def register(sub, positive_int) -> None: root = sub.add_parser("agent", help="Measure how coding agents use a product") leaves = root.add_subparsers(dest="agent_cmd", required=True) run = leaves.add_parser("run", help="Run and independently check coding-agent sessions", - description="[paid] Exit 0 when controls and sessions pass, 1 on a checker or control failure, 2 for invalid input, " + description="[paid] Exit 0 when controls, sessions and any helper gate pass, " + "1 on a checker, control or helper failure, 2 for invalid input, " "and 3 when evidence is inconclusive and no checker failed.") cli_flags.add(run, "inputs", "--tasks", required=True, type=Path, help="External directory of executable tasks") cli_flags.add(run, "coding_agent", "--agent", action="append", type=_agent, required=True, @@ -115,6 +131,10 @@ def register(sub, positive_int) -> None: cli_flags.add(run, "reps", "--reps", type=positive_int, default=3, help="Sessions per task and agent (default 3)") run.add_argument("--mode", choices=("host", "docker", "harbor"), default="host", help="Execute directly, via Dokimi's Docker harness, or via Harbor") + run.add_argument("--arms", choices=("base", "base,assets"), default="base", + help="Compare baseline Usage with each shipping helper") + cli_flags.add(run, "usage_evidence", "--helper", action="append", type=_helper, metavar="NAME=DIR", + help="Shipping helper overlay for host mode. Repeat for multiple helpers.") cli_flags.add(run, "coding_agent", "--route", choices=("litellm", "bedrock"), default="litellm", help="Model route for host mode") cli_flags.add(run, "coding_agent", "--endpoint", help="Model API base URL for host mode") diff --git a/dokimi/dokimi/schemas/agent_run.v1.json b/dokimi/dokimi/schemas/agent_run.v1.json index 236b45954..96f9587dc 100644 --- a/dokimi/dokimi/schemas/agent_run.v1.json +++ b/dokimi/dokimi/schemas/agent_run.v1.json @@ -27,7 +27,17 @@ "repeats": {"type": "integer", "minimum": 1}, "sessions": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/session"}}, "usage": {"type": "array", "items": {"$ref": "#/$defs/usage"}}, - "pilot_usage": {"type": "array", "items": {"$ref": "#/$defs/usage"}} + "pilot_usage": {"type": "array", "items": {"$ref": "#/$defs/usage"}}, + "helpers": { + "type": "object", + "required": ["status", "qualifying_helpers", "comparisons"], + "properties": { + "status": {"enum": ["PASS", "FAIL", "INCONCLUSIVE"]}, + "reason": {"type": "string"}, + "qualifying_helpers": {"type": "array", "items": {"type": "string", "minLength": 1}}, + "comparisons": {"type": "array", "items": {"$ref": "#/$defs/helper_comparison"}} + } + } }, "$defs": { "session": { @@ -54,6 +64,19 @@ "tokens_out": {"type": ["integer", "null"], "minimum": 0} } }, + "helper_comparison": { + "type": "object", + "required": ["helper", "agent", "model", "base_usage", "helper_usage", "effect", "coverage"], + "properties": { + "helper": {"type": "string", "minLength": 1}, + "agent": {"type": "string", "minLength": 1}, + "model": {"type": "string", "minLength": 1}, + "base_usage": {"type": ["number", "null"], "minimum": 0, "maximum": 10}, + "helper_usage": {"type": ["number", "null"], "minimum": 0, "maximum": 10}, + "effect": {"type": ["number", "null"], "minimum": -10, "maximum": 10}, + "coverage": {"type": "number", "minimum": 0, "maximum": 1} + } + }, "usage": { "type": "object", "required": ["agent", "model", "arm", "usage", "coverage", "pass_rate_ci95", "stable_tasks", "false_success_rate"], diff --git a/dokimi/tests/data/cli_flags_allowlist.txt b/dokimi/tests/data/cli_flags_allowlist.txt index 26783440a..236b1640d 100644 --- a/dokimi/tests/data/cli_flags_allowlist.txt +++ b/dokimi/tests/data/cli_flags_allowlist.txt @@ -19,7 +19,7 @@ --allow-unsafe --allow-unsupported --answers-out ---arms # novelty measurement arms (no_artifact,full,placebo) on skill novelty and catalog novelty; arm-name filters on eval score checklist and pairwise; not subject arm specs +--arms # novelty measurement arms, checks on named arms in eval score, or the baseline/helper design in agent run; not subject arm specs --artifact --atoms # skill probe, ground, view and shorten: the atoms.json of skill novelty atoms; no canonical input names it --baseline-harness diff --git a/dokimi/tests/test_agent_run.py b/dokimi/tests/test_agent_run.py index 012acb2bc..d89362f8e 100644 --- a/dokimi/tests/test_agent_run.py +++ b/dokimi/tests/test_agent_run.py @@ -335,7 +335,7 @@ def execute(argv, *, env, **kwargs): return _done(argv, {"correct": True, "integrity": True, "no_hallucination": True, "process": PROCESS_POINTS}) make_run = runner.Run - monkeypatch.setattr(runner, "Run", lambda *args: make_run(*args, runner=execute)) + monkeypatch.setattr(runner, "Run", lambda *args, **kwargs: make_run(*args, runner=execute, **kwargs)) task = _task_directory(tmp_path / "task") monkeypatch.setattr(sys, "argv", ["dokimi", "agent", "run", "--tasks", str(task), "--agent", "claude-code=m", "--route", "bedrock", "--reps", "1", "--out-dir", str(tmp_path / "runs")]) @@ -636,7 +636,7 @@ def execute(argv, **kwargs): return _done(argv, {"correct": True, "integrity": True, "no_hallucination": True, "process": PROCESS_POINTS}) make_run = runner.Run - monkeypatch.setattr(runner, "Run", lambda *args: make_run(*args, runner=execute)) + monkeypatch.setattr(runner, "Run", lambda *args, **kwargs: make_run(*args, runner=execute, **kwargs)) monkeypatch.setenv("LITELLM_KEY", "test-route-credential") task = _task_directory(tmp_path / "task") output = tmp_path / "runs" @@ -666,7 +666,7 @@ def execute(argv, **kwargs): "process": PROCESS_POINTS}) make_run = runner.Run - monkeypatch.setattr(runner, "Run", lambda *args: make_run(*args, runner=execute)) + monkeypatch.setattr(runner, "Run", lambda *args, **kwargs: make_run(*args, runner=execute, **kwargs)) task = _task_directory(tmp_path / "task") (task / "task.toml").write_text( '[metadata]\nusage_group = "Core"\n[verifier]\n' @@ -710,7 +710,7 @@ def execute(argv, **kwargs): return _done(argv, {"correct": True, "integrity": True, "no_hallucination": True, "process": PROCESS_POINTS}) make_run = runner.Run - monkeypatch.setattr(runner, "Run", lambda *args: make_run(*args, runner=execute)) + monkeypatch.setattr(runner, "Run", lambda *args, **kwargs: make_run(*args, runner=execute, **kwargs)) monkeypatch.setattr(adapters, "entry_points", lambda **_: [Entry()]) task = _task_directory(tmp_path / "task") monkeypatch.setattr(sys, "argv", ["dokimi", "agent", "run", "--tasks", str(task), "--agent", "local=m", @@ -755,7 +755,7 @@ def execute(argv, **kwargs): return replace(result, timed_out=True) make_run = runner.Run - monkeypatch.setattr(runner, "Run", lambda *args: make_run(*args, runner=execute)) + monkeypatch.setattr(runner, "Run", lambda *args, **kwargs: make_run(*args, runner=execute, **kwargs)) monkeypatch.setenv("LITELLM_KEY", "test-route-credential") task = _task_directory(tmp_path / "task") monkeypatch.setattr(sys, "argv", ["dokimi", "agent", "run", "--tasks", str(task), "--agent", "claude-code=m", diff --git a/dokimi/tests/test_helper_effects.py b/dokimi/tests/test_helper_effects.py new file mode 100644 index 000000000..7a7d886fe --- /dev/null +++ b/dokimi/tests/test_helper_effects.py @@ -0,0 +1,118 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path + +import pytest + +from dokimi import process +from dokimi.agent_run.adapters import Route +from dokimi.agent_run.helpers import Helper, helper_effects +from dokimi.agent_run.runner import Agent, Run, task_control_digest +from dokimi.agent_run.scoring import PROCESS_POINTS +from dokimi.artifacts import save_artifact +from dokimi.harnesses.tasks import TaskSpec +from dokimi.utils import InputError + + +def test_helper_is_required_and_negative_effect_on_one_agent_fails(): + rows = [{"task": "fit", "group": "Core", "model": "m", "agent": agent, "arm": arm, "repeat": rep, + "verdict": "PASS", "claimed": True, "points": points} + for agent, arm, points in [("codex", "base", 90), ("codex", "skill", 80), + ("claude", "base", 70), ("claude", "skill", 90)] for rep in range(1, 4)] + helper = Helper("skill", Path("skills")) + assert helper_effects(rows, (), 3)["status"] == "FAIL" + report = helper_effects(rows, (helper,), 3) + assert report["status"] == "FAIL" + assert report["qualifying_helpers"] == [] + assert [r["effect"] for r in report["comparisons"]] == pytest.approx([2, -1]) + for row in rows: + if row["agent"] == "codex" and row["arm"] == "skill": + row["points"] = 90 + assert helper_effects(rows, (helper,), 3)["qualifying_helpers"] == ["skill"] + rows.pop() + assert helper_effects(rows, (helper,), 3)["status"] == "INCONCLUSIVE" + + +def test_helper_overlay_changes_only_treated_workspace(tmp_path): + overlay = tmp_path / "helper" + (overlay / "workspace").mkdir(parents=True) + (overlay / "workspace" / "AGENTS.md").write_text("Use docs/index.md.\n", encoding="utf-8") + (overlay / "codex-mcp.toml").write_text('[mcp_servers.docs]\nurl="https://example.org/mcp"\n', encoding="utf-8") + config = tmp_path / "config" + config.mkdir() + (config / "config.toml").write_text('model_provider="dokimi"\n', encoding="utf-8") + treated, baseline = tmp_path / "treated", tmp_path / "baseline" + treated.mkdir() + baseline.mkdir() + helper = Helper("docs", overlay) + helper.validate() + helper.install(treated, config, "codex", ["codex"]) + assert (treated / "AGENTS.md").read_text() == "Use docs/index.md.\n" + assert not (baseline / "AGENTS.md").exists() + assert '[mcp_servers.docs]' in (config / "config.toml").read_text() + + +@pytest.mark.parametrize("text", ['{"mcpServers": {}}', '{"mcpServers": []}', '{invalid']) +def test_helper_rejects_empty_or_malformed_mcp(tmp_path, text): + (tmp_path / "claude-mcp.json").write_text(text, encoding="utf-8") + with pytest.raises(InputError, match="invalid MCP configuration"): + Helper("docs", tmp_path).validate() + + +def test_mcp_treatment_does_not_silently_pass_for_unconfigured_agent(tmp_path): + mcp = tmp_path / "claude-mcp.json" + mcp.write_text('{"mcpServers":{"docs":{"url":"https://example.org/mcp"}}}', encoding="utf-8") + config = tmp_path / "config" + config.mkdir() + helper = Helper("mcp", tmp_path) + helper.validate() + assert helper.applies_to("claude-code") + assert not helper.applies_to("codex") + argv = ["claude", "--print"] + helper.install(tmp_path / "workspace", config, "claude-code", argv) + assert argv[1:4] == ["--strict-mcp-config", "--mcp-config", str(config / mcp.name)] + assert (config / mcp.name).read_bytes() == mcp.read_bytes() + + +def test_runner_matches_base_and_each_installed_helper(tmp_path, monkeypatch): + import json + + from dokimi.agent_run import adapters, runner + + monkeypatch.setattr(adapters, "_WINDOWS", False) + monkeypatch.setenv("LITELLM_KEY", "fake-model-key") + task_dir = tmp_path / "task" + task_dir.mkdir() + task = TaskSpec("fit", task_dir, "Fit data", {"usage_group": "Core", "source": "synthetic"}, + {"host_command": ["{python}", "{task_path}", "{workspace}"]}) + controls = {"tasks": [{"task": task.name, "status": "PASS", "task_digest": task_control_digest(task_dir)}]} + monkeypatch.setattr(runner, "check_controls", lambda *args, **kwargs: controls) + seen = [] + + def execute(argv, *, cwd, **kwargs): + if argv[1:3] == ["-m", "venv"]: + payload = {} + elif argv[0] == "claude": + files = {name for name in ("AGENTS.md", "index.md") if (cwd / name).is_file()} + seen.append(files) + (cwd / "used-help").write_text(str(bool(files)), encoding="utf-8") + payload = {"type": "result", "result": "DONE"} + else: + helped = (Path(argv[-1]) / "used-help").read_text(encoding="utf-8") == "True" + payload = {"correct": True, "integrity": True, "no_hallucination": True, + "process": {**PROCESS_POINTS, "docs": 10 if helped else 0}} + return process.Completed(tuple(argv), 0, json.dumps(payload).encode(), b"") + + for name, file in (("agents", "AGENTS.md"), ("index", "index.md")): + workspace = tmp_path / name / "workspace" + workspace.mkdir(parents=True) + (workspace / file).write_text("Fit documentation.\n", encoding="utf-8") + helpers = tuple(Helper(name, tmp_path / name) for name in ("agents", "index")) + out = tmp_path / "out" + run = Run([task], [Agent("claude-code", "m")], Route("litellm", None, None), "host", 3, out, + runner=execute, helpers=helpers) + data = save_artifact("agent_run", run.execute(), out / "agent-run.json") + assert seen == [set(), {"AGENTS.md"}, {"index.md"}] * 3 + assert data["helpers"]["status"] == "PASS" + assert [row["effect"] for row in data["helpers"]["comparisons"]] == pytest.approx([1.0, 1.0]) From efb94e468eb21f96e37c5b2f7a1e81049ebe5a41 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 2 Dec 2026 23:42:41 -0800 Subject: [PATCH 2/4] fix(agent): classify unavailable Codex sandbox Signed-off-by: Nikolay Petrov (cherry picked from commit ab89a736222856242d3766b01f750387c3f3400f) Signed-off-by: Nikolay Petrov --- .../20261202_codex_sandbox_unavailable.md | 8 +++ dokimi/docs/coding-harnesses.md | 5 ++ dokimi/dokimi/agent_run/runner.py | 16 ++++- dokimi/tests/test_agent_environment.py | 64 +++++++++++++++++++ 4 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 dokimi/changelog.d/20261202_codex_sandbox_unavailable.md create mode 100644 dokimi/tests/test_agent_environment.py diff --git a/dokimi/changelog.d/20261202_codex_sandbox_unavailable.md b/dokimi/changelog.d/20261202_codex_sandbox_unavailable.md new file mode 100644 index 000000000..a2291b5f9 --- /dev/null +++ b/dokimi/changelog.d/20261202_codex_sandbox_unavailable.md @@ -0,0 +1,8 @@ + + +### Fixed + +- Mark failed Codex runs as inconclusive when a separate probe confirms Linux namespace failure. diff --git a/dokimi/docs/coding-harnesses.md b/dokimi/docs/coding-harnesses.md index 69476d0f8..6a9337249 100644 --- a/dokimi/docs/coding-harnesses.md +++ b/dokimi/docs/coding-harnesses.md @@ -1547,6 +1547,11 @@ repeat and a Wilson 95% interval for the checker pass rate. Exit 0 means all controls and sessions passed, 1 that at least one failed, 2 that input was invalid, and 3 that evidence was inconclusive without a failure. +On Linux, a failed Codex tool operation and a failed checker trigger a +separate namespace probe. A confirmed namespace failure makes the session +inconclusive and keeps its metering and transcript. Re-test the classification +with `pytest tests/test_agent_environment.py`. + With `--json`, `cost.spent_usd` sums known session costs and `cost.priced` is false when any counted session lacks a price, or null when no calls were counted. `cost.calls` sums reported agent turns. When the turn count is diff --git a/dokimi/dokimi/agent_run/runner.py b/dokimi/dokimi/agent_run/runner.py index 385a77a05..c563f2ac9 100644 --- a/dokimi/dokimi/agent_run/runner.py +++ b/dokimi/dokimi/agent_run/runner.py @@ -27,7 +27,7 @@ from dokimi.repos.events import convert from dokimi.repos.transcript import Transcript -from .adapters import Adapter, Route, Unavailable, adapter_for +from .adapters import Adapter, Codex, Route, Unavailable, adapter_for from .checker import SYSTEM_ENV, check, inconclusive, refuse_workspace_checker, session_env from .container import claim, container_evidence, model_activity from .controls import check_controls, task_control_digest @@ -42,6 +42,7 @@ re.IGNORECASE, ) _SECRET_NAME = re.compile(r"TOKEN|PASSWORD|PASSWD|AUTH|SECRET|KEY|PROXY", re.IGNORECASE) +_NAMESPACE_ERROR = re.compile(r"(?m)^bwrap: (?:Creating new namespace failed|No permissions to create a new namespace)") _HOST_CAPTURE_LIMIT = 16 * 1024 * 1024 @@ -150,6 +151,7 @@ def _host(self, task: TaskSpec, agent: Agent, adapter: Adapter, tmp: Path, outpu config.mkdir() home.mkdir() cmd, route_env = adapter.launch(_prompt(task), agent.model, config, self.route) + sandbox = shutil.which(cmd[0]) if sys.platform == "linux" and isinstance(adapter, Codex) else None seed = task.path / "workspace" if seed.is_dir(): shutil.copytree(seed, workspace) @@ -179,10 +181,22 @@ def _host(self, task: TaskSpec, agent: Agent, adapter: Adapter, tmp: Path, outpu trace_path.write_text(redact(proc.stdout, secrets), encoding="utf-8") reason = _unavailable(proc, trace) verdict = (inconclusive(reason) if reason else self._host_check(task, workspace, trace_path, task_digest)) + if sandbox and verdict["verdict"] == "FAIL" and self._sandbox_failed(os.path.abspath(sandbox), trace, tmp, home): + verdict = inconclusive("Codex could not create a Linux workspace sandbox") activity = model_activity(trace) or (trace_format == "text" and proc.ok and bool(trace.answer)) return {**verdict, "claimed": claim(trace.answer), **metered, "transcript": trace_path.relative_to(self.output).as_posix(), "model_activity": activity} + def _sandbox_failed(self, executable: str, trace: Transcript, cwd: Path, home: Path) -> bool: + if not any(event.get("kind") in {"command", "edit"} and event.get("rc") not in (None, 0) for event in trace.events): + return False + try: + probe = self.runner([executable, "sandbox", "linux", "--", "/bin/true"], cwd=cwd, timeout=10, + env=process.Env.only(SYSTEM_ENV, {"HOME": str(home)})) + except OSError: + return False + return not probe.ok and bool(_NAMESPACE_ERROR.search(probe.stderr)) + def _host_check(self, task: TaskSpec, workspace: Path, trace_path: Path, task_digest: str) -> dict[str, Any]: try: with tempfile.TemporaryDirectory(prefix="dokimi-checker-", ignore_cleanup_errors=True) as scratch: diff --git a/dokimi/tests/test_agent_environment.py b/dokimi/tests/test_agent_environment.py new file mode 100644 index 000000000..e1bb22b93 --- /dev/null +++ b/dokimi/tests/test_agent_environment.py @@ -0,0 +1,64 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import json +from pathlib import Path + +import pytest + +from dokimi import process +from dokimi.agent_run import adapters, runner +from dokimi.agent_run.adapters import Route +from dokimi.agent_run.runner import Agent, Run +from dokimi.agent_run.scoring import PROCESS_POINTS +from dokimi.harnesses.tasks import TaskSpec + + +@pytest.mark.parametrize(("failed_edit", "namespace_error", "correct", "expected", "probed"), [ + (True, True, False, "INCONCLUSIVE", True), + (True, False, False, "FAIL", True), + (False, True, False, "FAIL", False), + (True, True, True, "PASS", False), +]) +def test_codex_needs_an_independent_sandbox_failure_before_omitting_a_score( + tmp_path, monkeypatch, failed_edit, namespace_error, correct, expected, probed, +): + monkeypatch.setattr(adapters, "_WINDOWS", False) + monkeypatch.setattr(runner.sys, "platform", "linux") + monkeypatch.setattr(runner.shutil, "which", lambda _: "/usr/bin/codex") + monkeypatch.setenv("LITELLM_KEY", "test-route-value") + root = tmp_path / "task" + root.mkdir() + task = TaskSpec("fit", root, "Record the result.", {"usage_group": "Core", "source": "synthetic"}, + {"host_command": ["{python}", "{task_path}/check.py"]}) + controls = {"tasks": [{"task": task.name, "status": "PASS", "task_digest": runner.task_control_digest(root)}]} + monkeypatch.setattr(runner, "check_controls", lambda *args, **kwargs: controls) + probes = [] + + def run(argv, *, cwd, env, **kwargs): + if argv[1:3] == ["-m", "venv"]: + return process.Completed(tuple(argv), 0) + if argv[0] == "codex": + messages = [ + {"type": "item.completed", "item": {"type": "file_change", "status": "failed" if failed_edit else "completed", + "changes": [{"path": "result.txt", "kind": "add"}]}}, + {"type": "item.completed", "item": {"type": "agent_message", "text": "The sandbox failed.\nDONE"}}, + {"type": "turn.completed", "usage": {"input_tokens": 5, "output_tokens": 2}}, + ] + return process.Completed(tuple(argv), 0, "\n".join(map(json.dumps, messages)).encode()) + if argv[0] == "/usr/bin/codex": + assert argv[1:] == ["sandbox", "linux", "--", "/bin/true"] + assert Path(cwd, "workspace").is_dir() + assert "DOKIMI_AGENT_ROUTE_KEY" not in env.resolve() + probes.append(argv) + stderr = b"bwrap: Creating new namespace failed: Permission denied\n" if namespace_error else b"" + return process.Completed(tuple(argv), int(namespace_error), stderr_bytes=stderr) + check = {"correct": correct, "integrity": True, "no_hallucination": True, "process": PROCESS_POINTS} + return process.Completed(tuple(argv), 0, json.dumps(check).encode()) + + result = Run([task], [Agent("codex", "m")], Route("litellm", None, None), + "host", 1, tmp_path / "run", runner=run).execute() + [row] = result["sessions"] + assert (row["verdict"], row["tokens_in"], bool(probes)) == (expected, 5, probed) + assert row["false_success"] is (expected == "FAIL") + assert (row["points"] is None) == (expected == "INCONCLUSIVE") From 30b84acc42c1ffe59f0ac6edae383468a5060e47 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 22:13:02 -0800 Subject: [PATCH 3/4] fix(agent): import input errors directly Signed-off-by: Nikolay Petrov --- dokimi/dokimi/agent_run/helpers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/dokimi/agent_run/helpers.py b/dokimi/dokimi/agent_run/helpers.py index 1a953c244..92e018c9a 100644 --- a/dokimi/dokimi/agent_run/helpers.py +++ b/dokimi/dokimi/agent_run/helpers.py @@ -12,7 +12,7 @@ from pathlib import Path from typing import Any -from dokimi.utils import InputError +from dokimi.files import InputError from .scoring import usage_summary From 43b1efd87e480163b4e3f8e04ad632f1021fc55e Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 22:22:33 -0800 Subject: [PATCH 4/4] fix(agent): pass MCP flags after Windows launcher Signed-off-by: Nikolay Petrov --- dokimi/dokimi/agent_run/helpers.py | 3 ++- dokimi/tests/test_helper_effects.py | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/agent_run/helpers.py b/dokimi/dokimi/agent_run/helpers.py index 92e018c9a..c124b0bc8 100644 --- a/dokimi/dokimi/agent_run/helpers.py +++ b/dokimi/dokimi/agent_run/helpers.py @@ -49,7 +49,8 @@ def install(self, workspace: Path, config: Path, agent: str, argv: list[str]) -> if agent == "claude-code" and (server := self.root / "claude-mcp.json").is_file(): local = config / server.name shutil.copyfile(server, local) - argv[1:1] = ["--strict-mcp-config", "--mcp-config", str(local)] + # The launcher may be node.exe plus a script. Add flags before `-- PROMPT`. + argv[-2:-2] = ["--strict-mcp-config", "--mcp-config", str(local)] if agent == "codex" and (server := self.root / "codex-mcp.toml").is_file(): with (config / "config.toml").open("a", encoding="utf-8") as file: file.write("\n" + server.read_text(encoding="utf-8")) diff --git a/dokimi/tests/test_helper_effects.py b/dokimi/tests/test_helper_effects.py index 7a7d886fe..96b5a0970 100644 --- a/dokimi/tests/test_helper_effects.py +++ b/dokimi/tests/test_helper_effects.py @@ -60,7 +60,8 @@ def test_helper_rejects_empty_or_malformed_mcp(tmp_path, text): Helper("docs", tmp_path).validate() -def test_mcp_treatment_does_not_silently_pass_for_unconfigured_agent(tmp_path): +@pytest.mark.parametrize("launcher", [["claude"], ["node.exe", "C:/npm/claude/cli.js"]]) +def test_mcp_treatment_does_not_silently_pass_for_unconfigured_agent(tmp_path, launcher): mcp = tmp_path / "claude-mcp.json" mcp.write_text('{"mcpServers":{"docs":{"url":"https://example.org/mcp"}}}', encoding="utf-8") config = tmp_path / "config" @@ -69,9 +70,10 @@ def test_mcp_treatment_does_not_silently_pass_for_unconfigured_agent(tmp_path): helper.validate() assert helper.applies_to("claude-code") assert not helper.applies_to("codex") - argv = ["claude", "--print"] + argv = [*launcher, "-p", "--", "Which package is current?"] helper.install(tmp_path / "workspace", config, "claude-code", argv) - assert argv[1:4] == ["--strict-mcp-config", "--mcp-config", str(config / mcp.name)] + assert argv == [*launcher, "-p", "--strict-mcp-config", "--mcp-config", str(config / mcp.name), + "--", "Which package is current?"] assert (config / mcp.name).read_bytes() == mcp.read_bytes()