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.

10.4 KB
Raw Blame
#!/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())