Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver-bench): fairness checks, runner support and a task manifest for the public core tasks (#6574)

cua-agents[bot]60ed3eb5f038
diff --git a/.github/workflows/ci-cua-driver-bench.yml b/.github/workflows/ci-cua-driver-bench.yml
index 8103f9006e..a21c67ac81 100644
--- a/.github/workflows/ci-cua-driver-bench.yml
+++ b/.github/workflows/ci-cua-driver-bench.yml
@@ -50,6 +50,14 @@ jobs:
uv run --no-project --python 3.12 --with pytest==8.4.2
python -m pytest -q tests probes/tests swift/tests
+ - name: Task manifest, selectors, pins and docs agree
+ working-directory: libs/cua-driver-bench/automated-eval/macos_bench
+ run: uv run --no-project --python 3.12 python tools/taskset.py check
+
+ - name: Fairness and health checks
+ working-directory: libs/cua-driver-bench/fairness
+ run: uv run --no-project --python 3.9 python -m unittest discover -s tests
+
linux-desktop:
needs: quick
if: ${{ !failure() && !cancelled() }}
diff --git a/libs/cua-driver-bench/METHOD.md b/libs/cua-driver-bench/METHOD.md
index 23efc3e90c..1567a75378 100644
--- a/libs/cua-driver-bench/METHOD.md
+++ b/libs/cua-driver-bench/METHOD.md
@@ -184,6 +184,19 @@ run. Every setup in a run uses the same seed. Only complete task blocks are
analysed. Rate-limit interruptions are retried with the same trial id;
infrastructure failures are excluded after bounded retries and reported.
+**Harness errors are re-run, never scored.** A trial is scored only when the
+harness gave the agent a working environment: the tool server answered its
+preflight and was connected in the agent's session; after the reset, every app
+the task automates accepted Apple events, loopback and the task's local web app
+were up, and the checker's programs were on its PATH; the environment stayed up;
+and the export step and the evaluator produced a result. Otherwise the attempt is
+a harness error: it is re-run with the same seed and never counted as a pass or a
+fail, and a trial that keeps failing this way is excluded and reported. The checks
+and their exact rules are in [`fairness/SPEC.md`](fairness/SPEC.md), with a
+runner-agnostic reference implementation. Seeds are per task and run index
+(`int(sha256(f"{task}:{run_index}")[:8], 16) mod 10^6`, run index from 0), the
+same for every setup and for a re-run.
+
## Analysis
`automated-eval/macos_bench/tools/analyze_v2.py`, written before any Bench v2
diff --git a/libs/cua-driver-bench/README.md b/libs/cua-driver-bench/README.md
index 324b24f3d0..cd63585ed7 100644
--- a/libs/cua-driver-bench/README.md
+++ b/libs/cua-driver-bench/README.md
@@ -7,8 +7,9 @@ harness, the agent, the model, the prompts and the limits are the same for every
setup; only the computer-use tool changes.
This directory holds the harness, the public task set and the method of
-**Bench v2**. Bench v2 is **macOS-only for now**: every task, app and
-measurement assumes a macOS 26 desktop.
+**Bench v2**. The ten Bench v2 tasks run on macOS and Linux; the three multi-app
+tasks (CDB-G02 to CDB-G04) also run on Windows. The measurement on macOS assumes
+a macOS 26 desktop.
| Path | What it is |
| --- | --- |
@@ -17,6 +18,8 @@ measurement assumes a macOS 26 desktop.
| [`automated-eval/macos_bench/TASKS.md`](automated-eval/macos_bench/TASKS.md) | The ten Bench v2 tasks: prompts, setup, checkers, limits |
| [`automated-eval/macos_bench/RUNNER.md`](automated-eval/macos_bench/RUNNER.md) | How the runner works: the `claude -p` invocation, isolation, schedule, output |
| [`taskpack/`](taskpack) | The three multi-app tasks (Electron apps, fixtures, evaluators) that CDB-G02 to CDB-G04 run |
+| [`taskpack/v2-taskset.json`](taskpack/v2-taskset.json) | The task manifest: category, split (public or held out), OS availability, conditions and health requirements of every task |
+| [`fairness/`](fairness) | Runner-agnostic fairness and health checks (tool-server preflight, Apple-events and network health, checker toolchain, environment watchdog, harness-error semantics, seeds), with a reference implementation any runner can call |
No results are published here yet. The final Bench v2 run and the held-out run
will be published together with their raw rows.
@@ -40,8 +43,77 @@ Ten tasks in three categories. Each task has a `PROVENANCE.md` next to it.
The CDB-G tasks are the GUI-only variants of pack tasks `cdb-s02` to `cdb-s04`:
the same files, with no coding tools offered. The MB and IR tasks run in
-BenchLab, a small AppKit test app built from source in this directory. A fourth
-category, Web apps & forms, has no Bench v2 task yet.
+BenchLab, a small AppKit test app built from source in this directory (with a
+Linux port in `automated-eval/macos_bench/linux`). A fourth category, Web apps &
+forms, has no Bench v2 task yet.
+
+### Platforms and conditions
+
+The manifest [`taskpack/v2-taskset.json`](taskpack/v2-taskset.json) lists the
+tasks in schedule order with their category, apps, OS availability, the
+conditions they run in, the health checks they need and their **split**:
+`public` tasks are in this repository; a `heldout` task would be kept out of it
+and read from a separate pack (`CDB_TASKPACK_HELDOUT`) through the same adapter,
+reset, export and evaluator code. All ten tasks are public today. The table is
+generated from the manifest (`tools/taskset.py doc --write`).
+
+<!-- taskset:begin (generated by tools/taskset.py doc) -->
+10 tasks in 3 categories: 10 public.
+
+| Category | Public |
+| --- | --- |
+| Multi-app workflows (`multi_app`) | 3 |
+| Precision interactions (`precision`) | 3 |
+| Interruptions & recovery (`interruptions`) | 4 |
+
+Public tasks, in schedule order:
+
+| Task | Category | Apps | OS availability | Conditions | What the agent does |
+| --- | --- | --- | --- | --- | --- |
+| CDB-G02 | multi_app | Electron mail, chat and calendar apps, LibreOffice Calc | macOS, Linux, Windows | both | Replan a schedule across mail, chat, a calendar and a Calc workbook |
+| CDB-G03 | multi_app | Electron mail app, LibreOffice Calc, GnuCash | macOS, Linux, Windows | both | Review payables across mail, a Calc workbook and a GnuCash book |
+| CDB-G04 | multi_app | Electron case tracker and manual, Google Chrome | macOS, Linux, Windows | both | Triage duplicate support cases with a tracker, a manual, an archive site and a log |
+| MB-09 | precision | BenchLab | macOS, Linux | both | Reorder a native list by drag and drop |
+| MB-10 | precision | BenchLab | macOS, Linux | foreground only | Reveal a hover-only toolbar and click one action |
+| MB-11 | precision | BenchLab | macOS, Linux | foreground only | Read a native tooltip and type the code it shows |
+| IR-01 | interruptions | BenchLab | macOS, Linux | both | Finish a two-step form through a permission-style prompt |
+| IR-02 | interruptions | BenchLab | macOS, Linux | both | Apply settings while a notification-style banner covers the button |
+| IR-03 | interruptions | BenchLab | macOS, Linux | both | Edit two notes and keep both changes through a save prompt |
+| IR-04 | interruptions | BenchLab | macOS, Linux | both | Sign up on a web page while a cookie-consent overlay appears |
+<!-- taskset:end -->
+
+The seven BenchLab tasks run on macOS and on Linux. The three multi-app tasks run
+on macOS, Linux and Windows; CDB-G03 needs GnuCash. Tasks marked "foreground
+only" skip the background condition: their readout appears only on a hover or a
+tooltip, which follows the real pointer, so no setup can do them in the
+background.
+
+## Fairness and health checks
+
+A trial is scored only when the harness gave the agent a working environment.
+[`fairness/SPEC.md`](fairness/SPEC.md) defines the checks and
+[`fairness/cdb_fairness.py`](fairness/cdb_fairness.py) implements them with the
+standard library only, as functions and a command line, so any runner can use
+them:
+
+* **Tool-server preflight.** The setup's MCP server must start, answer
+ `initialize` and list its tools (optionally pass one probe call) before the
+ agent starts, and the agent session must report it connected.
+* **Per-reset health.** After each reset: every app the task's reset or export
+ automates accepts Apple events (Automation consent present), loopback works and
+ the task's local web app is ready, and every program the checker needs
+ (`python3`, `node` for CDB-G04, `osascript`, `xattr`) is on the checker's PATH.
+* **Environment watchdog.** During the agent phase the runner probes the
+ environment; if it is lost, the trial is a harness error.
+* **Harness error, re-run, never scored.** A trial that fails any of these, or
+ whose export step or evaluator produces no result, is re-run with the same seed
+ and never counted as a pass or a fail. A trial that only ever has harness
+ errors is reported as excluded.
+* **Seeds per trial index.** `seed = int(sha256(f"{task}:{run_index}")[:8], 16) mod 10^6`,
+ with `run_index` counting from 0 per task, the same for every setup and for a
+ re-run.
+
+The runner here calls the per-reset checks before every pack-task trial.
## Method in brief
@@ -249,6 +321,8 @@ rates. Keep raw results, streams and recordings out of git.
cd automated-eval/macos_bench
python3 -m pytest tests probes/tests swift/tests # harness, checkers, sentinel (no GUI, no model)
cd ../../taskpack/tasks/shared/cdb-s02 && python3 -m unittest discover -s tests
+cd ../../../../fairness && python3 -m unittest discover -s tests # fairness and health checks
+python3 ../automated-eval/macos_bench/tools/taskset.py check # manifest, selectors, pins and docs agree
```
## Adding tasks
diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/TASKS.md b/libs/cua-driver-bench/automated-eval/macos_bench/TASKS.md
index f0cbc91f12..df7b8397d1 100644
--- a/libs/cua-driver-bench/automated-eval/macos_bench/TASKS.md
+++ b/libs/cua-driver-bench/automated-eval/macos_bench/TASKS.md
@@ -255,3 +255,15 @@ built with `xcrun swiftc -O tools/benchinput.swift -o <dir>/benchinput`.
BenchLab has other modes, used by earlier pilot tasks that are not part of
Bench v2 and are not in this repository.
+
+## Platforms, splits and the task manifest
+
+[`../../taskpack/v2-taskset.json`](../../taskpack/v2-taskset.json) lists every task with its category, apps, OS
+availability (the seven BenchLab tasks: macOS and Linux; CDB-G02 to CDB-G04: macOS, Linux and Windows), conditions,
+health requirements and split; the bench README renders it as a table. Selectors are in `probes/<ID>/task.json`.
+A task whose selector says `"split": "heldout"` is read from a separate pack with the same layout, named by
+`CDB_TASKPACK_HELDOUT` (selectors in `probes/`, trees in `tasks/`, digests in `pins.heldout.json`); `--task-set
+v2-public` / `v2-heldout` select one split. A pack task may declare native macOS apps (`kind: native`, exact
+`process_names`) and a `semantics.export` step that reads app data into the workspace after the agent and before the
+evaluator; the checker reads only the exported files. A task whose manifest entry lists `conditions` runs only in
+those when a set other than `v2` is selected, so `v2` reproduces earlier runs.
diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/bench_v2.py b/libs/cua-driver-bench/automated-eval/macos_bench/bench_v2.py
index 94c746a59c..2371ba411f 100644
--- a/libs/cua-driver-bench/automated-eval/macos_bench/bench_v2.py
+++ b/libs/cua-driver-bench/automated-eval/macos_bench/bench_v2.py
@@ -53,6 +53,42 @@ V2_TASKS: tuple[str, ...] = (
"IR-03",
"IR-04",
)
+# `../../taskpack/v2-taskset.json` lists every task with its category, OS availability, conditions and split (public,
+# or held out of this repository). `--task-set` selects a set; the default stays `v2`, so earlier runs reproduce.
+TASKSET_FILE = Path(__file__).resolve().parents[2] / "taskpack" / "v2-taskset.json"
+SPLITS = ("public", "heldout")
+
+
+def load_taskset(path: Path | None = None) -> dict[str, Any]:
+ """The task manifest: one entry per task with `id`, `category`, `split` and `os`."""
+ return json.loads((path or TASKSET_FILE).read_text("utf-8"))
+
+
+def split_of(task_id: str, taskset: dict[str, Any] | None = None) -> str:
+ """`public` or `heldout`. Tasks not in the manifest (the ten core tasks are listed too) default to public."""
+ for entry in (taskset or load_taskset())["tasks"]:
+ if entry["id"] == task_id:
+ return str(entry["split"])
+ return "public"
+
+
+def task_sets(taskset: dict[str, Any] | None = None) -> dict[str, tuple[str, ...]]:
+ """Named task sets for `--task-set`. `-public` and `-heldout` keep schedule order and only that split."""
+ data = taskset or load_taskset()
+ split = {e["id"]: e["split"] for e in data["tasks"]}
+ sets: dict[str, tuple[str, ...]] = {"v2": V2_TASKS}
+ for part in SPLITS:
+ sets[f"v2-{part}"] = tuple(t for t in V2_TASKS if split.get(t, "public") == part)
+ return sets
+
+
+def tasks_for_condition(
+ task_ids: list[str], condition: str | None, specs: dict[str, dict[str, Any]]
+) -> list[str]:
+ """The tasks of one condition: a task whose task.json lists `conditions` runs only in those."""
+ return [t for t in task_ids if condition in (specs.get(t, {}).get("conditions") or CONDITIONS)]
+
+
# v1 tasks that are not in v2, and why (the S/G split is dropped).
NOT_IN_V2: dict[str, str] = {
"CDB-S01": "its end state needs a source-code fix and a test; no GUI-only version without changing the pack",
diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/cdb_adapter.py b/libs/cua-driver-bench/automated-eval/macos_bench/cdb_adapter.py
index 6b846eb356..b85fbc1560 100644
--- a/libs/cua-driver-bench/automated-eval/macos_bench/cdb_adapter.py
+++ b/libs/cua-driver-bench/automated-eval/macos_bench/cdb_adapter.py
@@ -19,6 +19,13 @@ Mechanical adaptations, all recorded in TASKS.md:
them apart. Each app instead runs from its own copy of the pack's own `Electron.app`, with the app's window
title as its name and its own bundle id (`com.trycua.cdbbench.<name>`). Same Electron binary, same app code,
same arguments; only the bundle's name and id differ.
+
+The task manifest (`taskpack/v2-taskset.json`) also covers pack tasks under `tasks/v2/` that share `tasks/v2/_kit`. Their
+descriptors may declare native macOS apps (`kind: native`, exact `process_names`, started with `open -a`) and an
+optional `semantics.export` step that reads app data (Calendar, Reminders, Notes, Finder metadata) into the
+workspace after the agent and before the evaluator. A task whose selector says `"split": "heldout"` is read from the
+held-out pack (`CDB_TASKPACK_HELDOUT`, the same layout as the public pack), so the same adapter, reset, export and
+evaluator code runs both splits.
"""
from __future__ import annotations
@@ -45,9 +52,39 @@ ELECTRON_DIST = Path("node_modules/electron/dist")
REPO_TASKPACK = Path(__file__).resolve().parents[2] / "taskpack"
+FAIRNESS_DIR = Path(__file__).resolve().parents[2] / "fairness"
+TASKSET_FILE = REPO_TASKPACK / "v2-taskset.json"
+
+
+def fairness(): # noqa: ANN201 - the runner-agnostic checks in ../../fairness (standard library only)
+ if str(FAIRNESS_DIR) not in sys.path:
+ sys.path.insert(0, str(FAIRNESS_DIR))
+ import cdb_fairness
+
+ return cdb_fairness
-def pack_tasks_root() -> Path:
+def task_health(task_id: str) -> dict[str, Any]:
+ """The task's `health` block of the task-set manifest (automation apps, ready URLs, checker tools)."""
+ files = [TASKSET_FILE]
+ heldout = os.environ.get("CDB_TASKPACK_HELDOUT")
+ if heldout: # held-out tasks keep their full entries in the held-out pack
+ files.insert(0, Path(heldout) / "v2-taskset.heldout.json")
+ for path in files:
+ if not path.is_file():
+ continue
+ for entry in json.loads(path.read_text("utf-8"))["tasks"]:
+ if entry["id"] == task_id and entry.get("health"):
+ return dict(entry["health"])
+ return {}
+
+
+def pack_tasks_root(spec: dict[str, Any] | None = None) -> Path:
+ if spec is not None and spec.get("split") == "heldout":
+ heldout = os.environ.get("CDB_TASKPACK_HELDOUT")
+ if not heldout:
+ raise RuntimeError(f"{spec.get('id')}: a held-out task needs CDB_TASKPACK_HELDOUT")
+ return Path(heldout) / "tasks"
env = os.environ.get("CDB_TASKPACK")
if env:
return Path(env) / "tasks"
@@ -55,6 +92,21 @@ def pack_tasks_root() -> Path:
return (work if work.is_dir() else REPO_TASKPACK) / "tasks"
+def heldout_pins() -> dict[str, str]:
+ """Tree digests of the held-out pack's tasks (`<held-out pack>/pins.heldout.json` `tree_sha256`), else {}."""
+ heldout = os.environ.get("CDB_TASKPACK_HELDOUT")
+ path = Path(heldout) / "pins.heldout.json" if heldout else None
+ if path is None or not path.is_file():
+ return {}
+ return dict(json.loads(path.read_text("utf-8")).get("tree_sha256", {}))
+
+
+def shared_kit(spec: dict[str, Any]) -> Path | None:
+ """The shared helper tree a `v2/...` task's descriptor uses (`${bundle}/../_kit`), or None."""
+ kit = pack_tasks_root(spec) / spec["pack_task"] / ".." / "_kit"
+ return kit.resolve() if kit.is_dir() else None
+
+
def missing_electron_apps(root: Path | None = None) -> tuple[list[str], list[str]]:
root = root if root is not None else pack_tasks_root()
apps = [p.parent for p in sorted(root.glob("*/*/apps/*/package.json"))]
@@ -88,7 +140,9 @@ def node_facts(node: str = "/usr/local/bin/node") -> dict[str, str]:
def _descriptor(spec: dict[str, Any]) -> dict[str, Any]:
path = (
- pack_tasks_root() / spec["pack_task"] / f"platform/launch.{desktop.detect_platform()}.json"
+ pack_tasks_root(spec)
+ / spec["pack_task"]
+ / f"platform/launch.{desktop.detect_platform()}.json"
)
return json.loads(path.read_text("utf-8"))
@@ -112,6 +166,12 @@ def allowed_app_names(spec: dict[str, Any]) -> set[str]:
names.update({"libreoffice", "soffice"})
if any("gnucash" in part.lower() for part in app["command"]):
names.add("gnucash")
+ # native apps: their exact process names, and the app `open -a` names
+ names.update(str(n).lower() for n in app.get("process_names") or [])
+ if app["command"][:2] == ["/usr/bin/open", "-a"] and len(app["command"]) > 2:
+ names.add(str(app["command"][2]).lower())
+ if app.get("kind") == "native" and app.get("role"):
+ names.add(str(app["role"]).lower())
return names
@@ -262,6 +322,10 @@ def kill_policy(spec: dict[str, Any]) -> tuple[list[str], list[int]]:
names += ["soffice", "soffice.bin"]
if "gnucash" in text.lower():
names += ["gnucash", "Gnucash"]
+ for app in _descriptor(spec)["apps"]: # native apps declare their exact process names
+ for name in app.get("process_names") or []:
+ if str(name) not in names:
+ names.append(str(name))
ports = sorted({int(p) for p in re.findall(r"127\.0\.0\.1:(\d+)", text)})
return names, ports
@@ -291,7 +355,7 @@ class CdbTask:
def __init__(self, spec: dict[str, Any], artifacts: Path, seed: int | None = None) -> None:
self.spec = spec
self.seed = seed
- self.bundle = pack_tasks_root() / spec["pack_task"]
+ self.bundle = pack_tasks_root(spec) / spec["pack_task"]
self.descriptor = _descriptor(spec)
self.artifacts = artifacts
self.workspace = Path(
@@ -340,6 +404,29 @@ class CdbTask:
if done.returncode != 0:
raise RuntimeError(f"reset {step} failed: {(done.stderr or done.stdout)[-400:]}")
+ def health_check(self) -> list[dict[str, Any]]:
+ """Fairness checks once the reset is done and the apps are up, before the agent (../../fairness/SPEC.md):
+ the checker toolchain is on the PATH the evaluator gets, loopback works for tasks with a local web app,
+ and every running app the reset or export automates accepts Apple events (macOS). A failed check raises,
+ so the trial is a harness error: re-run with the same seed, never scored."""
+ fx = fairness()
+ health = task_health(str(self.spec.get("id")))
+ resolve = {"python": sys.executable, "evaluator_node": self.node["path"]}
+ programs = list(health.get("evaluator_tools") or [])
+ programs += [
+ p for p in fx.programs_of_descriptor(self.descriptor, resolve) if p not in programs
+ ]
+ checks = fx.toolchain_health(programs, path=APP_PATH)
+ if health.get("ready_urls"):
+ checks.append(fx.loopback_health())
+ if desktop.detect_platform() == "macos" and health.get("automation_apps"):
+ checks += fx.appleevents_health(health["automation_apps"])
+ bad = [c for c in checks if not c.ok]
+ self.log.append(f"health {len(checks) - len(bad)}/{len(checks)} ok")
+ if bad:
+ raise RuntimeError("harness health: " + "; ".join(f"{c.name}: {c.reason}" for c in bad))
+ return [c.to_json() for c in checks]
+
def brief(self) -> str:
brief = self.sub(self.descriptor["semantics"].get("brief", "brief.md"))
text = (self.bundle / brief).read_text("utf-8")
@@ -422,7 +509,32 @@ class CdbTask:
)
return done.stdout.strip() or None
+ def export_state(self) -> int | None:
+ """The descriptor's optional `semantics.export` step: read app data the evaluator needs into the
+ workspace, as the bench user, after the agent and before the evaluator. None when there is none."""
+ command = self.descriptor["semantics"].get("export")
+ if not command:
+ return None
+ done = self._run(command, timeout=240)
+ self.log.append(f"export rc={done.returncode}")
+ (self.artifacts / "cdb-export.stderr").write_text((done.stderr or "")[-4000:], "utf-8")
+ return done.returncode
+
def evaluate(self, agent_exit_code: int) -> dict[str, Any]:
+ """Run the export step and the evaluator. A result with `harness_error` set means the harness, not the
+ agent, failed (no export, no evaluator result): the runner re-runs that trial and never scores it."""
+ try:
+ export_rc = self.export_state()
+ except subprocess.TimeoutExpired:
+ export_rc = 124
+ if export_rc not in (None, 0):
+ return {
+ "passed": False,
+ "score": None,
+ "error": f"export step failed (rc {export_rc})",
+ "harness_error": "export_failed",
+ "diagnostics": {"export_rc": export_rc},
+ }
result = self.artifacts / "cdb-result.json"
if os.environ.get("CDB_EVAL_SUDO") == "1":
# The pack's evaluator, oracle and hidden tests live in a home the agent's user cannot read.
@@ -457,7 +569,13 @@ class CdbTask:
)
(self.artifacts / "cdb-evaluator.stderr").write_text((done.stderr or "")[-4000:], "utf-8")
if not result.is_file():
- return {"passed": False, "score": None, "error": "evaluator wrote no result"}
+ return {
+ "passed": False,
+ "score": None,
+ "error": "evaluator wrote no result",
+ "harness_error": "evaluator_no_result",
+ "diagnostics": {"export_rc": export_rc},
+ }
data = json.loads(result.read_text("utf-8"))
checks_raw = (data.get("detail") or {}).get("checks") or data.get("checks") or {}
checks = {
@@ -475,7 +593,12 @@ class CdbTask:
"passed": bool(passed),
"score": data.get("score"),
"checks": checks,
- "diagnostics": {"raw_keys": sorted(data)[:12]},
+ "diagnostics": {
+ "raw_keys": sorted(data)[:12],
+ # a task's own diagnostics (an IR task's `interruption`, for example) reach the row
+ **(data.get("diagnostics") if isinstance(data.get("diagnostics"), dict) else {}),
+ "export_rc": export_rc,
+ },
}
def stop_apps(self) -> None:
diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py b/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py
index 4c12d88643..e3279efaa1 100644
--- a/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py
+++ b/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py
@@ -86,9 +86,19 @@ class StopRun(Exception):
# ---------------------------------------------------------------- tasks
+def task_selector_files(probes_dir: Path) -> list[Path]:
+ """Selectors of this repository, plus those of the held-out pack when `CDB_TASKPACK_HELDOUT` is set
+ (`<held-out pack>/probes/<ID>/task.json`, `"split": "heldout"`)."""
+ files = sorted(probes_dir.glob("*/task.json"))
+ heldout = os.environ.get("CDB_TASKPACK_HELDOUT")
+ if heldout:
+ files += sorted((Path(heldout) / "probes").glob("*/task.json"))
+ return files
+
+
def load_tasks(probes_dir: Path) -> dict[str, pilot.Task]:
tasks: dict[str, pilot.Task] = {}
- for meta in sorted(probes_dir.glob("*/task.json")):
+ for meta in task_selector_files(probes_dir):
data = json.loads(meta.read_text("utf-8"))
if data.get("status") == "dropped":
continue # kept on disk, not run (PREREGISTRATION.md, amendment of 6 Oct)
@@ -971,6 +981,7 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]
windows=lambda win: place_window(ctx, win),
force_accessibility=ca.force_accessibility(arm),
)
+ row["health"] = cdb.health_check() # raises: a harness error, re-run, never scored
if ca.force_accessibility(arm):
row["force_accessibility_apps"] = [
line.split(":", 1)[0]
@@ -1119,6 +1130,12 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]
"score": None,
"error": f"{type(error).__name__}: {error}",
}
+ if evaluation.get("harness_error") and not failure.get("kind"):
+ # no export or no evaluator result: the harness failed, not the agent; re-run, never scored
+ failure = {
+ "kind": "harness_evaluator",
+ "message": f"{evaluation['harness_error']}: {evaluation.get('error', '')}",
+ }
except StopRun:
raise
except Exception as error: # noqa: BLE001 - record, classify as harness exception, never crash the matrix
@@ -2258,14 +2275,27 @@ def preflight(ctx: Ctx, with_models: bool = True) -> list[tuple[str, str, str]]:
add(name, status, detail)
cdb_ids = [t for t in ctx.task_ids if task_spec(ctx.tasks[t]).get("kind") == "cdb"]
if cdb_ids:
- want = ca.load_pins().get("cdb_pack", {}).get("tree_sha256", {})
+ want = dict(ca.load_pins().get("cdb_pack", {}).get("tree_sha256", {}))
+ want_heldout = cdb_adapter.heldout_pins()
+ kits_checked: set[str] = set()
for tid in cdb_ids:
spec = task_spec(ctx.tasks[tid])
+ pins_for = want_heldout if spec.get("split") == "heldout" else want
try:
probe = cdb_adapter.CdbTask(spec, ctx.run_dir)
got = probe._digest_hidden() or cdb_adapter.tree_sha256(probe.bundle)
- ok = got == want.get(spec["pack_task"])
+ ok = got == pins_for.get(spec["pack_task"])
add(f"CDB pack {tid} matches its pinned digest", "pass" if ok else "fail", got[:16])
+ kit = cdb_adapter.shared_kit(spec)
+ if kit is not None and str(kit) not in kits_checked:
+ kits_checked.add(str(kit))
+ kit_key = str(Path(spec["pack_task"]).parent / "_kit")
+ got_kit = cdb_adapter.tree_sha256(kit)
+ add(
+ f"CDB shared kit {kit_key} matches its pinned digest",
+ "pass" if got_kit == want.get(kit_key) else "fail",
+ got_kit[:16],
+ )
names = cdb_adapter.allowed_app_names(spec)
add(f"CDB {tid} descriptor readable", "pass", f"{len(names)} app names")
except Exception as error: # noqa: BLE001
@@ -2440,6 +2470,12 @@ def build_parser() -> argparse.ArgumentParser:
help="explicit task ids, in this order (default: priority order of all MB tasks)",
)
p.add_argument("--only-task", default=None)
+ p.add_argument(
+ "--task-set",
+ default="v2",
+ help="with --bench-v2: v2 (the ten registered tasks, default), or v2-public / v2-heldout for one split "
+ "(see taskpack/v2-taskset.json)",
+ )
p.add_argument(
"--phase1-runs",
type=int,
@@ -2580,7 +2616,23 @@ def make_ctx(args: argparse.Namespace) -> Ctx:
(run_dir / "trials").mkdir(exist_ok=True)
tasks = load_tasks(HERE / "probes")
bench_v2 = bool(getattr(args, "bench_v2", False))
- defaults = list(v2.V2_TASKS) if bench_v2 else [t for t in tasks if default_task(tasks, t)]
+ task_set = getattr(args, "task_set", "v2") or "v2"
+ sets = v2.task_sets()
+ if task_set not in sets:
+ raise SystemExit(f"unknown --task-set {task_set!r}; known {sorted(sets)}")
+ defaults = list(sets[task_set]) if bench_v2 else [t for t in tasks if default_task(tasks, t)]
+ if bench_v2 and task_set != "v2":
+ # a set other than v2 honours each task's `conditions` (taskpack/v2-taskset.json)
+ manifest = {e["id"]: e for e in v2.load_taskset()["tasks"]}
+ condition = getattr(args, "condition", "foreground")
+ specs = {
+ t: {**(task_spec(tasks[t]) if t in tasks else {}), **manifest.get(t, {})}
+ for t in defaults
+ }
+ for t in defaults: # a held-out entry carries no conditions; its selector does
+ if t in tasks and "conditions" in task_spec(tasks[t]):
+ specs[t]["conditions"] = task_spec(tasks[t])["conditions"]
+ defaults = v2.tasks_for_condition(defaults, condition, specs)
selected = args.tasks or ([args.only_task] if args.only_task else defaults)
if args.only_task and args.tasks is None:
selected = [args.only_task]
@@ -2817,6 +2869,10 @@ def write_manifest(ctx: Ctx, first_schedule: list[dict[str, Any]]) -> None:
"bench_version": v2.BENCH_VERSION if getattr(args, "bench_v2", False) else 1,
"bench_v2": {
"categories": v2.CATEGORIES,
+ "task_set": getattr(args, "task_set", "v2"),
+ "task_splits": {
+ t: task_spec(ctx.tasks[t]).get("split", "public") for t in ctx.task_ids
+ },
"task_categories": {t: task_spec(ctx.tasks[t]).get("category") for t in ctx.task_ids},
"gui_only_enforce": getattr(args, "gui_only_enforce", True),
"condition": getattr(args, "condition", "foreground"),
diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_taskset.py b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_taskset.py
new file mode 100644
index 0000000000..d3f41fb537
--- /dev/null
+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_taskset.py
@@ -0,0 +1,223 @@
+# SPDX-License-Identifier: FSL-1.1-MIT
+# Copyright (c) 2026 Cua AI, Inc.
+
+"""The task manifest: manifest, selectors, splits, conditions, native apps, the export step, harness errors and the
+held-out pack (no GUI, no model, no VM)."""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+HERE = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(HERE))
+
+import bench_v2 as v2 # noqa: E402
+import cdb_adapter # noqa: E402
+import run_bench as rb # noqa: E402
+
+TOOLS = HERE / "tools"
+
+
+class TaskSetTest(unittest.TestCase):
+ def test_manifest_is_the_ten_public_core_tasks(self) -> None:
+ manifest = v2.load_taskset()
+ self.assertEqual(tuple(e["id"] for e in manifest["tasks"]), v2.V2_TASKS)
+ self.assertTrue(all(e["split"] == "public" for e in manifest["tasks"]))
+ self.assertTrue(set(e["category"] for e in manifest["tasks"]) <= set(v2.CATEGORIES))
+
+ def test_platforms(self) -> None:
+ by_id = {e["id"]: e for e in v2.load_taskset()["tasks"]}
+ for tid in ("CDB-G02", "CDB-G03", "CDB-G04"):
+ self.assertEqual(by_id[tid]["os"], ["macos", "linux", "windows"], tid)
+ for tid in ("MB-09", "MB-10", "MB-11", "IR-01", "IR-02", "IR-03", "IR-04"):
+ self.assertEqual(by_id[tid]["os"], ["macos", "linux"], tid)
+ self.assertIn("GnuCash", by_id["CDB-G03"]["apps"])
+
+ def test_task_sets_and_splits(self) -> None:
+ sets = v2.task_sets()
+ self.assertEqual(sets["v2"], v2.V2_TASKS)
+ self.assertEqual(sets["v2-public"], v2.V2_TASKS)
+ self.assertEqual(sets["v2-heldout"], ())
+ fake = {
+ "tasks": [
+ {"id": t, "split": "heldout" if t in ("IR-03", "IR-04") else "public"}
+ for t in v2.V2_TASKS
+ ]
+ }
+ split = v2.task_sets(fake)
+ self.assertEqual(split["v2-heldout"], ("IR-03", "IR-04"))
+ self.assertNotIn("IR-03", split["v2-public"])
+ self.assertEqual(v2.split_of("IR-03", fake), "heldout")
+ self.assertEqual(v2.split_of("MB-09", fake), "public")
+
+ def test_conditions(self) -> None:
+ specs = {"MB-11": {"conditions": ["foreground"]}, "MB-09": {}}
+ self.assertEqual(v2.tasks_for_condition(["MB-09", "MB-11"], "background", specs), ["MB-09"])
+ self.assertEqual(
+ v2.tasks_for_condition(["MB-09", "MB-11"], "foreground", specs), ["MB-09", "MB-11"]
+ )
+
+ def test_core_tasks_have_selectors(self) -> None:
+ tasks = rb.load_tasks(HERE / "probes")
+ for tid in v2.V2_TASKS:
+ with self.subTest(task=tid):
+ self.assertIn(tid, tasks)
+ self.assertEqual(v2.validate_tasks({tid: rb.task_spec(tasks[tid])}, [tid]), [])
+
+ def test_taskset_tool_check_passes(self) -> None:
+ done = subprocess.run(
+ [sys.executable, str(TOOLS / "taskset.py"), "check"], capture_output=True, text=True
+ )
+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
+
+ def test_health_requirements(self) -> None:
+ by_id = {e["id"]: e for e in v2.load_taskset()["tasks"]}
+ self.assertIn("node", by_id["CDB-G04"]["health"]["evaluator_tools"])
+ self.assertEqual(by_id["MB-11"]["conditions"], ["foreground"])
+
+
+NATIVE = {
+ "semantics": {
+ "reset": {"setup": ["true"], "verify": ["true"]},
+ "export": ["${python}", "export.py", "--workspace", "${workspace}"],
+ "evaluate": ["${python}", "evaluate.py", "--result", "${result}"],
+ },
+ "workspace_root": "${HOME}/cdb-synthetic-native",
+ "apps": [
+ {
+ "id": "calendar",
+ "kind": "native",
+ "role": "Calendar",
+ "command": ["/usr/bin/open", "-a", "Calendar"],
+ "process_names": ["Calendar"],
+ }
+ ],
+}
+
+
[email protected](sys.platform == "darwin", "macOS descriptors")
+class NativeExportTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tmp = Path(tempfile.mkdtemp())
+ self.bundle = self.tmp / "tasks" / "v2" / "syn-native"
+ (self.bundle / "platform").mkdir(parents=True)
+ (self.bundle / "platform" / "launch.macos.json").write_text(json.dumps(NATIVE))
+ (self.tmp / "tasks" / "v2" / "_kit").mkdir()
+ self.env = mock.patch.dict(
+ os.environ, {"CDB_TASKPACK": str(self.tmp), "CDB_EVAL_SUDO": "0"}
+ )
+ self.env.start()
+ self.spec = {"id": "SYN-01", "kind": "cdb", "pack_task": "v2/syn-native"}
+ self.artifacts = self.tmp / "artifacts"
+ self.artifacts.mkdir()
+
+ def tearDown(self) -> None:
+ self.env.stop()
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def write(self, export_rc: int, result: dict | None) -> None:
+ (self.bundle / "export.py").write_text(f"import sys\nsys.exit({export_rc})\n")
+ body = "import sys, json\n"
+ if result is not None:
+ body += f"open(sys.argv[sys.argv.index('--result') + 1], 'w').write({json.dumps(json.dumps(result))})\n"
+ (self.bundle / "evaluate.py").write_text(body)
+
+ def test_native_app_names_and_kill_policy(self) -> None:
+ self.assertIn("calendar", cdb_adapter.allowed_app_names(self.spec))
+ names, _ = cdb_adapter.kill_policy(self.spec)
+ self.assertIn("Calendar", names)
+ self.assertEqual(
+ cdb_adapter.shared_kit(self.spec), (self.tmp / "tasks" / "v2" / "_kit").resolve()
+ )
+
+ def test_export_then_evaluate_and_task_diagnostics(self) -> None:
+ self.write(
+ 0,
+ {
+ "passed": True,
+ "score": 1.0,
+ "checks": {"a": {"passed": True}},
+ "diagnostics": {"interruption": {"shown": True}},
+ },
+ )
+ verdict = cdb_adapter.CdbTask(self.spec, self.artifacts).evaluate(0)
+ self.assertTrue(verdict["passed"])
+ self.assertNotIn("harness_error", verdict)
+ self.assertEqual(verdict["diagnostics"]["export_rc"], 0)
+ self.assertEqual(verdict["diagnostics"]["interruption"], {"shown": True})
+
+ def test_failed_export_is_a_harness_error(self) -> None:
+ self.write(3, {"passed": True, "score": 1.0, "checks": {}})
+ verdict = cdb_adapter.CdbTask(self.spec, self.artifacts).evaluate(0)
+ self.assertEqual(verdict["harness_error"], "export_failed")
+ self.assertFalse(verdict["passed"])
+
+ def test_no_evaluator_result_is_a_harness_error(self) -> None:
+ self.write(0, None)
+ verdict = cdb_adapter.CdbTask(self.spec, self.artifacts).evaluate(0)
+ self.assertEqual(verdict["harness_error"], "evaluator_no_result")
+
+ def test_health_check_raises_on_a_missing_checker_tool(self) -> None:
+ task = cdb_adapter.CdbTask(self.spec, self.artifacts)
+ with mock.patch.object(
+ cdb_adapter, "task_health", return_value={"evaluator_tools": ["no-such-tool-xyz"]}
+ ):
+ with self.assertRaisesRegex(RuntimeError, "no-such-tool-xyz"):
+ task.health_check()
+ with mock.patch.object(
+ cdb_adapter, "task_health", return_value={"evaluator_tools": ["python3"]}
+ ):
+ checks = task.health_check()
+ self.assertTrue(all(c["ok"] for c in checks))
+
+
[email protected](sys.platform == "darwin", "macOS descriptors")
+class HeldOutPackTest(unittest.TestCase):
+ """A held-out task runs from CDB_TASKPACK_HELDOUT with the same code as a public one."""
+
+ def test_heldout_selector_root_and_pins(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ (root / "tasks" / "v2" / "syn-held" / "platform").mkdir(parents=True)
+ (root / "tasks" / "v2" / "syn-held" / "platform" / "launch.macos.json").write_text(
+ json.dumps(NATIVE)
+ )
+ (root / "probes" / "SYN-99").mkdir(parents=True)
+ selector = {
+ "id": "SYN-99",
+ "category": "multi_app",
+ "kind": "cdb",
+ "pack_task": "v2/syn-held",
+ "split": "heldout",
+ "coding_tools": False,
+ "timeout_s": 360,
+ "max_turns": 45,
+ }
+ (root / "probes" / "SYN-99" / "task.json").write_text(json.dumps(selector))
+ (root / "pins.heldout.json").write_text(
+ json.dumps({"tree_sha256": {"v2/syn-held": "abc"}})
+ )
+ with mock.patch.dict(os.environ, {"CDB_TASKPACK_HELDOUT": str(root)}):
+ tasks = rb.load_tasks(HERE / "probes")
+ self.assertIn("SYN-99", tasks)
+ spec = rb.task_spec(tasks["SYN-99"])
+ task = cdb_adapter.CdbTask(spec, root)
+ self.assertEqual(task.bundle, root / "tasks" / "v2" / "syn-held")
+ self.assertEqual(cdb_adapter.heldout_pins(), {"v2/syn-held": "abc"})
+ with mock.patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("CDB_TASKPACK_HELDOUT", None)
+ self.assertNotIn("SYN-99", rb.load_tasks(HERE / "probes"))
+ with self.assertRaisesRegex(RuntimeError, "CDB_TASKPACK_HELDOUT"):
+ cdb_adapter.pack_tasks_root(spec)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tools/taskset.py b/libs/cua-driver-bench/automated-eval/macos_bench/tools/taskset.py
new file mode 100644
index 0000000000..dab638b99c
--- /dev/null
+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tools/taskset.py
@@ -0,0 +1,260 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: FSL-1.1-MIT
+# Copyright (c) 2026 Cua AI, Inc.
+
+"""The task manifest (`taskpack/v2-taskset.json`): check it, render its docs table, split it.
+
+ tools/taskset.py check # manifest, selectors, pack trees, pins and docs agree
+ tools/taskset.py doc [--write] # the README task table (between the taskset markers)
+ tools/taskset.py split --heldout ID1,ID2 --out DIR
+
+`split` moves the named tasks out of this repository into DIR, a held-out pack with the public pack's layout
+(`DIR/tasks/v2/<task>`, a copy of `DIR/tasks/v2/_kit`, `DIR/probes/<ID>/task.json`, `DIR/pins.heldout.json` and
+`DIR/v2-taskset.heldout.json` with their full manifest entries). In this repository their manifest entries keep
+only id, category, set and `"split": "heldout"`, their pins are removed, and the docs list them by category and
+count. The runner reads them from `CDB_TASKPACK_HELDOUT=DIR` with the same adapter, reset, export and evaluator code
+as public tasks. Keep DIR in a private repository; it is never committed here.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import sys
+from collections import Counter
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent.parent
+BENCH = HERE.parents[1]
+sys.path.insert(0, str(HERE))
+
+import bench_v2 as v2 # noqa: E402
+import cdb_adapter # noqa: E402
+
+MANIFEST = BENCH / "taskpack" / "v2-taskset.json"
+PINS = HERE / "pins.json"
+PROBES = HERE / "probes"
+TASKS_ROOT = cdb_adapter.REPO_TASKPACK / "tasks"
+README = BENCH / "README.md"
+BEGIN, END = "<!-- taskset:begin (generated by tools/taskset.py doc) -->", "<!-- taskset:end -->"
+OS_NAMES = {"macos": "macOS", "linux": "Linux", "windows": "Windows"}
+CROSS_OS = {
+ "libreoffice": "cross-OS candidate (LibreOffice)",
+ "browser": "cross-OS candidate (Chrome)",
+ "libreoffice+browser": "cross-OS candidate (LibreOffice, Chrome)",
+}
+
+
+def os_label(entry: dict) -> str:
+ label = ", ".join(OS_NAMES[o] for o in entry["os"])
+ if entry["os"] == ["macos"] and not entry.get("cross_os_candidate"):
+ return "macOS only"
+ candidate = CROSS_OS.get(entry.get("cross_os_candidate") or "")
+ return f"{label}; {candidate}" if candidate else label
+
+
+def load() -> dict:
+ return json.loads(MANIFEST.read_text("utf-8"))
+
+
+def render(manifest: dict) -> str:
+ tasks = manifest["tasks"]
+ public = [e for e in tasks if e["split"] == "public"]
+ heldout = [e for e in tasks if e["split"] == "heldout"]
+ categories = {e["category"] for e in tasks}
+ lines = [
+ f"{len(tasks)} tasks in {len(categories)} categories: {len(public)} public"
+ + (f", {len(heldout)} held out." if heldout else "."),
+ "",
+ "| Category | Public |" + (" Held out |" if heldout else ""),
+ "| --- | --- |" + (" --- |" if heldout else ""),
+ ]
+ for cat, label in v2.CATEGORIES.items():
+ if cat not in categories:
+ continue
+ row = f"| {label} (`{cat}`) | {sum(e['category'] == cat for e in public)} |"
+ if heldout:
+ row += f" {sum(e['category'] == cat for e in heldout)} |"
+ lines.append(row)
+ lines += [
+ "",
+ "Public tasks, in schedule order:",
+ "",
+ "| Task | Category | Apps | OS availability | Conditions | What the agent does |",
+ "| --- | --- | --- | --- | --- | --- |",
+ ]
+ for e in public:
+ conditions = "both" if len(e["conditions"]) == 2 else "foreground only"
+ lines.append(
+ f"| {e['id']} | {e['category']} | {', '.join(e['apps'])} | "
+ f"{os_label(e)} | {conditions} | {e['title']} |"
+ )
+ if heldout:
+ counts = Counter(e["category"] for e in heldout)
+ lines += [
+ "",
+ "Held-out tasks are not in this repository. They are listed only by category and count: "
+ + ", ".join(
+ f"{v2.CATEGORIES[c]} {n}"
+ for c, n in sorted(counts.items(), key=lambda kv: list(v2.CATEGORIES).index(kv[0]))
+ )
+ + ".",
+ ]
+ return "\n".join(lines) + "\n"
+
+
+def doc(write: bool) -> bool:
+ text = README.read_text("utf-8")
+ start, end = text.index(BEGIN) + len(BEGIN), text.index(END)
+ new = text[:start] + "\n" + render(load()) + text[end:]
+ if write and new != text:
+ README.write_text(new, "utf-8")
+ return new == text
+
+
+def check() -> list[str]:
+ manifest = load()
+ problems: list[str] = []
+ ids = [e["id"] for e in manifest["tasks"]]
+ if tuple(ids[: len(v2.V2_TASKS)]) != v2.V2_TASKS:
+ problems.append("manifest does not start with bench_v2.V2_TASKS, in order")
+ pins = json.loads(PINS.read_text("utf-8"))["cdb_pack"]["tree_sha256"]
+ for e in manifest["tasks"]:
+ if e["category"] not in v2.CATEGORIES:
+ problems.append(f"{e['id']}: unknown category {e['category']}")
+ if e["split"] not in v2.SPLITS:
+ problems.append(f"{e['id']}: unknown split {e['split']}")
+ selector = PROBES / e["id"] / "task.json"
+ if e["split"] == "heldout":
+ if selector.exists():
+ problems.append(f"{e['id']}: held out but its selector is in this repository")
+ if set(e) - {"id", "category", "split", "set"}:
+ problems.append(
+ f"{e['id']}: held-out manifest entry carries more than id, category, split, set"
+ )
+ continue
+ if not selector.is_file():
+ problems.append(f"{e['id']}: no selector")
+ continue
+ spec = json.loads(selector.read_text("utf-8"))
+ if spec.get("category") != e["category"]:
+ problems.append(f"{e['id']}: selector category differs")
+ if e.get("pack_task"):
+ if spec.get("pack_task") != e["pack_task"]:
+ problems.append(f"{e['id']}: selector pack_task differs")
+ if not (TASKS_ROOT / e["pack_task"]).is_dir():
+ problems.append(f"{e['id']}: pack tree missing")
+ elif pins.get(e["pack_task"]) != cdb_adapter.tree_sha256(TASKS_ROOT / e["pack_task"]):
+ problems.append(
+ f"{e['id']}: pin differs from the tree (tools/check_pack_pins.py --write)"
+ )
+ kit = TASKS_ROOT / "v2" / "_kit"
+ if kit.is_dir() and pins.get("v2/_kit") != cdb_adapter.tree_sha256(kit):
+ problems.append("v2/_kit: pin differs from the tree")
+ pack_dir = TASKS_ROOT / "v2"
+ on_disk = (
+ {p.name for p in pack_dir.iterdir() if (p / "task.v2.json").is_file()}
+ if pack_dir.is_dir()
+ else set()
+ )
+ listed = {
+ Path(e["pack_task"]).name
+ for e in manifest["tasks"]
+ if (e.get("pack_task") or "").startswith("v2/")
+ }
+ if on_disk - listed:
+ problems.append(f"pack trees not in the manifest: {sorted(on_disk - listed)}")
+ if not doc(write=False):
+ problems.append("README task table is stale (tools/taskset.py doc --write)")
+ return problems
+
+
+def split(heldout: list[str], out: Path) -> None:
+ manifest = load()
+ by_id = {e["id"]: e for e in manifest["tasks"]}
+ unknown = [
+ t
+ for t in heldout
+ if t not in by_id or not (by_id[t].get("pack_task") or "").startswith("v2/")
+ ]
+ if unknown:
+ raise SystemExit(f"only pack tasks under tasks/v2 can be held out; not: {unknown}")
+ pins_doc = json.loads(PINS.read_text("utf-8"))
+ pins = pins_doc["cdb_pack"]["tree_sha256"]
+ out_tasks = out / "tasks" / "v2"
+ out_tasks.mkdir(parents=True, exist_ok=True)
+ if not (out_tasks / "_kit").exists():
+ shutil.copytree(TASKS_ROOT / "v2" / "_kit", out_tasks / "_kit")
+ shutil.copy2(TASKS_ROOT / "v2" / "run_tests.py", out_tasks / "run_tests.py")
+ heldout_pins_path = out / "pins.heldout.json"
+ heldout_pins = (
+ json.loads(heldout_pins_path.read_text("utf-8"))
+ if heldout_pins_path.is_file()
+ else {"tree_sha256": {}}
+ )
+ heldout_pins["tree_sha256"]["v2/_kit"] = cdb_adapter.tree_sha256(out_tasks / "_kit")
+ full_path = out / "v2-taskset.heldout.json"
+ full = json.loads(full_path.read_text("utf-8")) if full_path.is_file() else {"tasks": []}
+ for tid in heldout:
+ entry = by_id[tid]
+ if entry["split"] == "heldout":
+ continue
+ src = TASKS_ROOT / entry["pack_task"]
+ shutil.move(str(src), str(out_tasks / src.name))
+ heldout_pins["tree_sha256"][entry["pack_task"]] = pins.pop(entry["pack_task"])
+ selector = json.loads((PROBES / tid / "task.json").read_text("utf-8"))
+ selector["split"] = "heldout"
+ (out / "probes" / tid).mkdir(parents=True, exist_ok=True)
+ (out / "probes" / tid / "task.json").write_text(
+ json.dumps(selector, indent=2) + "\n", "utf-8"
+ )
+ shutil.rmtree(PROBES / tid)
+ full["tasks"] = [e for e in full["tasks"] if e["id"] != tid] + [
+ {**entry, "split": "heldout"}
+ ]
+ reduced = {
+ "id": tid,
+ "category": entry["category"],
+ "split": "heldout",
+ "set": entry["set"],
+ }
+ entry.clear()
+ entry.update(reduced)
+ PINS.write_text(json.dumps(pins_doc, indent=2) + "\n", "utf-8")
+ MANIFEST.write_text(json.dumps(manifest, indent=2) + "\n", "utf-8")
+ heldout_pins_path.write_text(json.dumps(heldout_pins, indent=2) + "\n", "utf-8")
+ full_path.write_text(json.dumps(full, indent=2) + "\n", "utf-8")
+ doc(write=True)
+ print(
+ f"held out {len(heldout)} task(s) into {out}; run tools/taskset.py check, and keep {out} private"
+ )
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ sub = parser.add_subparsers(dest="command", required=True)
+ sub.add_parser("check")
+ p = sub.add_parser("doc")
+ p.add_argument("--write", action="store_true")
+ p = sub.add_parser("split")
+ p.add_argument("--heldout", required=True, help="comma-separated task ids")
+ p.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args()
+ if args.command == "check":
+ problems = check()
+ for problem in problems:
+ print("FAIL", problem)
+ print("ok" if not problems else f"{len(problems)} problem(s)")
+ return 1 if problems else 0
+ if args.command == "doc":
+ same = doc(args.write)
+ if not args.write:
+ print(render(load()))
+ return 0 if same or args.write else 1
+ split([t.strip() for t in args.heldout.split(",") if t.strip()], args.out.resolve())
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/libs/cua-driver-bench/fairness/SPEC.md b/libs/cua-driver-bench/fairness/SPEC.md
new file mode 100644
index 0000000000..20760486ca
--- /dev/null
+++ b/libs/cua-driver-bench/fairness/SPEC.md
@@ -0,0 +1,88 @@
+# Fairness and health checks
+
+A benchmark comparison is only fair if every setup gets a working environment. When the harness fails (the tool
+server never started, the app's data could not be read back, the environment went away), the agent did not fail,
+and scoring that trial as a fail would penalise whichever setup happened to hit the fault. This document defines
+the checks Cua Driver Bench runs around every trial, what a failure means, and how results are counted. It is
+runner-agnostic: [`cdb_fairness.py`](cdb_fairness.py) implements every check with the Python standard library only
+(3.9 or later), as functions and as a command line, so any runner can call it. The bench's own runner
+(`automated-eval/macos_bench`) uses it; so can an AgentEnv provider or a hosted evaluation service.
+
+## Outcomes
+
+Every trial attempt has exactly one outcome:
+
+| Outcome | Meaning | Counted |
+| --- | --- | --- |
+| `pass` | The task's checker passed every required check, and no GUI-only rule was broken | Yes |
+| `fail` | The checker ran on a healthy environment and did not pass | Yes |
+| `harness_error` | A check below failed, or the export step or the evaluator produced no result | **Never** |
+
+A `harness_error` attempt is **re-run with the same seed** (same task, run index and condition, same setup). The
+latest `pass` or `fail` attempt of a trial is the one that counts. A trial whose attempts are all harness errors
+after the runner's retry limit (default 3 attempts) is reported as **excluded**, with its last reason, and is never
+counted as a fail. Reports give the number of harness-error attempts and excluded trials per setup.
+
+`cdb_fairness.classify(row)`, `scored_rows(rows)`, `rerun_plan(rows)` and `summarize(rows)` implement these rules on
+trial rows with `arm` (or `setup`), `task`, `run_index`, `condition`, `passed`, and optionally `harness_error` (a
+reason), `status` (`harness_error` or `infra_error`) and `health` (a list of check results). The command line
+`cdb_fairness.py summarize rows.jsonl` prints the scored count, passes, and the trials to re-run or exclude.
+
+## Seeds
+
+```text
+seed = int(sha256(f"{task_id}:{run_index}").hexdigest()[:8], 16) % 1_000_000
+```
+
+`run_index` counts from 0 for each task: trial k of a task (counting from 1) has run index k-1. Every setup gets the
+same seed for the same task and run index, so setups are compared on the same task variants, and a re-run of a
+harness-error attempt keeps its seed. `cdb_fairness.trial_seed(task, run_index)`; `cdb_fairness.py seed TASK N`.
+
+## The checks
+
+Each check returns `ok`, a short `reason` and `detail`. Any `ok: false` makes the attempt a `harness_error`. The
+command line prints one JSON object and exits 0 when every check passed, **97** on a harness error, 2 on bad usage.
+
+| When | Check | Function / command | Fails when |
+| --- | --- | --- | --- |
+| Before the agent starts | Tool-server preflight | `mcp_preflight_from_config(mcp.json)` / `cdb_fairness.py mcp MCP_JSON [--server NAME] [--probe-tool T]` | The setup's MCP server does not start, does not answer `initialize`, lists no tools within the timeout (default 60 s), or a given probe tool (for example a permissions check) returns an error |
+| First event of the agent session | Session tool servers | `session_servers_connected(init_event)` / `cdb_fairness.py session-init STREAM` | The agent session's own `init` event shows a tool server that is not `connected` |
+| After every reset | Apple events (macOS) | `appleevents_health(apps)` / `cdb_fairness.py appleevents APP ...` | An app the task's reset or export automates refuses a harmless Apple event: Automation consent missing or pending (-1743, -1744), sender not entitled (-10004), time-out (-1712), app gone (-600, -609) |
+| After every reset | Network | `network_health(urls, require_lease)` / `cdb_fairness.py network [--url URL ...] [--require-lease]` | Loopback (127.0.0.1) cannot accept a connection; a task app's ready URL does not answer 200; with `--require-lease`, the environment has no usable IPv4 address (none, or self-assigned 169.254/16, a failed DHCP lease) |
+| After every reset | Checker toolchain | `toolchain_health(programs, path)` with `programs_of_descriptor(descriptor)` / `cdb_fairness.py toolchain [PROGRAM ...] --descriptor D --path PATH` | A program the reset, export or checker needs is not on the PATH they get, or does not start (`python3`, `node` for a checker that starts the task's own web server, `osascript`, `xattr`) |
+| During the agent phase | Environment watchdog | `EnvWatchdog(probe, interval, misses)` | The runner's liveness probe (the VM answers, the desktop session and the tool server process exist) fails `misses` times in a row (default 3, every 10 s) |
+| After the agent | Export and evaluator | runner | The task's `semantics.export` step exits non-zero, or the evaluator writes no result |
+
+What each task needs is in the task-set manifest
+([`../taskpack/v2-taskset.json`](../taskpack/v2-taskset.json)), in each task's `health` block:
+
+* `automation_apps`: the apps to pass to the Apple-events check;
+* `ready_urls`: the local web app's ready URL (the runner waits on it when it starts the app);
+* `evaluator_tools`: the programs for the toolchain check, in addition to those of the launch descriptor.
+
+## Runner duties
+
+A conforming runner:
+
+1. derives seeds as above and records `run_index` and `seed` in every row;
+2. runs the tool-server preflight before the agent, and the session check on the agent's first event;
+3. after each reset, runs the Apple-events check for the task's `automation_apps` (macOS), the network check, and
+ the toolchain check with the PATH and interpreters the evaluator will get;
+4. runs an environment watchdog during the agent phase when the agent and the environment are on different
+ machines;
+5. records every check in the row (`health`), marks a failed attempt `harness_error` with its reason, re-runs it
+ with the same seed, and counts only `pass` and `fail`;
+6. reports harness-error attempts and excluded trials per setup next to the scores.
+
+Health checks run as the same user, with the same environment, as the reset, export and evaluator they protect.
+None of them touches task state, so running them never changes a task's outcome.
+
+## How the bench's own runner maps onto this
+
+`automated-eval/macos_bench/run_bench.py` records a harness error as `status: infra_error` with an
+`infra_failure` kind (`mcp_start`, `tool_setup`, `harness_exception`, `harness_evaluator`, ...), re-runs it once and
+then excludes it (`excluded: true`), and never counts it as a pass or a fail. `cdb_adapter.CdbTask.health_check`
+runs the toolchain, loopback and Apple-events checks from this module after every pack-task reset, once the task's apps are up; a failed check raises, so
+the attempt becomes a `harness_exception`. An export step that fails or an evaluator that writes no result becomes
+`harness_evaluator`. The runner runs the agent in the same macOS VM as the apps, so it needs no separate watchdog;
+a runner that drives a remote VM should add one.
diff --git a/libs/cua-driver-bench/fairness/cdb_fairness.py b/libs/cua-driver-bench/fairness/cdb_fairness.py
new file mode 100644
index 0000000000..262fef4f39
--- /dev/null
+++ b/libs/cua-driver-bench/fairness/cdb_fairness.py
@@ -0,0 +1,707 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: FSL-1.1-MIT
+# Copyright (c) 2026 Cua AI, Inc.
+
+"""Runner-agnostic fairness and health checks for Cua Driver Bench trials.
+
+The rules are in SPEC.md next to this file. This module is the reference implementation: standard library
+only, Python 3.9 or later, no import from any runner, so any runner (the bench's own `macos_bench`, an
+AgentEnv provider, a hosted evaluation service) can import it or call its command line.
+
+Every check returns a `Check` with `ok`, a short `reason` and `detail`. A failed check means a HARNESS ERROR:
+the trial is re-run with the same seed and is never scored as an agent failure (see `classify` and
+`scored_rows`).
+
+Command line (one JSON object on stdout; exit 0 when healthy, 97 on a harness error, 2 on bad usage):
+
+ cdb_fairness.py seed TASK RUN_INDEX
+ cdb_fairness.py mcp MCP_JSON [--server NAME] [--timeout S] [--probe-tool NAME [--probe-args JSON]]
+ cdb_fairness.py session-init STREAM_JSONL
+ cdb_fairness.py appleevents APP [APP ...] [--timeout S] [--launch]
+ cdb_fairness.py network [--url URL ...] [--require-lease]
+ cdb_fairness.py toolchain [PROGRAM ...] [--descriptor DESCRIPTOR_JSON] [--path PATH]
+ cdb_fairness.py summarize ROWS_JSONL
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import ipaddress
+import json
+import os
+import re
+import select
+import shutil
+import socket
+import subprocess
+import sys
+import threading
+import time
+import urllib.request
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Iterable, Optional
+
+EXIT_OK = 0
+EXIT_HARNESS_ERROR = 97
+SEED_MODULUS = 1_000_000
+
+PASS, FAIL, HARNESS_ERROR = "pass", "fail", "harness_error"
+
+
+@dataclass
+class Check:
+ name: str
+ ok: bool
+ reason: str = ""
+ detail: dict[str, Any] = field(default_factory=dict)
+
+ def to_json(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+# ------------------------------------------------------------------ seeds
+
+
+def trial_seed(task_id: str, run_index: int) -> int:
+ """The seed of a task's run: the first 8 hex digits of sha256("<task>:<run_index>"), mod 10^6.
+
+ `run_index` counts from 0 per task (trial k of a task, counting from 1, has run_index k-1). Every setup
+ gets the same seed for the same task and run index, and a re-run of a harness-error trial keeps it."""
+ if run_index < 0:
+ raise ValueError("run_index counts from 0")
+ digest = hashlib.sha256(f"{task_id}:{run_index}".encode()).hexdigest()
+ return int(digest[:8], 16) % SEED_MODULUS
+
+
+# ------------------------------------------------------------------ tool server (MCP) preflight
+
+
+def _read_message(
+ proc: subprocess.Popen, deadline: float, buffer: bytearray
+) -> Optional[dict[str, Any]]:
+ """One newline-delimited JSON-RPC message from the server's stdout, or None at the deadline."""
+ assert proc.stdout is not None
+ fd = proc.stdout.fileno()
+ while True:
+ newline = buffer.find(b"\n")
+ if newline >= 0:
+ line = bytes(buffer[:newline]).strip()
+ del buffer[: newline + 1]
+ if not line:
+ continue
+ try:
+ return json.loads(line)
+ except ValueError:
+ continue # a server may log non-JSON lines to stdout; skip them
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return None
+ ready, _, _ = select.select([fd], [], [], remaining)
+ if not ready:
+ return None
+ chunk = os.read(fd, 65536)
+ if not chunk:
+ return None
+ buffer.extend(chunk)
+
+
+def _await_id(
+ proc: subprocess.Popen, want: int, deadline: float, buffer: bytearray
+) -> Optional[dict[str, Any]]:
+ while True:
+ message = _read_message(proc, deadline, buffer)
+ if message is None or message.get("id") == want:
+ return message
+
+
+def mcp_preflight(
+ command: list[str],
+ env: Optional[dict[str, str]] = None,
+ timeout: float = 60.0,
+ probe_tool: Optional[str] = None,
+ probe_args: Optional[dict[str, Any]] = None,
+ name: str = "server",
+) -> Check:
+ """Start a stdio MCP server, `initialize`, list its tools and optionally call one probe tool.
+
+ Healthy when the server answers `initialize` and `tools/list` with at least one tool within `timeout`,
+ and the probe tool (when given) returns a result that is not an error. The agent must never start a trial
+ without a working tool server: a failure here is a harness error, not an agent failure."""
+ check = Check(f"mcp:{name}", False)
+ started = time.monotonic()
+ deadline = started + timeout
+ try:
+ proc = subprocess.Popen(
+ command,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ env={**os.environ, **(env or {})},
+ )
+ except OSError as error:
+ check.reason = f"cannot start the tool server: {error}"
+ return check
+ buffer = bytearray()
+
+ def send(message: dict[str, Any]) -> None:
+ assert proc.stdin is not None
+ proc.stdin.write((json.dumps(message) + "\n").encode())
+ proc.stdin.flush()
+
+ try:
+ send(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "clientInfo": {"name": "cdb-fairness-preflight", "version": "1"},
+ },
+ }
+ )
+ init = _await_id(proc, 1, deadline, buffer)
+ if init is None or "result" not in init:
+ check.reason = (
+ "no initialize result" if init is None else f"initialize error: {init.get('error')}"
+ )
+ return check
+ send({"jsonrpc": "2.0", "method": "notifications/initialized"})
+ send({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}})
+ listed = _await_id(proc, 2, deadline, buffer)
+ tools = ((listed or {}).get("result") or {}).get("tools") or []
+ check.detail["tools"] = len(tools)
+ if not tools:
+ check.reason = "tools/list returned no tools" if listed else "no tools/list result"
+ return check
+ if probe_tool:
+ if probe_tool not in {t.get("name") for t in tools}:
+ check.reason = f"probe tool {probe_tool!r} is not offered"
+ return check
+ send(
+ {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "tools/call",
+ "params": {"name": probe_tool, "arguments": probe_args or {}},
+ }
+ )
+ called = _await_id(proc, 3, deadline, buffer)
+ result = (called or {}).get("result")
+ if result is None or result.get("isError"):
+ check.reason = f"probe tool {probe_tool!r} failed"
+ check.detail["probe"] = (called or {}).get("error") or result
+ return check
+ check.ok = True
+ check.reason = "ready"
+ return check
+ except (BrokenPipeError, OSError) as error:
+ check.reason = f"tool server exited: {error}"
+ return check
+ finally:
+ check.detail["seconds"] = round(time.monotonic() - started, 2)
+ try:
+ proc.kill()
+ proc.wait(timeout=5)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ for stream in (proc.stdin, proc.stdout):
+ try:
+ if stream is not None:
+ stream.close()
+ except OSError:
+ pass
+
+
+def mcp_preflight_from_config(
+ config_path: Path,
+ server: Optional[str] = None,
+ timeout: float = 60.0,
+ probe_tool: Optional[str] = None,
+ probe_args: Optional[dict[str, Any]] = None,
+) -> list[Check]:
+ """`mcp_preflight` for each stdio server of an `mcpServers` config (or only `server`)."""
+ servers = json.loads(Path(config_path).read_text("utf-8")).get("mcpServers", {})
+ if server is not None:
+ servers = {server: servers[server]} if server in servers else {}
+ if not servers:
+ return [Check("mcp", False, "no MCP server in the config")]
+ out = []
+ for name, entry in servers.items():
+ if "command" not in entry:
+ out.append(Check(f"mcp:{name}", False, "not a stdio server (no command)"))
+ continue
+ out.append(
+ mcp_preflight(
+ [entry["command"], *entry.get("args", [])],
+ env=entry.get("env"),
+ timeout=timeout,
+ probe_tool=probe_tool,
+ probe_args=probe_args,
+ name=name,
+ )
+ )
+ return out
+
+
+def session_servers_connected(init_event: dict[str, Any]) -> Check:
+ """The agent session's own view of its tool servers, from a Claude Code `system`/`init` stream event
+ (`mcp_servers: [{"name", "status"}]`). Every server must be `connected`; one that is `failed` or
+ `pending` means the agent ran without its tools, so the trial is a harness error."""
+ servers = init_event.get("mcp_servers") or []
+ bad = [s.get("name", "?") for s in servers if s.get("status") != "connected"]
+ if not servers:
+ return Check("session_init", False, "the session reported no tool server")
+ if bad:
+ return Check(
+ "session_init",
+ False,
+ "tool server not connected: " + ",".join(bad),
+ {"servers": servers},
+ )
+ return Check("session_init", True, "connected", {"servers": servers})
+
+
+def session_init_from_stream(lines: Iterable[str]) -> Check:
+ """`session_servers_connected` on the first `system`/`init` event of a stream-json transcript."""
+ for line in lines:
+ try:
+ event = json.loads(line)
+ except ValueError:
+ continue
+ if event.get("type") == "system" and event.get("subtype") == "init":
+ return session_servers_connected(event)
+ return Check("session_init", False, "no init event in the stream")
+
+
+# ------------------------------------------------------------------ AppleEvents / automation consent (macOS)
+
+# osascript error numbers that mean the harness, not the agent, cannot automate the app
+AE_HARNESS_ERRORS = {
+ -1743: "not authorized to send Apple events (Automation consent missing)",
+ -1744: "the user must consent first (Automation consent pending)",
+ -10004: "privilege error (the sender is not entitled)",
+ -1712: "Apple event timed out",
+ -600: "the app is not running",
+ -609: "connection to the app is invalid",
+}
+
+
+def appleevents_health(
+ apps: Iterable[str],
+ timeout: float = 30.0,
+ osascript: str = "/usr/bin/osascript",
+ launch: bool = False,
+) -> list[Check]:
+ """Send one harmless Apple event (`name`) to each app the task's reset or export automates.
+
+ Run it after the reset, as the same user the reset and export run as. A task whose reset or export
+ reads app data (Calendar, Reminders, Notes, Finder) cannot be graded when the event is refused, so a
+ refusal is a harness error, never an agent failure.
+
+ With `launch=False` (the default) an app that is not running is not sent anything, so the check never opens
+ an app or a window that the task's start state does not have; run it after the task's apps have started."""
+ out = []
+ for app in apps:
+ name = json.dumps(app)
+ script = f"const a = Application({name}); a.running() ? a.name() : '__not_running__'"
+ if launch:
+ script = f"Application({name}).name()"
+ try:
+ done = subprocess.run(
+ [osascript, "-l", "JavaScript", "-e", script],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+ except FileNotFoundError:
+ out.append(Check(f"appleevents:{app}", False, "osascript not found"))
+ continue
+ except subprocess.TimeoutExpired:
+ out.append(Check(f"appleevents:{app}", False, AE_HARNESS_ERRORS[-1712]))
+ continue
+ if done.returncode == 0:
+ if done.stdout.strip() == "__not_running__":
+ out.append(
+ Check(
+ f"appleevents:{app}", True, "not running; not checked", {"checked": False}
+ )
+ )
+ else:
+ out.append(Check(f"appleevents:{app}", True, "ok", {"checked": True}))
+ continue
+ match = re.search(r"\((-?\d+)\)\s*$", done.stderr.strip())
+ code = int(match.group(1)) if match else None
+ reason = AE_HARNESS_ERRORS.get(code or 0, "Apple event failed")
+ out.append(
+ Check(
+ f"appleevents:{app}",
+ False,
+ reason,
+ {"code": code, "stderr": done.stderr.strip()[-300:]},
+ )
+ )
+ return out
+
+
+# ------------------------------------------------------------------ network
+
+
+def loopback_health() -> Check:
+ """127.0.0.1 accepts a listener and a connection to it. Every pack task with a local web app serves it on
+ loopback; if loopback is broken the app never becomes ready and the trial is a harness error."""
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
+ server.bind(("127.0.0.1", 0))
+ server.listen(1)
+ port = server.getsockname()[1]
+ with socket.create_connection(("127.0.0.1", port), timeout=5):
+ conn, _ = server.accept()
+ conn.close()
+ return Check("network:loopback", True, "ok", {"port": port})
+ except OSError as error:
+ return Check("network:loopback", False, f"loopback unusable: {error}")
+
+
+def http_ready(url: str, timeout: float = 20.0) -> Check:
+ """A task app's `ready.http` URL answers 200 within `timeout`."""
+ deadline = time.monotonic() + timeout
+ last = ""
+ while time.monotonic() < deadline:
+ try:
+ with urllib.request.urlopen(url, timeout=2) as response:
+ if response.status == 200:
+ return Check(f"network:ready:{url}", True, "ok")
+ last = f"HTTP {response.status}"
+ except OSError as error:
+ last = str(error)
+ time.sleep(0.4)
+ return Check(f"network:ready:{url}", False, f"not ready within {timeout:g} s: {last}")
+
+
+def primary_ipv4() -> Optional[str]:
+ """The source address the OS would use for an outside destination (no packet is sent)."""
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:
+ probe.connect(
+ ("192.0.2.1", 9)
+ ) # TEST-NET-1: never routed, nothing is sent for a UDP connect
+ return probe.getsockname()[0]
+ except OSError:
+ return None
+
+
+def lease_health() -> Check:
+ """The environment has a usable IPv4 address (a DHCP lease or a static one), not none and not a
+ 169.254/16 self-assigned address. Only needed when something in the environment must reach the network
+ (for example a tool server that talks to a host-side model gateway); tasks themselves use no internet."""
+ address = primary_ipv4()
+ if not address:
+ return Check("network:lease", False, "no IPv4 route")
+ ip = ipaddress.ip_address(address)
+ if ip.is_link_local:
+ return Check(
+ "network:lease", False, "self-assigned address (no DHCP lease)", {"address": address}
+ )
+ if ip.is_loopback or ip.is_unspecified:
+ return Check("network:lease", False, "no usable IPv4 address", {"address": address})
+ return Check("network:lease", True, "ok", {"address": address})
+
+
+def network_health(
+ urls: Iterable[str] = (), require_lease: bool = False, timeout: float = 20.0
+) -> list[Check]:
+ checks = [loopback_health(), *(http_ready(u, timeout) for u in urls)]
+ if require_lease:
+ checks.append(lease_health())
+ return checks
+
+
+# ------------------------------------------------------------------ checker toolchain
+
+
+DESCRIPTOR_PROGRAMS = {"${python}": "python3", "${evaluator_node}": "node"}
+
+
+def programs_of_descriptor(
+ descriptor: dict[str, Any], resolve: Optional[dict[str, str]] = None
+) -> list[str]:
+ """Programs the descriptor's reset, export and evaluate steps need: each step's first argument, and the
+ interpreter variables used anywhere in its semantics. `resolve` maps `${python}` / `${evaluator_node}` to
+ the executables the runner substitutes (default: `python3` and `node` on PATH)."""
+ sem = descriptor.get("semantics", {})
+ mapping = {**DESCRIPTOR_PROGRAMS, **{"${" + k + "}": v for k, v in (resolve or {}).items()}}
+ found: list[str] = []
+ steps = [*(sem.get("reset") or {}).values(), sem.get("export"), sem.get("evaluate")]
+ for step in steps:
+ if isinstance(step, list) and step:
+ found.append(str(step[0]))
+ text = json.dumps(sem)
+ found += [v for v in DESCRIPTOR_PROGRAMS if v in text]
+ out: list[str] = []
+ for item in found:
+ program = mapping.get(item, item)
+ if "${" in program or program in out:
+ continue
+ out.append(program)
+ return out
+
+
+def toolchain_health(programs: Iterable[str], path: Optional[str] = None) -> list[Check]:
+ """Every program the task's checker side needs is present and starts, on the PATH the reset, export and
+ evaluator get. Pass the task's `health.evaluator_tools` from the task-set manifest, plus
+ `programs_of_descriptor(...)`. A missing checker tool (for example `node` for a checker that starts the
+ task's own web server) fails the trial for a reason that has nothing to do with the agent."""
+ out = []
+ for program in programs:
+ found = program if os.path.isabs(program) else shutil.which(program, path=path)
+ if not found or not os.access(found, os.X_OK):
+ out.append(
+ Check(f"toolchain:{program}", False, f"{program} not found on the checker's PATH")
+ )
+ continue
+ if os.path.basename(found) in ("python3", "python", "node"):
+ try:
+ done = subprocess.run(
+ [found, "--version"], capture_output=True, text=True, timeout=20
+ )
+ ok = done.returncode == 0
+ detail = {"path": found, "version": (done.stdout or done.stderr).strip()[:80]}
+ except (OSError, subprocess.TimeoutExpired) as error:
+ ok, detail = False, {"path": found, "error": str(error)}
+ out.append(
+ Check(f"toolchain:{program}", ok, "ok" if ok else f"{found} does not start", detail)
+ )
+ else:
+ out.append(Check(f"toolchain:{program}", True, "ok", {"path": found}))
+ return out
+
+
+# ------------------------------------------------------------------ environment-lost watchdog
+
+
+class EnvWatchdog:
+ """Probe the environment during the agent phase; report it lost after `misses` failed probes in a row.
+
+ `probe` is the runner's own liveness call (the VM answers, the tool server's process is alive, the
+ desktop session still exists). A trial whose environment was lost mid-run is a harness error: the agent
+ may have been acting on a desktop that no longer existed."""
+
+ def __init__(self, probe: Callable[[], bool], interval: float = 10.0, misses: int = 3) -> None:
+ self.probe, self.interval, self.misses = probe, interval, misses
+ self.failures = 0
+ self.lost_at: Optional[float] = None
+ self.probes = 0
+ self._stop = threading.Event()
+ self._thread = threading.Thread(target=self._run, name="cdb-env-watchdog", daemon=True)
+ self._started = 0.0
+
+ def _run(self) -> None:
+ while not self._stop.wait(self.interval):
+ self.tick()
+ if self.lost_at is not None:
+ return
+
+ def tick(self) -> None:
+ """One probe (the thread calls it; tests call it directly)."""
+ self.probes += 1
+ try:
+ alive = bool(self.probe())
+ except Exception: # noqa: BLE001 - a probe that raises is a failed probe
+ alive = False
+ self.failures = 0 if alive else self.failures + 1
+ if self.failures >= self.misses and self.lost_at is None:
+ self.lost_at = time.monotonic() - self._started
+
+ def start(self) -> "EnvWatchdog":
+ self._started = time.monotonic()
+ self._thread.start()
+ return self
+
+ def stop(self) -> Check:
+ self._stop.set()
+ if self._thread.is_alive():
+ self._thread.join(timeout=self.interval + 5)
+ if self.lost_at is not None:
+ return Check(
+ "env_watchdog",
+ False,
+ "environment lost during the agent phase",
+ {"lost_after_s": round(self.lost_at, 1), "probes": self.probes},
+ )
+ return Check("env_watchdog", True, "ok", {"probes": self.probes})
+
+
+# ------------------------------------------------------------------ outcomes: harness error -> re-run, never scored
+
+
+def classify(row: dict[str, Any]) -> str:
+ """`pass`, `fail` or `harness_error` for one trial row.
+
+ A row is a harness error when any health check failed (`health` list with an `ok: false` entry), when it
+ carries `harness_error` (a reason string), or when its `status` is `harness_error`/`infra_error`. Only
+ `pass` and `fail` are scored."""
+ if row.get("harness_error") or row.get("status") in ("harness_error", "infra_error"):
+ return HARNESS_ERROR
+ if any(not c.get("ok", True) for c in row.get("health") or []):
+ return HARNESS_ERROR
+ return PASS if row.get("passed") else FAIL
+
+
+def trial_key(row: dict[str, Any]) -> tuple[str, str, int, str]:
+ return (
+ str(row.get("arm") or row.get("setup") or ""),
+ str(row["task"]),
+ int(row["run_index"]),
+ str(row.get("condition") or ""),
+ )
+
+
+def scored_rows(rows: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
+ """The rows that count: for each (setup, task, run index, condition), its last pass/fail attempt.
+ Harness-error attempts are dropped. A trial that only ever had harness errors is not in the result; it is
+ reported by `rerun_plan`, never counted as a failure."""
+ final: dict[tuple, dict[str, Any]] = {}
+ for row in rows:
+ if classify(row) != HARNESS_ERROR:
+ final[trial_key(row)] = row
+ return list(final.values())
+
+
+def rerun_plan(
+ rows: Iterable[dict[str, Any]], max_attempts: int = 3
+) -> dict[str, list[dict[str, Any]]]:
+ """Which trials to run again: a trial whose attempts so far are all harness errors is re-run with the
+ same seed (`rerun`) until `max_attempts`, then reported as `excluded` (never scored)."""
+ attempts: dict[tuple, list[dict[str, Any]]] = {}
+ for row in rows:
+ attempts.setdefault(trial_key(row), []).append(row)
+ plan: dict[str, list[dict[str, Any]]] = {"rerun": [], "excluded": []}
+ for key, tries in attempts.items():
+ if any(classify(r) != HARNESS_ERROR for r in tries):
+ continue
+ setup, task, run_index, condition = key
+ item = {
+ "setup": setup,
+ "task": task,
+ "run_index": run_index,
+ "condition": condition,
+ "seed": trial_seed(task, run_index),
+ "attempts": len(tries),
+ "last_reason": tries[-1].get("harness_error") or tries[-1].get("status"),
+ }
+ plan["rerun" if len(tries) < max_attempts else "excluded"].append(item)
+ return plan
+
+
+def summarize(rows: list[dict[str, Any]], max_attempts: int = 3) -> dict[str, Any]:
+ scored = scored_rows(rows)
+ plan = rerun_plan(rows, max_attempts)
+ return {
+ "attempts": len(rows),
+ "harness_error_attempts": sum(classify(r) == HARNESS_ERROR for r in rows),
+ "scored": len(scored),
+ "passed": sum(classify(r) == PASS for r in scored),
+ "rerun": plan["rerun"],
+ "excluded": plan["excluded"],
+ }
+
+
+# ------------------------------------------------------------------ command line
+
+
+def _emit(checks: list[Check], extra: Optional[dict[str, Any]] = None) -> int:
+ ok = all(c.ok for c in checks)
+ print(
+ json.dumps({"ok": ok, "checks": [c.to_json() for c in checks], **(extra or {})}, indent=1)
+ )
+ return EXIT_OK if ok else EXIT_HARNESS_ERROR
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Cua Driver Bench fairness and health checks (see SPEC.md)"
+ )
+ sub = parser.add_subparsers(dest="command", required=True)
+ p = sub.add_parser("seed")
+ p.add_argument("task")
+ p.add_argument("run_index", type=int)
+ p = sub.add_parser("mcp")
+ p.add_argument("config", type=Path)
+ p.add_argument("--server")
+ p.add_argument("--timeout", type=float, default=60.0)
+ p.add_argument("--probe-tool")
+ p.add_argument("--probe-args", default="{}")
+ p = sub.add_parser("session-init")
+ p.add_argument("stream", type=Path)
+ p = sub.add_parser("appleevents")
+ p.add_argument("apps", nargs="+")
+ p.add_argument("--timeout", type=float, default=30.0)
+ p.add_argument(
+ "--launch", action="store_true", help="also check apps that are not running (starts them)"
+ )
+ p = sub.add_parser("network")
+ p.add_argument("--url", action="append", default=[])
+ p.add_argument("--require-lease", action="store_true")
+ p.add_argument("--timeout", type=float, default=20.0)
+ p = sub.add_parser("toolchain")
+ p.add_argument("programs", nargs="*", help="extra programs (the task's health.evaluator_tools)")
+ p.add_argument("--descriptor", type=Path, help="also every program of this launch descriptor")
+ p.add_argument(
+ "--path", default=None, help="the PATH the checker gets (default: this process's)"
+ )
+ p.add_argument("--python")
+ p.add_argument("--node")
+ p = sub.add_parser("summarize")
+ p.add_argument("rows", type=Path)
+ p.add_argument("--max-attempts", type=int, default=3)
+ args = parser.parse_args(argv)
+
+ if args.command == "seed":
+ print(
+ json.dumps(
+ {
+ "task": args.task,
+ "run_index": args.run_index,
+ "seed": trial_seed(args.task, args.run_index),
+ }
+ )
+ )
+ return EXIT_OK
+ if args.command == "mcp":
+ return _emit(
+ mcp_preflight_from_config(
+ args.config, args.server, args.timeout, args.probe_tool, json.loads(args.probe_args)
+ )
+ )
+ if args.command == "session-init":
+ return _emit(
+ [session_init_from_stream(args.stream.read_text("utf-8", "replace").splitlines())]
+ )
+ if args.command == "appleevents":
+ return _emit(appleevents_health(args.apps, args.timeout, launch=args.launch))
+ if args.command == "network":
+ return _emit(network_health(args.url, args.require_lease, args.timeout))
+ if args.command == "toolchain":
+ resolve = {k: v for k, v in (("python", args.python), ("evaluator_node", args.node)) if v}
+ programs = list(args.programs)
+ if args.descriptor:
+ descriptor = json.loads(args.descriptor.read_text("utf-8"))
+ programs += [
+ p for p in programs_of_descriptor(descriptor, resolve) if p not in programs
+ ]
+ return _emit(toolchain_health(programs, args.path))
+ if args.command == "summarize":
+ rows = [
+ json.loads(line) for line in args.rows.read_text("utf-8").splitlines() if line.strip()
+ ]
+ print(json.dumps(summarize(rows, args.max_attempts), indent=1))
+ return EXIT_OK
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/libs/cua-driver-bench/fairness/tests/test_cdb_fairness.py b/libs/cua-driver-bench/fairness/tests/test_cdb_fairness.py
new file mode 100644
index 0000000000..497978441a
--- /dev/null
+++ b/libs/cua-driver-bench/fairness/tests/test_cdb_fairness.py
@@ -0,0 +1,358 @@
+# SPDX-License-Identifier: FSL-1.1-MIT
+# Copyright (c) 2026 Cua AI, Inc.
+
+"""Tests of the runner-agnostic fairness and health checks (no GUI, no VM, no model)."""
+
+from __future__ import annotations
+
+import json
+import os
+import socket
+import subprocess
+import sys
+import tempfile
+import textwrap
+import threading
+import unittest
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from pathlib import Path
+from unittest import mock
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent))
+
+import cdb_fairness as fx # noqa: E402
+
+FAKE_MCP = textwrap.dedent(
+ """
+ import json, sys
+ mode = sys.argv[1]
+ for line in sys.stdin:
+ msg = json.loads(line)
+ if "id" not in msg:
+ continue
+ if mode == "silent":
+ continue
+ if msg["method"] == "initialize":
+ print("a log line, not JSON", flush=True)
+ out = {"protocolVersion": "2025-06-18", "capabilities": {}, "serverInfo": {"name": "fake", "version": "1"}}
+ elif msg["method"] == "tools/list":
+ out = {"tools": [] if mode == "notools" else [{"name": "check_permissions", "inputSchema": {}}]}
+ elif msg["method"] == "tools/call":
+ out = {"content": [{"type": "text", "text": "ok"}], "isError": mode == "probefail"}
+ print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": out}), flush=True)
+ """
+)
+
+
+class SeedTests(unittest.TestCase):
+ def test_matches_the_runner_seed(self) -> None:
+ sys.path.insert(0, str(HERE.parents[1] / "automated-eval" / "macos_bench"))
+ import bench_core
+
+ for task in ("MB-09", "IR-01", "CDB-G02", "CDB-G04"):
+ for run_index in range(6):
+ self.assertEqual(
+ fx.trial_seed(task, run_index), bench_core.probe_seed(task, run_index)
+ )
+
+ def test_known_value_and_range(self) -> None:
+ self.assertEqual(fx.trial_seed("MB-09", 0), 790113)
+ self.assertTrue(all(0 <= fx.trial_seed("IR-02", i) < 1_000_000 for i in range(50)))
+ self.assertNotEqual(fx.trial_seed("IR-02", 0), fx.trial_seed("IR-02", 1))
+
+ def test_negative_run_index_rejected(self) -> None:
+ with self.assertRaises(ValueError):
+ fx.trial_seed("MB-09", -1)
+
+
+class McpPreflightTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tmp = Path(tempfile.mkdtemp())
+ self.server = self.tmp / "fake_mcp.py"
+ self.server.write_text(FAKE_MCP)
+
+ def run_mode(self, mode: str, **kw: object) -> fx.Check:
+ return fx.mcp_preflight([sys.executable, str(self.server), mode], timeout=5, **kw)
+
+ def test_ready_server_passes(self) -> None:
+ check = self.run_mode("ok")
+ self.assertTrue(check.ok, check)
+ self.assertEqual(check.detail["tools"], 1)
+
+ def test_probe_tool(self) -> None:
+ self.assertTrue(self.run_mode("ok", probe_tool="check_permissions").ok)
+ self.assertFalse(self.run_mode("probefail", probe_tool="check_permissions").ok)
+ self.assertIn("not offered", self.run_mode("ok", probe_tool="nope").reason)
+
+ def test_no_tools_is_a_harness_error(self) -> None:
+ self.assertFalse(self.run_mode("notools").ok)
+
+ def test_silent_server_times_out(self) -> None:
+ check = fx.mcp_preflight([sys.executable, str(self.server), "silent"], timeout=1)
+ self.assertFalse(check.ok)
+ self.assertIn("initialize", check.reason)
+
+ def test_missing_binary(self) -> None:
+ self.assertFalse(fx.mcp_preflight([str(self.tmp / "absent")], timeout=1).ok)
+
+ def test_from_config(self) -> None:
+ config = self.tmp / "mcp.json"
+ config.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "good": {"command": sys.executable, "args": [str(self.server), "ok"]},
+ "remote": {"type": "http", "url": "http://127.0.0.1:9/mcp"},
+ }
+ }
+ )
+ )
+ checks = fx.mcp_preflight_from_config(config, timeout=5)
+ self.assertEqual([c.ok for c in checks], [True, False])
+ self.assertEqual(len(fx.mcp_preflight_from_config(config, server="good", timeout=5)), 1)
+ self.assertFalse(fx.mcp_preflight_from_config(config, server="absent")[0].ok)
+
+ def test_cli_exit_codes(self) -> None:
+ config = self.tmp / "mcp.json"
+ config.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "s": {"command": sys.executable, "args": [str(self.server), "notools"]}
+ }
+ }
+ )
+ )
+ done = subprocess.run(
+ [
+ sys.executable,
+ str(HERE.parent / "cdb_fairness.py"),
+ "mcp",
+ str(config),
+ "--timeout",
+ "5",
+ ],
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(done.returncode, fx.EXIT_HARNESS_ERROR)
+ self.assertFalse(json.loads(done.stdout)["ok"])
+
+
+class SessionInitTests(unittest.TestCase):
+ def test_connected(self) -> None:
+ event = {
+ "type": "system",
+ "subtype": "init",
+ "mcp_servers": [{"name": "cu", "status": "connected"}],
+ }
+ self.assertTrue(fx.session_init_from_stream(["noise", json.dumps(event)]).ok)
+
+ def test_failed_server(self) -> None:
+ event = {
+ "type": "system",
+ "subtype": "init",
+ "mcp_servers": [{"name": "cu", "status": "failed"}],
+ }
+ check = fx.session_init_from_stream([json.dumps(event)])
+ self.assertFalse(check.ok)
+ self.assertIn("cu", check.reason)
+
+ def test_no_server_or_no_init(self) -> None:
+ self.assertFalse(fx.session_servers_connected({"mcp_servers": []}).ok)
+ self.assertFalse(fx.session_init_from_stream(['{"type": "assistant"}']).ok)
+
+
+class AppleEventsTests(unittest.TestCase):
+ def fake(self, rc: int, stderr: str = "") -> mock._patch:
+ return mock.patch.object(
+ fx.subprocess, "run", return_value=subprocess.CompletedProcess([], rc, "", stderr)
+ )
+
+ def test_ok(self) -> None:
+ with self.fake(0):
+ self.assertTrue(fx.appleevents_health(["Calendar"])[0].ok)
+
+ def test_not_authorized_is_a_harness_error(self) -> None:
+ with self.fake(
+ 1, "execution error: Error: Not authorized to send Apple events to Calendar. (-1743)"
+ ):
+ check = fx.appleevents_health(["Calendar"])[0]
+ self.assertFalse(check.ok)
+ self.assertEqual(check.detail["code"], -1743)
+ self.assertIn("consent", check.reason)
+
+ def test_not_running_app_is_not_launched(self) -> None:
+ done = subprocess.CompletedProcess([], 0, "__not_running__\n", "")
+ with mock.patch.object(fx.subprocess, "run", return_value=done) as run:
+ check = fx.appleevents_health(["TextEdit"])[0]
+ self.assertTrue(check.ok)
+ self.assertFalse(check.detail["checked"])
+ self.assertIn("running()", run.call_args[0][0][-1])
+ with mock.patch.object(fx.subprocess, "run", return_value=done) as run:
+ fx.appleevents_health(["TextEdit"], launch=True)
+ self.assertNotIn("running()", run.call_args[0][0][-1])
+
+ def test_timeout(self) -> None:
+ with mock.patch.object(
+ fx.subprocess, "run", side_effect=subprocess.TimeoutExpired("osascript", 1)
+ ):
+ self.assertFalse(fx.appleevents_health(["Notes"])[0].ok)
+
+
+class _Healthz(BaseHTTPRequestHandler):
+ def do_GET(self) -> None: # noqa: N802
+ self.send_response(200 if self.path == "/healthz" else 404)
+ self.end_headers()
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+
+class NetworkTests(unittest.TestCase):
+ def test_loopback(self) -> None:
+ self.assertTrue(fx.loopback_health().ok)
+
+ def test_ready_url(self) -> None:
+ server = HTTPServer(("127.0.0.1", 0), _Healthz)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ try:
+ base = f"http://127.0.0.1:{server.server_port}"
+ self.assertTrue(fx.http_ready(base + "/healthz", timeout=3).ok)
+ self.assertFalse(fx.http_ready(base + "/missing", timeout=1).ok)
+ finally:
+ server.shutdown()
+ server.server_close()
+
+ def test_lease(self) -> None:
+ with mock.patch.object(fx, "primary_ipv4", return_value="169.254.10.2"):
+ self.assertIn("self-assigned", fx.lease_health().reason)
+ with mock.patch.object(fx, "primary_ipv4", return_value=None):
+ self.assertFalse(fx.lease_health().ok)
+ with mock.patch.object(fx, "primary_ipv4", return_value="192.0.2.5"):
+ self.assertTrue(fx.lease_health().ok)
+
+ def test_loopback_failure(self) -> None:
+ with mock.patch.object(fx.socket, "socket", side_effect=OSError("no lo0")):
+ self.assertFalse(fx.loopback_health().ok)
+
+
+class ToolchainTests(unittest.TestCase):
+ DESCRIPTOR = {
+ "semantics": {
+ "reset": {
+ "setup": ["${python}", "reset/setup.py"],
+ "verify": ["${python}", "reset/verify.py"],
+ },
+ "export": ["${python}", "reset/export.py"],
+ "evaluate": ["${python}", "evaluator/evaluate.py", "--node", "${evaluator_node}"],
+ }
+ }
+
+ def test_programs_of_descriptor(self) -> None:
+ self.assertEqual(fx.programs_of_descriptor(self.DESCRIPTOR), ["python3", "node"])
+ self.assertEqual(
+ fx.programs_of_descriptor(self.DESCRIPTOR, {"python": "/opt/py"}), ["/opt/py", "node"]
+ )
+
+ def test_missing_program_is_a_harness_error(self) -> None:
+ with tempfile.TemporaryDirectory() as empty:
+ checks = fx.toolchain_health(["node"], path=empty)
+ self.assertFalse(checks[0].ok)
+ self.assertIn("not found", checks[0].reason)
+
+ def test_present_program(self) -> None:
+ with tempfile.TemporaryDirectory() as bindir:
+ tool = Path(bindir) / "xattr"
+ tool.write_text("#!/bin/sh\nexit 0\n")
+ tool.chmod(0o755)
+ self.assertTrue(fx.toolchain_health(["xattr"], path=bindir)[0].ok)
+ self.assertTrue(fx.toolchain_health([sys.executable])[0].ok)
+
+
+class WatchdogTests(unittest.TestCase):
+ def test_lost_after_consecutive_misses(self) -> None:
+ answers = iter([True, False, False, True, False, False, False])
+ dog = fx.EnvWatchdog(lambda: next(answers), interval=999, misses=3)
+ for _ in range(7):
+ dog.tick()
+ check = dog.stop()
+ self.assertFalse(check.ok)
+ self.assertEqual(check.detail["probes"], 7)
+
+ def test_raising_probe_counts_as_a_miss_and_healthy_env_passes(self) -> None:
+ def boom() -> bool:
+ raise OSError("gone")
+
+ dog = fx.EnvWatchdog(boom, interval=999, misses=2)
+ dog.tick()
+ dog.tick()
+ self.assertFalse(dog.stop().ok)
+ healthy = fx.EnvWatchdog(lambda: True, interval=0.01, misses=2).start()
+ threading.Event().wait(0.1)
+ self.assertTrue(healthy.stop().ok)
+
+
+class OutcomeTests(unittest.TestCase):
+ def row(self, task: str, run_index: int, **kw: object) -> dict:
+ return {"arm": "a", "task": task, "run_index": run_index, "condition": "foreground", **kw}
+
+ def test_classify(self) -> None:
+ self.assertEqual(fx.classify(self.row("T", 0, passed=True)), fx.PASS)
+ self.assertEqual(fx.classify(self.row("T", 0, passed=False)), fx.FAIL)
+ self.assertEqual(
+ fx.classify(self.row("T", 0, passed=True, harness_error="export_failed")),
+ fx.HARNESS_ERROR,
+ )
+ self.assertEqual(fx.classify(self.row("T", 0, status="infra_error")), fx.HARNESS_ERROR)
+ self.assertEqual(
+ fx.classify(self.row("T", 0, passed=True, health=[{"ok": False}])), fx.HARNESS_ERROR
+ )
+
+ def test_harness_errors_are_never_scored_and_rerun_with_the_same_seed(self) -> None:
+ rows = [
+ self.row("T", 0, harness_error="mcp_preflight"),
+ self.row("T", 0, passed=False), # the re-run counts
+ self.row("U", 0, harness_error="env_lost"),
+ self.row("V", 1, harness_error="env_lost"),
+ self.row("V", 1, harness_error="env_lost"),
+ self.row("V", 1, harness_error="env_lost"),
+ ]
+ scored = fx.scored_rows(rows)
+ self.assertEqual([(r["task"], r["passed"]) for r in scored], [("T", False)])
+ plan = fx.rerun_plan(rows, max_attempts=3)
+ self.assertEqual(
+ [(i["task"], i["seed"]) for i in plan["rerun"]], [("U", fx.trial_seed("U", 0))]
+ )
+ self.assertEqual([i["task"] for i in plan["excluded"]], ["V"])
+ summary = fx.summarize(rows)
+ self.assertEqual(
+ (summary["scored"], summary["harness_error_attempts"], summary["passed"]), (1, 5, 0)
+ )
+
+ def test_summarize_cli(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "rows.jsonl"
+ path.write_text(
+ "\n".join(json.dumps(r) for r in [self.row("T", 0, passed=True)]) + "\n"
+ )
+ done = subprocess.run(
+ [sys.executable, str(HERE.parent / "cdb_fairness.py"), "summarize", str(path)],
+ capture_output=True,
+ text=True,
+ env={**os.environ, "PYTHONPATH": ""},
+ )
+ self.assertEqual(done.returncode, 0, done.stderr)
+ self.assertEqual(json.loads(done.stdout)["passed"], 1)
+
+
+class LoopbackSocketSanity(unittest.TestCase):
+ def test_primary_ipv4_never_raises(self) -> None:
+ with mock.patch.object(fx.socket, "socket", side_effect=OSError):
+ self.assertIsNone(fx.primary_ipv4())
+ self.assertIsInstance(socket.AF_INET, int)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver-bench/taskpack/README.md b/libs/cua-driver-bench/taskpack/README.md
index 0203b44f4a..88a468aff1 100644
--- a/libs/cua-driver-bench/taskpack/README.md
+++ b/libs/cua-driver-bench/taskpack/README.md
@@ -18,6 +18,10 @@ Select them explicitly with `--tasks WEB-01 WEB-02`; `run_bench.WEB_TASKS` lists
They use a Node built-in-only loopback service, task-local routes and checks,
and a fresh workspace-local Chrome profile. No internet or external assets are used.
+The task manifest, [`v2-taskset.json`](v2-taskset.json), lists every Bench v2 task with its
+category, OS availability, conditions and `split`. A task kept out of this repository would run
+from a separate pack named by `CDB_TASKPACK_HELDOUT`, with the same layout.
+
Each task directory holds:
* `brief.md`: what the agent is told;
diff --git a/libs/cua-driver-bench/taskpack/v2-taskset.json b/libs/cua-driver-bench/taskpack/v2-taskset.json
new file mode 100644
index 0000000000..26bde59a68
--- /dev/null
+++ b/libs/cua-driver-bench/taskpack/v2-taskset.json
@@ -0,0 +1,288 @@
+{
+ "schema": "cdb-taskset/1",
+ "name": "v2",
+ "description": "Bench v2: the ten core tasks, all public. `os` lists where the task has a launch descriptor or runs today: the three multi-app tasks (CDB-G02 to CDB-G04, pack tasks with Electron apps, LibreOffice and, for CDB-G03, GnuCash) run on macOS, Linux and Windows; the seven BenchLab tasks (MB-09 to MB-11, IR-01 to IR-04) run on macOS and Linux. `split` is public (in this repository) or heldout (kept out of this repository; such a task would be listed by id and category only).",
+ "limits": {
+ "timeout_s": 360,
+ "max_turns": 45
+ },
+ "seed": "int(sha256(f'{task}:{run_index}').hexdigest()[:8], 16) % 1000000; run_index counts from 0 per task (trial k uses run_index k-1); the same for every setup and for a re-run of a harness-error trial",
+ "tasks": [
+ {
+ "id": "CDB-G02",
+ "category": "multi_app",
+ "split": "public",
+ "set": "v2",
+ "pack_task": "shared/cdb-s02",
+ "title": "Replan a schedule across mail, chat, a calendar and a Calc workbook",
+ "apps": [
+ "Electron mail, chat and calendar apps",
+ "LibreOffice Calc"
+ ],
+ "os": [
+ "macos",
+ "linux",
+ "windows"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "CDB-G03",
+ "category": "multi_app",
+ "split": "public",
+ "set": "v2",
+ "pack_task": "shared/cdb-s03",
+ "title": "Review payables across mail, a Calc workbook and a GnuCash book",
+ "apps": [
+ "Electron mail app",
+ "LibreOffice Calc",
+ "GnuCash"
+ ],
+ "os": [
+ "macos",
+ "linux",
+ "windows"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "CDB-G04",
+ "category": "multi_app",
+ "split": "public",
+ "set": "v2",
+ "pack_task": "shared/cdb-s04",
+ "title": "Triage duplicate support cases with a tracker, a manual, an archive site and a log",
+ "apps": [
+ "Electron case tracker and manual",
+ "Google Chrome"
+ ],
+ "os": [
+ "macos",
+ "linux",
+ "windows"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3",
+ "node"
+ ]
+ }
+ },
+ {
+ "id": "MB-09",
+ "category": "precision",
+ "split": "public",
+ "set": "v2",
+ "pack_task": null,
+ "title": "Reorder a native list by drag and drop",
+ "apps": [
+ "BenchLab"
+ ],
+ "os": [
+ "macos",
+ "linux"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "MB-10",
+ "category": "precision",
+ "split": "public",
+ "set": "v2",
+ "pack_task": null,
+ "title": "Reveal a hover-only toolbar and click one action",
+ "apps": [
+ "BenchLab"
+ ],
+ "os": [
+ "macos",
+ "linux"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "MB-11",
+ "category": "precision",
+ "split": "public",
+ "set": "v2",
+ "pack_task": null,
+ "title": "Read a native tooltip and type the code it shows",
+ "apps": [
+ "BenchLab"
+ ],
+ "os": [
+ "macos",
+ "linux"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "IR-01",
+ "category": "interruptions",
+ "split": "public",
+ "set": "v2",
+ "pack_task": null,
+ "title": "Finish a two-step form through a permission-style prompt",
+ "apps": [
+ "BenchLab"
+ ],
+ "os": [
+ "macos",
+ "linux"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "IR-02",
+ "category": "interruptions",
+ "split": "public",
+ "set": "v2",
+ "pack_task": null,
+ "title": "Apply settings while a notification-style banner covers the button",
+ "apps": [
+ "BenchLab"
+ ],
+ "os": [
+ "macos",
+ "linux"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "IR-03",
+ "category": "interruptions",
+ "split": "public",
+ "set": "v2",
+ "pack_task": null,
+ "title": "Edit two notes and keep both changes through a save prompt",
+ "apps": [
+ "BenchLab"
+ ],
+ "os": [
+ "macos",
+ "linux"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ },
+ {
+ "id": "IR-04",
+ "category": "interruptions",
+ "split": "public",
+ "set": "v2",
+ "pack_task": null,
+ "title": "Sign up on a web page while a cookie-consent overlay appears",
+ "apps": [
+ "BenchLab"
+ ],
+ "os": [
+ "macos",
+ "linux"
+ ],
+ "cross_os_candidate": null,
+ "conditions": [
+ "foreground",
+ "background"
+ ],
+ "health": {
+ "automation_apps": [],
+ "ready_urls": [],
+ "evaluator_tools": [
+ "python3"
+ ]
+ }
+ }
+ ]
+}