#!/usr/bin/env python3 """Generate the Harbor-compatible Video-Arena benchmark, Protocol B (default) or A. One Harbor task per case: 180 tasks in one dataset directory. See docs/HARBOR.md. python tools/make_harbor.py --out harbor/video-arena [--protocol B|A] [--net strict|docker|phase] [--base-image video-arena/base:latest] [--games go,chess] [--cases 2] [--host-media /abs/media/root] [--force] Each task: task.toml Harbor task config (schema 1.4) instruction.md B: the agent's prompt (200 turns / 7200 s), which points at the file below. A: the A-rendered instruction itself; the Protocol A agent (tools/harbor/protocol_a_agent.py) appends the frames and the single-reply tail and makes the one request. environment/ docker-compose.yaml -- prebuilt image, no network, the case's render (and, for B, its instruction) mounted read-only into /app -- and, for B, that instruction.md tests/ test.sh, score_harbor.py, judge.py, gt.json, case.json (verifier only) solution/ solve.sh, answer.json (GT projected onto the answer schema; oracle only) Protocol A on Harbor: the model never sees the container. The agent samples the paper's grid with ffmpeg INSIDE the offline sandbox, then sends the frames in one chat request from the host and writes the extracted answer to /app/answer.json. Same verifier, same reward keys as B. Deliberate separations * Scoring never runs in the agent's container. /app/answer.json is the collected artifact; a separate verifier container re-materializes it and runs the case judge there, so the sandbox holds no ground truth, no judge and no solution. * The dataset holds no video. Each compose file bind-mounts the render from $VA_MEDIA_ROOT//media/.mp4 on the Docker host, so the dataset stays small (a few MB) and the 11.8 GB of renders are fetched once per host, not once per task. * No network. The base image (tools/harbor/Dockerfile) pre-installs ffmpeg, Python and the usual video/numeric libraries, and already holds the empty answer.json seed. """ import argparse import json import os import shutil import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import va_core as C # noqa: E402 import score as S # noqa: E402 (oracle_answer) DEFAULT_BASE_IMAGE = "video-arena/base:latest" MEDIA_VAR = "${VA_MEDIA_ROOT}" # --net: ([environment] line, [agent] line, Docker-level network_mode: none in the compose file) # strict Harbor no-network for the whole trial, AND no network interface at the Docker level. # For host-side agents (terminus-2, oracle). Needs Harbor's egress control, which # probes the Docker host for nftables support and rejects no-network tasks without it. # docker The same sandbox, offline through Docker alone; Harbor's own policy is left public. # For Docker hosts where that probe fails. # phase Network while an installed agent (claude-code, codex, ...) installs itself, then # Harbor no-network for the run, opened to the model API only via # `harbor run --allow-agent-host `. Needs Harbor's egress control. NET = { "strict": ('network_mode = "no-network"', 'network_mode = "no-network"', True), "docker": ('# offline via docker-compose.yaml (network_mode: none); Harbor policy stays public\n' 'network_mode = "public"', '# offline via docker-compose.yaml', True), "phase": ('# public only for agent setup (install); the run itself is no-network\n' 'network_mode = "public"', 'network_mode = "no-network"', False), } TASK_TOML = """# Generated by tools/make_harbor.py -- do not edit; regenerate instead. schema_version = "1.4" artifacts = ["/app/answer.json"] [task] name = "video-arena/{name}" version = "1.0.0" description = "{desc}" keywords = {keywords} [metadata] game = "{game}" case_id = "{cid}" family = "{family}" regime = "{regime}" root_key = "{root_key}" tol = {tol} protocol = "{protocol}" answer = "/app/answer.json" video = "{media}" {extra} [agent] {agent_budget} # the image's unprivileged user (tools/harbor/Dockerfile); the verifier runs as root user = "agent" {agent_net} [verifier] environment_mode = "separate" timeout_sec = 600.0 [environment] docker_image = "{base_image}" workdir = "/app" {env_net} cpus = 4 memory_mb = 8192 [solution] env = {{}} """ # Per protocol: the [agent] budget, the description, and whether the sandbox gets the # instruction file (under A the model never sees the sandbox; the prompt is instruction.md). AGENT_BUDGET = { "B": "# Protocol B: at most 200 tool-call turns inside a 7200 s hard wall clock.\n" "timeout_sec = 7200.0", "A": "# Protocol A: one request, no tools; frame sampling plus that one call.\n" "timeout_sec = 3600.0", } DESC = { "B": "Video-Arena Protocol B case %s/%s: watch the replay and infer event times, " "outcomes and impact tiers from the video alone.", "A": "Video-Arena Protocol A case %s/%s: one request with the sampled frames and no " "tools; infer event times, outcomes and impact tiers from the frames alone.", } INSTRUCTION_MOUNT = """ - type: bind source: ./instruction.md target: /app/instruction.md read_only: true """ COMPOSE_TOML = """# Generated by tools/make_harbor.py -- do not edit. # # The prebuilt image is the sandbox and already holds the empty /app/answer.json seed; this file # only mounts the case's read-only inputs into /app. With --net strict or docker it also # sets network_mode: none: Docker gives the sandbox no interface but loopback, and a service # that declares its own networking is left out of Harbor's egress-control sidecar. In strict # mode Harbor's no-network policy applies on top. services: main: {net_line} working_dir: /app # Long syntax on purpose: a missing source fails the start instead of Docker silently # creating an empty directory where the file should be. volumes: {instruction_mount} - type: bind source: {media_src} target: /app/match.mp4 read_only: true """ TEST_SH = """#!/bin/bash # Verifier entrypoint: score the agent's answer.json, then hand Harbor /logs/verifier/reward.json. set -euo pipefail mkdir -p /logs/verifier python3 /tests/score_harbor.py """ SOLVE_SH = """#!/bin/bash set -euo pipefail # Oracle reference: the ground truth projected onto the answer schema (tools/score.py). cp /solution/answer.json /app/answer.json echo "wrote /app/answer.json" """ SCORE_PY = '''#!/usr/bin/env python3 """Score the agent's /app/answer.json with this case judge; write /logs/verifier/reward.json. Runs in the VERIFIER container, never in the sandbox: the judge and the ground truth are uploaded here for scoring and are absent from the agent container. Reward keys follow the public Video-Arena scorer (tools/score.py): reward the case headline reward (judge reward.reward) t1_f1 T1 localization F1 t2_macro_acc T2 macro accuracy t3_macro_acc T3 macro accuracy Any tier the judge did not report is recorded as 0.0: Harbor accepts only finite numbers, and a tier the judge declined to score is a tier the answer earned nothing on. A missing or unparseable /app/answer.json is not an exception. It is scored as the pre-seeded empty answer -- reward 0.0, every tier 0.0 -- which covers the run that died before writing anything, the artifact upload that failed, and the wiped sandbox alike. Those must grade zero rather than surface as a harness error. A judge that cannot run at all is a real harness error and is graded zero loudly, on stderr, in the verifier log. """ import json import os import subprocess import sys TESTS = os.path.dirname(os.path.abspath(__file__)) ANSWER = "/app/answer.json" GT = os.path.join(TESTS, "gt.json") JUDGE = os.path.join(TESTS, "judge.py") OUT = "/logs/verifier/reward.json" TOL = float(os.environ.get("VA_TOL", {tol!r})) PRIMARY = {primary!r} def load_answer(): """The agent answer, or the pre-seeded empty answer when there is nothing scoreable.""" try: with open(ANSWER, encoding="utf-8") as fh: doc = json.load(fh) if isinstance(doc, dict): return doc sys.stderr.write("answer.json is %s, not an object; scoring it as empty\\n" % type(doc).__name__) except Exception as exc: sys.stderr.write("answer.json unreadable (%s); scoring it as empty\\n" % exc) return {{"{root_key}": []}} def judge(answer_doc): """Run the case judge exactly as its CLI documents; None if the judge itself failed.""" staged = "/logs/verifier/answer.scored.json" with open(staged, "w", encoding="utf-8") as fh: json.dump(answer_doc, fh) cmd = [sys.executable, JUDGE, "--answer", staged, "--gt", GT, "--out", "/logs/verifier/judge.json", "--tol", str(TOL)] if PRIMARY: cmd += ["--primary", PRIMARY] proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace") if proc.returncode != 0: sys.stderr.write("judge exited %s\\n%s\\n" % (proc.returncode, proc.stderr[-4000:])) return None with open("/logs/verifier/judge.json", encoding="utf-8") as fh: return json.load(fh) def subscores(reward): """The four published numbers, mirroring tools/score.py:subscores (no va_core here). The two judge families put the tier block in different places.""" t = reward.get("tiers") if t: t3 = t.get("t3_situation") or t.get("t3_score") or {{}} t3v = t3.get("macro_acc") if t3v is None: t3v = t3.get("exact_pair_acc") return {{"reward": reward.get("reward"), "t1_f1": (t.get("t1_localization") or {{}}).get("f1"), "t2_macro_acc": (t.get("t2_impact") or {{}}).get("macro_acc"), "t3_macro_acc": t3v}} d = reward.get("detail", {{}}) t2 = d.get("t2_round_winner") or d.get("t2_minute_gain_event") or d.get("t2_impact") or {{}} t3 = (d.get("t3_score_track") or d.get("t3_leader_after_event") or d.get("t3_situation") or {{}}) t3v = t3.get("exact_frac") if t3v is None: t3v = t3.get("macro_acc") return {{"reward": reward.get("reward"), "t1_f1": (d.get("t1_localization") or {{}}).get("f1"), "t2_macro_acc": t2.get("macro_acc"), "t3_macro_acc": t3v}} def main(): os.makedirs(os.path.dirname(OUT), exist_ok=True) reward = judge(load_answer()) scores = {{"reward": 0.0, "t1_f1": 0.0, "t2_macro_acc": 0.0, "t3_macro_acc": 0.0}} if reward is not None: for key, value in subscores(reward).items(): if isinstance(value, bool) or not isinstance(value, (int, float)): value = 0.0 scores[key] = float(value) with open(OUT, "w", encoding="utf-8") as fh: json.dump(scores, fh, indent=2, sort_keys=True) fh.write("\\n") print(json.dumps(scores, sort_keys=True)) if __name__ == "__main__": main() ''' # Build-time diagnostics in CASE_TYPES.json that stay out of the published task metadata. _META_SKIP = {"id", "case_id", "features", "t3_classes", "t2_classes", "zone_counts", "hud_audit", "result", "type_zh", "winner"} def meta_extra(extra): """The case's own tags from CASE_TYPES.json as [metadata] lines. Only short scalar fields ride along; the long derived dictionaries are build diagnostics, not task metadata.""" out = [] for key in sorted(extra): value = extra[key] if key in _META_SKIP or isinstance(value, (dict, list)): continue if isinstance(value, bool) or not isinstance(value, (int, float)): value = str(value) out.append("%s = %s\n" % (key, json.dumps(value, ensure_ascii=False))) return "".join(out) def write(path, text, mode=None): with open(path, "w", encoding="utf-8", newline="\n") as fh: fh.write(text) if mode is not None: os.chmod(path, mode) def build_task(game, cid, out_dir, args): meta = C.resolve(game, cid) with open(meta["gt"], encoding="utf-8") as fh: gt = json.load(fh) answer = S.oracle_answer(game, gt) # The oracle answer must be a PROJECTION of the ground truth: every key it carries comes # from the GT (dota2's schema has two optional dense blocks beyond the event list), and the # event list survives the projection whole. bad = [k for k in answer if k not in gt] if bad: raise SystemExit("%s/%s: oracle answer invents keys not in GT: %s" % (game, cid, bad)) if len(answer[meta["root_key"]]) != len(gt[meta["root_key"]]): raise SystemExit("%s/%s: oracle event count differs from GT" % (game, cid)) name = "%s-%s" % (game, cid) task_dir = os.path.join(out_dir, name) tests = os.path.join(task_dir, "tests") env_dir = os.path.join(task_dir, "environment") sol_dir = os.path.join(task_dir, "solution") for d in (tests, env_dir, sol_dir): os.makedirs(d, exist_ok=True) video = "%s/%s/media/%s.mp4" % (args.host_media or MEDIA_VAR, game, cid) proto = args.protocol write(os.path.join(task_dir, "task.toml"), TASK_TOML.format( name=name, desc=DESC[proto] % (game, cid), game=game, cid=cid, family=meta["family"], protocol=proto, agent_budget=AGENT_BUDGET[proto], regime=C.REGIME[game], root_key=meta["root_key"], tol=meta["tol"], media=video, extra=meta_extra(C.case_meta(game).get(cid, {})), base_image=args.base_image, env_net=NET[args.net][0], agent_net=NET[args.net][1], keywords=json.dumps(["video-arena", "video-understanding", game, C.REGIME[game], "protocol-" + proto.lower()]))) write(os.path.join(env_dir, "docker-compose.yaml"), COMPOSE_TOML.format( net_line=" network_mode: none\n" if NET[args.net][2] else "", instruction_mount=INSTRUCTION_MOUNT if proto == "B" else "", media_src=video if args.host_media else "${VA_MEDIA_ROOT:?set VA_MEDIA_ROOT to the Video-Arena tasks directory}" "/%s/media/%s.mp4" % (game, cid))) # LF only: some instruction sources carry stray CRLF, which is noise inside a Linux sandbox. if proto == "B": write(os.path.join(task_dir, "instruction.md"), C.build_harbor_prompt()) write(os.path.join(env_dir, "instruction.md"), C.instruction_for("agentic", meta["instruction"]).replace("\r\n", "\n")) else: write(os.path.join(task_dir, "instruction.md"), C.instruction_for("video", meta["instruction"]).replace("\r\n", "\n")) write(os.path.join(tests, "test.sh"), TEST_SH, mode=0o755) write(os.path.join(tests, "score_harbor.py"), SCORE_PY.format( tol=meta["tol"], primary=meta["primary"], root_key=meta["root_key"])) shutil.copyfile(meta["judge"], os.path.join(tests, "judge.py")) shutil.copyfile(meta["gt"], os.path.join(tests, "gt.json")) write(os.path.join(tests, "case.json"), json.dumps( {"game": game, "case_id": cid, "family": meta["family"], "root_key": meta["root_key"], "tol": meta["tol"]}, indent=2) + "\n") write(os.path.join(sol_dir, "solve.sh"), SOLVE_SH, mode=0o755) write(os.path.join(sol_dir, "answer.json"), json.dumps(answer, indent=2) + "\n") return name def main(): ap = argparse.ArgumentParser(description="Generate the Harbor Video-Arena dataset.") ap.add_argument("--out", required=True, help="dataset directory to (re)generate") ap.add_argument("--games", default=",".join(C.GAMES), help="comma-separated subset of: %s" % ",".join(C.GAMES)) ap.add_argument("--cases", type=int, default=0, help="first N cases per game (0 = all 20)") ap.add_argument("--protocol", choices=("B", "A"), default="B", help="B (default): the agentic sandbox task. A: the single-request task, " "run with -a protocol_a_agent:ProtocolA (see docs/HARBOR.md)") ap.add_argument("--base-image", default=DEFAULT_BASE_IMAGE, help="prebuilt sandbox/verifier image (tools/harbor/Dockerfile)") ap.add_argument("--net", choices=sorted(NET), default="strict", help="strict (default): offline for the whole trial, enforced by Harbor and " "by Docker, for host-side agents such as terminus-2. docker: the same " "sandbox enforced by Docker alone, for hosts where Harbor's " "egress-control probe fails. phase: network only while an installed " "agent installs itself; run with --allow-agent-host .") ap.add_argument("--host-media", default=None, metavar="DIR", help="absolute host directory to pin in the generated compose files " "(default: the literal ${VA_MEDIA_ROOT}, resolved at run time)") ap.add_argument("--force", action="store_true", help="delete --out first (it may hold tasks from a previous run)") args = ap.parse_args() games = [g for g in args.games.split(",") if g] unknown = [g for g in games if g not in C.GAMES] if unknown: raise SystemExit("unknown game(s): %s" % unknown) out_dir = os.path.abspath(args.out) if os.path.exists(out_dir): if not args.force: raise SystemExit("%s exists; pass --force to regenerate it" % out_dir) shutil.rmtree(out_dir) os.makedirs(out_dir) made = [] for game in games: ids = C.case_ids(game) for cid in ids[:args.cases] if args.cases else ids: made.append(build_task(game, cid, out_dir, args)) print("%d Protocol %s tasks -> %s" % (len(made), args.protocol, out_dir)) print("image: %s net: %s" % (args.base_image, args.net)) print("media: %s//media/.mp4, mounted read-only at /app/match.mp4" % (args.host_media or "$VA_MEDIA_ROOT")) if __name__ == "__main__": main()