The first exam for code agents in the physical world: frozen robot tasks from many benchmark suites, each answered with a program and verified in a separate sandbox. Runs on Harbor.
Python ai-agentsbenchmarkcoding-agentsembodied-aievaluationharborllm-agentsrobot-learningroboticssimulation
RoboOlympics: fencing bout exported by RoboOlympics' own exporter (the first turn-based exported matches, eai-standard-turn/1.0) (+1 more) (#257, #281)
Changhe Chen96daa3dc90b5
diff --git a/ci_checks/check-protocol.py b/ci_checks/check-protocol.pyindex 9ecf2b07ba..715ab9d311 100755--- a/ci_checks/check-protocol.py+++ b/ci_checks/check-protocol.py@@ -22,23 +22,25 @@ import task_conventions as tc # noqa: E402 (the mode registry, PROTOCOL §2.16# standard-realtime 2.3 (the realtime capability, §4b), privileged noneMODE_PROTOCOLS = {m: set(d["protocols"]) for m, d in tc.MODE_REGISTRY.items()}# Tasks a benchmark exports with its own service inside (PROTOCOL §4c): each such benchmark keeps a manifest,-# scripts/<bench>/exported.toml, that lists the directories (`[[tasks]] name`) and the protocol each mode serves-# (`[protocols]`); a listed directory may declare its manifest's protocol for its mode. No per-benchmark table here.-def _own_protocols() -> dict[str, dict[str, str]]:- out: dict[str, dict[str, str]] = {}+# scripts/<bench>/exported.toml, that lists the directories (`[[tasks]] name`) and the protocol(s) each mode serves+# (`[protocols]`, a string or a list); a listed directory may declare one of its manifest's protocols for its mode. No+# per-benchmark table here.+def _own_protocols() -> dict[str, dict[str, set[str]]]:+ out: dict[str, dict[str, set[str]]] = {}for man in sorted((ROOT / "scripts").glob("*/exported.toml")):d = tomllib.loads(man.read_text())+ protos = {m: {p} if isinstance(p, str) else set(p) for m, p in d.get("protocols", {}).items()}for t in d.get("tasks", []):- out[t["name"]] = d.get("protocols", {})+ out[t["name"]] = protosreturn outOWN_PROTOCOLS = _own_protocols()-def own_protocol(name: str, mode: str | None) -> str | None:- """The protocol a benchmark's own exported task may declare instead (None: not such a task)."""- return OWN_PROTOCOLS.get(name, {}).get(mode or "")+def own_protocols(name: str, mode: str | None) -> set[str]:+ """The protocols a benchmark's own exported task may declare instead (empty: not such a task)."""+ return OWN_PROTOCOLS.get(name, {}).get(mode or "", set())PERSONAL_PATH = re.compile(rb"/(home|Users)/[A-Za-z0-9_.-]+/")@@ -85,7 +87,7 @@ def check_task(task: Path) -> None:if name.endswith("-realtime") and not name.endswith("-standard-realtime") or mode == "realtime":warn("mode name `realtime` / `-realtime` (the third mode is `standard-realtime`, PROTOCOL D12)", name)proto = meta.get("protocol")- if proto is not None and proto == own_protocol(name, mode):+ if proto is not None and proto in own_protocols(name, mode):pass # PROTOCOL §4c: the benchmark's own protocolelse:for m in {mode, named} & set(tc.MODES):diff --git a/docs/TAXONOMY.md b/docs/TAXONOMY.mdindex 5192ac8c60..41b5f3cea3 100644--- a/docs/TAXONOMY.md+++ b/docs/TAXONOMY.md@@ -40,7 +40,7 @@ Benchmark-specific fields (optional, PROTOCOL §1):| RoboFunOlympics | `reset_budget` | integer: the task's default reset budget, its service's `RCB_RESET_BUDGET` default (PROTOCOL §4.5) || DexHand | `hands`, `default_hand` | the hand models the task runs with: `sharpa` (Sharpa Wave, 22 finger actuators) · `wuji` (Wuji Hand 2.2, 20 finger actuators), mounted in place of each Sharpa Wave on the same wrist stage or arm; `default_hand = "sharpa"` (selected with `DEXHAND_HAND`; the verifier replays with the hand the trajectory records) || DexHand | `difficulty`, `release_status` | `hard` (proposed before calibration with agent trials); `provisional` (human solvability review pending, PROTOCOL §2.7) |-| RoboOlympics (exported, PROTOCOL §3) | `opponent_level`, `slowdown` | integers: the scripted opponent's level; the task's slowdown S (the world runs at 1/S of real speed; the sport's official one: 5, 10 or 20) |+| RoboOlympics (exported, PROTOCOL §3) | `opponent_level`, `slowdown` (real-time matches), `chess_clock_s` (turn-based matches) | integers: the scripted opponent's level; the task's slowdown S (the world runs at 1/S of real speed; the sport's official one: 5, 10 or 20); in a turn-based match the world waits for the player whose turn it is, and `chess_clock_s` is each player's clock of real time, running on its own turns || RoboOlympics (exported, PROTOCOL §3) | `revision`, `play`, `player_mode`, `action_level`, `source_task`, `source_commits`, `exporter`, `official`; skill tasks also `skill_deliverable`, `dev_requests`, `success_line` | the sport's revision; `program`; `high` · `low`; the RoboOlympics task it was exported from, its commits and exporter; `false` (development seeds); the deliverable's path, the number of graded requests, the success rate needed || RoboOlympics | `category` | `track-and-jumps` · `football-and-volleyball` · `basketball-and-rackets` · `throwing-catching-striking` · `parkour-apparatus-balance` || RoboOlympics | `reset_budget` | integer: the task's default reset budget, its service's `RCB_RESET_BUDGET` default (PROTOCOL §4.5) |@@ -70,8 +70,9 @@ Benchmark-specific fields (optional, PROTOCOL §1):`roboolympics-<family-with-dashes>-i<NN>` (`[metadata].family` = the family with underscores, e.g. `penalty_kick`);every family in privileged and standard mode. Its exported tasks (PROTOCOL §3, `scripts/roboolympics/exported.toml`): `<base>` is`roboolympics-<sport>-<format>-i<NN>` with the sport's RoboOlympics id (`tabletennis`, `badminton`, `soccer`,- `soccerssl`) and `match`, or a skill format (`hitskill`, `actskill`); matches in standard-realtime mode only, skill- tasks in standard mode only; never a family name of the generated families.+ `soccerssl`, `fencing`) and its format (`match`, `bout`), or a skill format (`hitskill`, `actskill`); real-time+ matches in standard-realtime mode only, turn-based matches (`eai-standard-turn/1.0`) and skill tasks in standard mode+ only; never a family name of the generated families.- RoboPaint: `<base>` is `robopaint-<family>-<target>-i<NN>`; Chinese targets by pinyin (the codepoint appended on acollision, e.g. `robopaint-kaishu-shu-66f8-i00`); `[metadata].family = "robopaint_<family>_<target>"`.- RoboSafeBench: `<base>` is `cell-<slug>-i<NN>` (standard tasks, and for the realtime set `-standard-realtime` twins ofdiff --git a/docs/benchmarks/pandadyn.md b/docs/benchmarks/pandadyn.mdindex 7135b00e64..a80904f495 100644--- a/docs/benchmarks/pandadyn.md+++ b/docs/benchmarks/pandadyn.md@@ -229,6 +229,13 @@ makes the benchmark `dynamic` and lists D05, D08, D11, D12, D13 and S06 as stati- **Contact and safety telemetry.** None is published beyond the robot's own proprioception (motor torques, joint andTCP motion), which is what the safety limits are judged on; contact forces stay private (PROTOCOL §4.5).+- **Scene motion in the privileged instruction** (2026-10-16, #281). The template's sentence "Things move by themselves+ from the first control step on: the scene does not wait for the robot." is written for the 19 dynamic families only+ (`REALTIME` in `mk_tasks.py`); the six static ones (D05, D08, D11, D12, D13, S06) used to carry it too, against their+ own scene text ("Nothing moves by itself"). Only those six privileged `instruction.md` files and their DIGEST changed;+ instance, grading and oracle are the same. Results recorded before stand: the scene text was right, and a privileged+ agent steps the simulator itself and sees that nothing moves.+## Notes on the tasks' checksThe instructions describe each check exactly as the task's code implements it (`scripts/pandadyn/descr/`, written fromthe code alone, never from the reference controllers). Writing them brought up properties of the benchmark's own checksdiff --git a/docs/benchmarks/roboolympics.md b/docs/benchmarks/roboolympics.mdindex ccc03e3d66..a611786f87 100644--- a/docs/benchmarks/roboolympics.md+++ b/docs/benchmarks/roboolympics.md@@ -414,6 +414,8 @@ RoboOlympics commit and the sport's frozen revision of each, and the files chang| `roboolympics-badminton-match-i02-standard-realtime` | as above | level 2, seed 8, S = 20, 14400 s | partial: the camera-only reference does not win level 2 (a model did: Opus 11:7); same task as i01 but the level || `roboolympics-soccer-match-i00-standard-realtime` | humanoid soccer 2 v 2 (RoboCup Humanoid League rules, revision `soccer-2v2-10`: the T1's real motors): one agent commands both Booster T1 robots of its team (walk velocity, stand, kick) from their head cameras against a scripted team; 2 x 5 min of game time | level 2, seed 7, S = 5 (2 x 5 min = 3000 s of wall time plus the reviews, inside 7200 s) | partial: the camera-only reference lost 1:8 on soccer-2v2-10 (0:2 on soccer-2v2-9; it cannot kick while walking; a model has won level 2, Astra 12:2); nop 0. Image `ghcr.io/mll-lab-nu/eai-olympiad-soccer:0.1.0` (private to the mll-lab-nu organization for now) || `roboolympics-soccerssl-match-i00-standard-realtime` | wheeled soccer 5 v 5 (RoboCup Small Size League rules, revision `soccer_ssl-1`): one agent commands its five omnidirectional robots (move, kick, dribble) from four overhead cameras against a scripted team; two halves and, if level, a shoot-out (about 1035 s of game time) | level 2, seed 7, S = 10; agent budget **14400 s** (the task's own `[agent] timeout_sec`: the match alone is 2.9 h of wall time at S = 10, and at S = 5 the four cameras cannot be rendered in time) | partial: the camera-only reference lost 2:5 in a full match (valid, replay identical; 2 h 35 min of agent time, over 7200 s); nop 0 |+| `roboolympics-fencing-bout-i01-standard` | robot epee fencing, one FIE direct-elimination bout (15 touches or 9 min of fencing time; RoboOlympics revision `fencing-7`, a RoboOlympics preview sport): two Unitree G1s (NVIDIA SONIC on legs, waist and free arm) fence phrase by phrase from on guard, each phrase replayed from a table of all 2916 phrases measured in MuJoCo; the agent chooses each phrase's tactical intention (one of nine) against a scripted fencer that reads its choices; turn-based (`eai-standard-turn/1.0`), a chess clock of 60 min per player | level 1, seed 39 | full: the camera-only reference won 15:11 (25 phrases, replay identical; the world is deterministic, so the oracle's result is the one RoboOlympics computes in process; seed chosen by a stated rule, RoboOlympics `tools/fexam/fencing/instances.py`); nop 0 (valid, no-show) |+| `roboolympics-fencing-bout-i02-standard` | as above | level 2, seed 35 | full: the reference won 15:13 (32 phrases, replay identical); nop 0 || `roboolympics-tabletennis-hitskill-i00-standard` | implement the robot's `hit` skill (the blade's state at contact) from the robot's model, its real-limit joint interface and a disclosed toolkit; graded offline by the sport's API test | 90 public development requests (24 development matches); success: rate >= 0.7 | full: RoboOlympics' reference skill 69/90 (the platform's own `hit` 90/90, an IK-only baseline 0/90); nop 0 || `roboolympics-badminton-actskill-i00-standard` | implement the badminton robot's `act` skill (the racket's state at contact, optional base position) from its model, its real-limit joint interface and the toolkit; graded offline by the sport's API test (RoboOlympics revision `badminton-wallclock-12`, PR #98) | 246 public development requests (12 development matches, levels 1-2); success: rate >= 0.8 | full: RoboOlympics' reference skill 244/246; nop 0 |@@ -421,17 +423,17 @@ What differs from the 2.x tasks (PROTOCOL §4c, owner 2026-10-14):| | the 2.x tasks | exported RoboOlympics tasks | why ||---|---|---|---|-| protocol | `eai-standard/2.x` | `eai-standard-realtime/1.0` (matches; RoboOlympics' own: `game` CLI / HTTP at `localhost:8000/A/...`), `skilleval-api-test/1` (skill tasks) | the frozen review after every point (at most 300 s, 600 s in soccer: `READY_TIMEOUT_S`; the world stands still, the agent's time runs on; a side that has not sent `ready` by then loses the match, `ready_timeout`, a valid 0: the world does not go on by itself; stated in each instruction and in `game spec` `timing.review_timeout_s` since 2026-10-14, board 0121, `patched` in exported.toml) is part of RoboOlympics' rules, and its results are only comparable under them |+| protocol | `eai-standard/2.x` | `eai-standard-realtime/1.0` (real-time matches; RoboOlympics' own: `game` CLI / HTTP at `localhost:8000/A/...`), `eai-standard-turn/1.0` (turn-based matches, mode `standard`: the same service and `game` CLI; the world waits for the player whose turn it is, and each player has a chess clock of real time that runs on its own turns, reviews included; a player whose clock runs out loses, a valid 0), `skilleval-api-test/1` (skill tasks) | the frozen review after every point (at most 300 s, 600 s in soccer: `READY_TIMEOUT_S`; the world stands still, the agent's time runs on; a side that has not sent `ready` by then loses the match, `ready_timeout`, a valid 0: the world does not go on by itself; stated in each instruction and in `game spec` `timing.review_timeout_s` since 2026-10-14, board 0121, `patched` in exported.toml) is part of RoboOlympics' rules, and its results are only comparable under them || crash recovery | journal, resume | none: a sim crash ends the trial with `infra_error = 1` | the service replays the whole match from its record to grade it; a resumed match would not be the recorded one |-| slowdown | — | per task, the sport's official slowdown: table tennis 10 (RoboOlympics PR #138), badminton 20, humanoid soccer 5, wheeled soccer 10 (`metadata.slowdown`) | results state S |+| slowdown | — | per task, the sport's official slowdown: table tennis 10 (RoboOlympics PR #138), badminton 20, humanoid soccer 5, wheeled soccer 10 (`metadata.slowdown`); turn-based matches have none (`metadata.chess_clock_s`: fencing 3600 s) | results state S, or the chess clock || agent budget | the benchmark's 7200 s | 7200 s; badminton i01 / i02 and wheeled soccer 14400 s (those tasks' own `[agent] timeout_sec`, owner 2026-10-14) | a game to 11 at S = 20 took the reference alone 78 to 93 min; a 5 v 5 match is 2.9 h of wall time at S = 10 || network | open (part 1's exception) | the allowlist (model APIs and package registries), as every other benchmark: these tasks declare it, and PROTOCOL §2.11 holds them to it | RoboOlympics' design; the open-egress exception is part 1's || twin | privileged + standard | none (the README's Twin row says why) | no trajectory deliverable || skill task | — | mode `standard`, `task_type = "policy"`, no sim service; the verifier runs the simulator and the skill | the deliverable is code (`/app/output/skill/hit.py`, `act.py`) |-| seeds | the instance's | matches: `[metadata.seeds]` default = allowed = the instance's development seed; skill tasks: seed 0 = the fixed development request set | development seeds below 100000: previews; RoboOlympics' official results are produced by RoboOlympics on its hidden six-digit seeds |+| seeds | the instance's | matches: `[metadata.seeds]` default = allowed = the instance's development seed (a turn-based match whose world is deterministic has one outcome per sequence of choices: its oracle is `full` when the reference wins that seed); skill tasks: seed 0 = the fixed development request set | development seeds below 100000: previews; RoboOlympics' official results are produced by RoboOlympics on its hidden six-digit seeds || metering | the usage gateway | the same (the seat is "unmetered" for RoboOlympics: no proxy, no credential in the sim; the D11 proxy's file `metering/think_proxy.py` is in the image's copy but never started) | |-**Replay videos of the matches (fixed here, 2026-10-16, board 0136).** The sim service draws the spectator video after the verdict (`core.spectator`, `RCB_VIDEO_TIMEOUT_S`); the grade never depends on it. Humanoid soccer's full match takes about 8-10 min to replay and draw, so its limit is 1800 s (was 300 s, as wheeled soccer) and the collect hook waits as long. Badminton declares no spectator camera or scene, so the core drew nothing: its tasks run `environment/sim/spectator/sport_video.py` from the collect hook instead (the players' two cameras, the sport's own `Views`, at 10 frames per game second; `video.json` says whether that replay ended in the verdict replay's state). `spectator/` is outside the match's `source_sha` (`core/`, `sport/`), so the match, its replay check and the grade are unchanged and earlier results stand; both are `patched` in `exported.toml` (to be sent upstream: a spectator camera in `sports/badminton/sport.toml` would change the sport's `source_sha`). Table tennis (about 100-420 frames) and wheeled soccer (1800 s) rendered every recorded video and are unchanged.+**Replay videos of the matches (fixed here, 2026-10-16, board 0136).** The sim service draws the spectator video after the verdict (`core.spectator`, `RCB_VIDEO_TIMEOUT_S`); the grade never depends on it. Humanoid soccer's full match takes about 8-10 min to replay and draw, so its limit is 1800 s (was 300 s, as wheeled soccer) and the collect hook waits as long. Badminton declares no spectator camera or scene, so the core drew nothing: its tasks run `environment/sim/spectator/sport_video.py` from the collect hook instead (the players' two cameras, the sport's own `Views`, at 10 frames per game second; `video.json` says whether that replay ended in the verdict replay's state). `spectator/` is outside the match's `source_sha` (`core/`, `sport/`), so the match, its replay check and the grade are unchanged and earlier results stand; both are `patched` in `exported.toml` (to be sent upstream: a spectator camera in `sports/badminton/sport.toml` would change the sport's `source_sha`). Table tennis (about 100-420 frames) and wheeled soccer (1800 s) rendered every recorded video and are unchanged. Fencing (turn-based) draws one still per phrase, held 1 s, with `core.spectator`; its limit is 900 s (board 0146: never shorter than the verdict replay's 600 s), the collect hook waits as long.**Skill tasks' verifier (fixed here, 2026-10-14, board 0111; the #180 review's finding).** The verifier runs thedelivered skill as `nobody` in its own process, in the container that grades it. A skill could leave a detached processdiff --git a/scripts/pandadyn/mk_tasks.py b/scripts/pandadyn/mk_tasks.pyindex 989724558b..ba7c57a4ff 100644--- a/scripts/pandadyn/mk_tasks.py+++ b/scripts/pandadyn/mk_tasks.py@@ -213,7 +213,10 @@ def plan_instance(task: str, R: dict, version: str) -> dict[str, dict[str, tuple"FROZEN": f"{task}-i{i:02d}", "MAX_ROWS": f"{MAX_ROWS:,}", "MODULE_PATH": module.replace(".", "/") + ".py"}priv = {"SCENE_PRIVILEGED": D["scene_privileged"], "PARAMS": params, "GOALS": goals_priv, "SUMMARY": D["summary"],"ROBOT_SETUP": D["robot_setup"], "SCENE": D["scene"], "PHASES_BLOCK": phases_block(False), "FAILURES_BLOCK": fails_block(False),- "CONTACT_RULES": D["contact_rules"]}+ "CONTACT_RULES": D["contact_rules"],+ # only the dynamic families (REALTIME) start moving on their own; in the static ones nothing moves by itself+ "SCENE_MOTION": " Things move by themselves from the first control step on: the scene does not wait for the robot."+ if code in REALTIME else ""}std = {"GOALS_STD": goals_std, "STANDARD_NOTES": std_text(D["standard_notes"], f"{code} standard_notes"),"SUMMARY": std_text(D["summary"], f"{code} summary"), "ROBOT_SETUP": std_text(D["robot_setup"], f"{code} robot_setup"),"SCENE": std_text(D["scene"], f"{code} scene"), "PHASES_BLOCK": phases_block(True), "FAILURES_BLOCK": fails_block(True),diff --git a/scripts/pandadyn/template/privileged/instruction.md.tmpl b/scripts/pandadyn/template/privileged/instruction.md.tmplindex f15f4b70a2..5ed8912f95 100644--- a/scripts/pandadyn/template/privileged/instruction.md.tmpl+++ b/scripts/pandadyn/template/privileged/instruction.md.tmpl@@ -5,7 +5,7 @@ You control @@ROBOT_INTRO@@ in a simulated scene (ManiSkill 3 / SAPIEN, rigid-boThis is a *fixed scene instance*: everything starts the same way after every reset, and you may reset and retry as manytimes as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a general-policy. Things move by themselves from the first control step on: the scene does not wait for the robot.+policy.@@SCENE_MOTION@@## Scene@@ROBOT_SETUP@@diff --git a/scripts/roboolympics/exported.toml b/scripts/roboolympics/exported.tomlindex 6b6f77b553..63c3d1ede3 100644--- a/scripts/roboolympics/exported.toml+++ b/scripts/roboolympics/exported.toml@@ -9,8 +9,10 @@# The protocol each mode of these tasks serves (PROTOCOL §4c): ci_checks/check-protocol.py accepts it for the# directories listed below only.[protocols]-standard-realtime = "eai-standard-realtime/1.0" # the matches: RoboOlympics' own service and referee-standard = "skilleval-api-test/1" # the skill tasks (task_type = "policy"), graded offline+standard-realtime = "eai-standard-realtime/1.0" # the real-time matches: RoboOlympics' own service and referee+standard = ["skilleval-api-test/1", # the skill tasks (task_type = "policy"), graded offline+ "eai-standard-turn/1.0"] # the turn-based matches: the world waits for the player whose turn it+ # is, a chess clock per player (RoboOlympics' own service and referee)[[tasks]]name = "roboolympics-badminton-actskill-i00-standard"@@ -36,6 +38,20 @@ source_commits = ["0d7f680cc049"]patched = ["instruction.md", "environment/sim/core/realtime.py", # 2026-10-14, board 0121: the review time limit and its forfeit stated (instruction, game spec timing)"task.toml", "environment/docker-compose.yaml", "README.md", "environment/sim/spectator/sport_video.py"] # 2026-10-16, board 0136: a replay video from the players' cameras (no spectator camera / scene in the sport)+[[tasks]]+name = "roboolympics-fencing-bout-i01-standard"+source_task = "roboolympics/fencing-bout-wallclock-program-standard"+revision = "fencing-7+core-0.2"+source_commits = ["a6712a675343"]+patched = ["task.toml", "environment/docker-compose.yaml"] # 2026-10-16, board 0146: the replay video's time limit 300 -> 900 s (not shorter than the verdict replay's 600 s), the collect / verifier timeouts with it++[[tasks]]+name = "roboolympics-fencing-bout-i02-standard"+source_task = "roboolympics/fencing-bout-wallclock-program-standard"+revision = "fencing-7+core-0.2"+source_commits = ["a6712a675343"]+patched = ["task.toml", "environment/docker-compose.yaml"] # 2026-10-16, board 0146: the replay video's time limit 300 -> 900 s (not shorter than the verdict replay's 600 s), the collect / verifier timeouts with it+[[tasks]]name = "roboolympics-soccer-match-i00-standard-realtime"source_task = "roboolympics/soccer-match-wallclock-program-standard"diff --git a/scripts/task_conventions.py b/scripts/task_conventions.pyindex ac244cb64d..2d09282b54 100644--- a/scripts/task_conventions.py+++ b/scripts/task_conventions.py@@ -92,6 +92,8 @@ BENCHMARKS = [ # (directory prefix, label)RO_EXPORTED_TASKS = ("roboolympics-badminton-actskill-i00-standard","roboolympics-badminton-match-i01-standard-realtime","roboolympics-badminton-match-i02-standard-realtime",+ "roboolympics-fencing-bout-i01-standard",+ "roboolympics-fencing-bout-i02-standard","roboolympics-soccer-match-i00-standard-realtime","roboolympics-soccerssl-match-i00-standard-realtime","roboolympics-tabletennis-hitskill-i00-standard",diff --git a/scripts/task_resources.toml b/scripts/task_resources.tomlindex 043ff0a10e..0cb09a958f 100644--- a/scripts/task_resources.toml+++ b/scripts/task_resources.toml@@ -844,7 +844,7 @@ measured = "author estimate (ws-1, 2026-10-11): CPU-only MuJoCo with OSMesa rend# roboolympics, standard: 50 task(s)[[rule]]-match = "^roboolympics-(?!tabletennis-hitskill-|badminton-actskill-).*-standard$" # not the exported skill tasks (their rules follow)+match = "^roboolympics-(?!tabletennis-hitskill-|badminton-actskill-|fencing-bout-i[0-9]{2}-).*-standard$" # not the exported skill tasks and turn-based matches (their rules follow)min_cpus = 3.0min_memory_gb = 5.0min_gpu_memory_gb = 0.0@@ -881,6 +881,19 @@ verifier_min_memory_gb = 4.0verifier_min_gpu_memory_gb = 0.0measured = "RoboOlympics' exported skill tasks (scripts/roboolympics/exported.toml; ws-1/2, 2026-10): no sim service, the agent 2 CPUs; the verifier runs the simulator and the skill; CPU only"+# roboolympics, exported turn-based matches (standard, eai-standard-turn/1.0): 2 task(s)+[[rule]]+match = "^roboolympics-fencing-bout-i[0-9]{2}-standard$"+min_cpus = 3.0+min_memory_gb = 5.0+min_gpu_memory_gb = 0.0+gpu_required = false+gpu_class = "none"+verifier_min_cpus = 2.0+verifier_min_memory_gb = 3.0+verifier_min_gpu_memory_gb = 0.0+measured = "vanilla Harbor 0.23.0 on ws-3 (32 cores), 2026-10-15, oracle and nop of both tasks, docker stats every 5 s: the sim peaks at 4.0 CPUs (its cap) and 0.71 GiB (the replay in a fresh process and the video after the bout; a bout is about 20 s of service time), the oracle's container under 0.1 GiB (a model's harness needs more: RoboOlympics' agent default); turn-based, so fewer CPUs only slow it down; CPU only"+# roboolympics, standard-realtime: 13 task(s)[[rule]]match = "^roboolympics-(?!(tabletennis|badminton|soccer|soccerssl)-match-i[0-9]{2}-).*-standard-realtime$" # not the exported matches (their own rules)@@ -994,7 +1007,7 @@ trial_max_memory_gb = 13.0measured = "author estimate: no trials yet; memory under the 16 GiB cap by the margin the monitor needs (an agent may run several worlds at once or train a controller); disk 20 GiB for downloaded tools and controllers; processes 512: design default"[[limit]]-match = "^roboolympics-(?!tabletennis-hitskill-|badminton-actskill-).*-standard$" # not the exported skill tasks (their rules follow)+match = "^roboolympics-(?!tabletennis-hitskill-|badminton-actskill-|fencing-bout-i[0-9]{2}-).*-standard$" # not the exported skill tasks and turn-based matches (their rules follow)scope = "agent"max_gpu_memory_gb = 0.0max_memory_gb = 8.0@@ -1038,6 +1051,21 @@ trial_max_gpu_memory_gb = 0.0trial_max_memory_gb = 4.0measured = "design defaults of RoboOlympics' exported tasks (no sim service)"+[[limit]]+match = "^roboolympics-fencing-bout-i[0-9]{2}-standard$"+scope = "agent"+max_gpu_memory_gb = 0.0+max_memory_gb = 4.0+max_processes = 512+max_disk_gb = 20.0+disk_paths = ["/app", "/tmp", "/root"]+disk_exclude = []+sustain_sec = 60.0+window_sec = 120.0+trial_max_gpu_memory_gb = 0.0+trial_max_memory_gb = 12.0+measured = "design defaults of RoboOlympics' exported matches (the agent 4 GiB under its 6 GiB cap; whole trial: + the sim's 8 GiB cap); measured peaks 2026-10-15: sim 0.71 GiB, oracle container under 0.1 GiB"+[[limit]]match = "^roboolympics-(?!(tabletennis|badminton|soccer|soccerssl)-match-i[0-9]{2}-).*-standard-realtime$" # not the exported matches (their own rules)scope = "agent"@@ -2378,7 +2406,7 @@ match = "^roboolympics-.*-privileged$"main = { cpus = 8.0, memory_gb = 16.0, pids = 8192 }[[cap]]-match = "^roboolympics-(?!tabletennis-hitskill-|badminton-actskill-).*-standard$" # not the exported skill tasks (their rules follow)+match = "^roboolympics-(?!tabletennis-hitskill-|badminton-actskill-|fencing-bout-i[0-9]{2}-).*-standard$" # not the exported skill tasks and turn-based matches (their rules follow)main = { cpus = 4.0, memory_gb = 10.0, pids = 8192 }sim = { cpus = 4.0, memory_gb = 8.0, pids = 8192 }@@ -2461,6 +2489,11 @@ sim = { cpus = 6.0, memory_gb = 8.0, pids = 256 } # the sim service's own pidsmatch = "^roboolympics-(tabletennis-hitskill|badminton-actskill)-i[0-9]{2}-standard$"main = { cpus = 2.0, memory_gb = 6.0, pids = 8192 }+[[cap]]+match = "^roboolympics-fencing-bout-i[0-9]{2}-standard$"+main = { cpus = 2.0, memory_gb = 6.0, pids = 8192 }+sim = { cpus = 4.0, memory_gb = 8.0, pids = 256 } # the sim service's own cpus and pids_limit (RoboOlympics' exported docker-compose.yaml)+[[cap]]match = "^pandadyn-.*-privileged$"main = { cpus = 8.0, memory_gb = 20.0, pids = 8192 }diff --git a/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/DIGEST b/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/DIGESTindex 6c45876f8e..31b75127b0 100644--- a/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/DIGEST+++ b/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/DIGEST@@ -1 +1 @@-sha256:d29ef7e819e89c33426c2bea65223cfe8e6ac8335804464f7133918c49af22ff+sha256:c2dec29f714f6e431bd0a683754d24bf4ab52d8702c5f6b7f898de34accf858adiff --git a/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/instruction.md b/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/instruction.mdindex c4d76691ae..b345fa3902 100644--- a/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/instruction.md+++ b/tasks/pandadyn-d05-moving-ramp-relay-i00-privileged/instruction.md@@ -5,7 +5,7 @@ You control two simulated **Franka Panda** arms (`panda-0` on the left, `panda-1This is a *fixed scene instance*: everything starts the same way after every reset, and you may reset and retry as manytimes as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a general-policy. Things move by themselves from the first control step on: the scene does not wait for the robot.+policy.## Scenepanda-0 (left): base at (-0.55, -0.22, 0), yaw 0 (facing +x). It carries an open-top square cup, 0.14 m x 0.14 m inside (2 x `tool_half`, `tool_half` = 0.07 m), with four 0.055 m high, 5 mm thick walls and a 5 mm floor, held by an adapter on its tool -x wall. The tool frame is the centre of the cup floor's inner surface, z up. The TCP sits 0.12 m along tool -x and 0.04 m above the tool frame. Start: (-0.04, -0.14, 0.23), orientation identity (upright). panda-1 (right): base at (0.74, 0.22, 0), yaw pi (facing -x). It carries a straight channel, open at both ends and 0.28 m long (2 x `right_tool_half`, `right_tool_half` = 0.14 m). It has a flat floor 72 mm wide and 8 mm thick and two side walls 40 mm high and 8 mm thick. A side adapter holds it at the middle of its tool +y wall. The tool frame is the centre of the floor's top surface: x runs along the channel (the +x end is the outlet, the -x half the inlet side), y across it, z up. The TCP sits 0.12 m along tool -x, 0.12 m along tool +y and 0.04 m above the tool frame. Start: (0.18, 0.10, 0.24), quaternion (0, 0, 0, 1) (yawed 180 deg: level, outlet end toward world -x). Role labels (panda-0 / panda-1) by phase: first_channel_entry donor / channel_operator; first_moving_exit relocating_receiver / moving_outlet; first_catch catcher / channel_support; second_channel_entry donor / changed_channel; second_moving_exit relocating_receiver / moving_outlet; second_catch_and_delivery catcher_deliverer / channel_support.diff --git a/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/DIGEST b/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/DIGESTindex d7f51e1a63..d49f8ad91f 100644--- a/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/DIGEST+++ b/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/DIGEST@@ -1 +1 @@-sha256:a0d4419677cb012f2f01ba1a8d4394f7136793c17d79757013b59894f3bf233d+sha256:e03e8bb49adf30df330dfbb389058c1e735662fe8aee255ab42dd3df1fe36236diff --git a/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/instruction.md b/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/instruction.mdindex faf0da14f4..9e79c81b9a 100644--- a/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/instruction.md+++ b/tasks/pandadyn-d08-pendulum-energy-relay-i00-privileged/instruction.md@@ -5,7 +5,7 @@ You control two simulated **Franka Panda** arms (`panda-0` on the left, `panda-1This is a *fixed scene instance*: everything starts the same way after every reset, and you may reset and retry as manytimes as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a general-policy. Things move by themselves from the first control step on: the scene does not wait for the robot.+policy.## SceneTwo Pandas facing each other along x. panda-0 (left): base at (-0.55, -0.22, 0), yaw 0 (facing +x). panda-1 (right): base at (0.74, 0.22, 0), yaw pi (facing -x). Each hand carries the same rigid 'fork' paddle: one flat vertical blade, 12 mm thick, 0.14 m wide (2 x `tool_half`, 0.07 at this instance) and 50 mm tall. A grey adapter (a horizontal bar from the hand and a short post) ends about 5 cm behind the blade on the hand side; blade and adapter form one rigid tool link. The tool frame is the centre of the blade: x is the blade normal (pointing away from the arm's own base), y runs along the blade's width, z is up. With the tool level the hand points straight down and the blade centre is 0.12 m ahead of the gripper TCP along tool x and 0.04 m below it. Start: left tool frame at (-0.04, -0.02, 0.21), axes aligned with the world (blade normal +x); right tool frame at (0.28, 0.02, 0.21), rotated 180 deg about z (blade normal -x, facing the left arm). Both arms use a slower motion profile than the default: the joint trajectory generator is limited to 20 % of the Panda's acceleration limits and 1 % of its jerk limits (default 55 % and 5 %), and wrist joints 5-7 use higher damping gains (24, 20, 14 instead of 12, 10, 7). Role labels per phase (left, right): left_excitation: exciter, preparing_brake; right_braking: cleared_exciter, brake; right_return_impulse: preparing_receiver, return_driver; left_recovery: brake, cleared_driver; low_energy_hold: damping_support, cleared_partner.diff --git a/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/DIGEST b/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/DIGESTindex 386626f7fb..b4cd04b893 100644--- a/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/DIGEST+++ b/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/DIGEST@@ -1 +1 @@-sha256:1c9a0481e6802487ff4f6059a4788fd6862b13836a481f3c0d31bbf66308f817+sha256:183ee664ca3f5911e6339857a5a2aab56ff365743e197f597f521812801acf4ddiff --git a/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/instruction.md b/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/instruction.mdindex d29b149f06..c4c26a98d4 100644--- a/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/instruction.md+++ b/tasks/pandadyn-d11-moving-fixture-unlock-i00-privileged/instruction.md@@ -5,7 +5,7 @@ You control two simulated **Franka Panda** arms (`panda-0` on the left, `panda-1This is a *fixed scene instance*: everything starts the same way after every reset, and you may reset and retry as manytimes as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a general-policy. Things move by themselves from the first control step on: the scene does not wait for the robot.+policy.## SceneTwo Pandas facing each other along x. panda-0 (left): base at (-0.55, -0.22, 0), yaw 0 (facing +x), no tool: its tool frame is the gripper TCP (the point between the fingertips). It starts with the TCP at (-0.063, 0, 0.285), pointing straight down (TCP x = world +x, fingers closing along world y). Its fingers start open 0.0175 m each (0.035 m total aperture), straddling the fixture's 34 mm wide handle without gripping it. For this arm the finger servo is stiffer than the default (finger PD gains kp 1875 N/m and kd 8 instead of 300 and 12; the force is still capped at 15 N per finger). Its fingers also follow their own trajectory, not synchronized with the arm joints. panda-1 (right): base at (0.74, 0.22, 0), yaw pi (facing -x). Its tool is a square peg, 16 x 16 mm in section and 70 mm long, hanging straight down from the tool frame: the tool frame is at the peg's top end and the tip is at tool-frame (0, 0, -0.07). A grey adapter (a horizontal bar from the hand and a short post) ends about 5 cm behind the peg on the hand side; peg and adapter form one rigid tool link. With the peg vertical the hand points straight down and the peg's top is 0.12 m ahead of the gripper TCP along tool x and 0.04 m below it. Start: tool frame at (0.12, 0.15, 0.40), peg vertical, rotated 180 deg about z (tool x = world -x), so the tip is at (0.12, 0.15, 0.33). Role labels per phase (left, right): moving_fixture_presentation: fixture_support, tracking_pin; relative_pin_insertion: moving_fixture_support, pin_inserter; mechanical_latch_open: fixture_support, latch_operator; follow_and_withdraw: outlet_operator, withdrawing_pin; gravity_delivery: outlet_support, cleared_pin.diff --git a/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/DIGEST b/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/DIGESTindex 8a63033458..122c89de13 100644--- a/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/DIGEST+++ b/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/DIGEST@@ -1 +1 @@-sha256:80ce99ebb3b65b97c339ac558b15f1fe003c88e3f0967653077c1ea25cbdfc26+sha256:d63996d592b9f61f65b7b24bc93f53509aa121155756fe4dc71fcd8110175788diff --git a/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/instruction.md b/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/instruction.mdindex b408ecc3d0..3f5923ec43 100644--- a/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/instruction.md+++ b/tasks/pandadyn-d12-reciprocal-sliding-transfer-i00-privileged/instruction.md@@ -5,7 +5,7 @@ You control two simulated **Franka Panda** arms (`panda-0` on the left, `panda-1This is a *fixed scene instance*: everything starts the same way after every reset, and you may reset and retry as manytimes as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a general-policy. Things move by themselves from the first control step on: the scene does not wait for the robot.+policy.## SceneTwo Pandas facing each other along x. panda-0 (left): base at (-0.55, -0.22, 0), yaw 0 (facing +x). panda-1 (right): base at (0.74, 0.22, 0), yaw pi (facing -x). Each hand carries a scoop: a square tray with a 5 mm floor, inside 0.16 x 0.16 m (2 x `tool_half`, 0.08 at this instance). It has 25 mm high, 5 mm thick walls on three sides and no wall on its tool +x side, the side pointing away from the arm's own base. The tool frame is the centre of the inside floor surface, z up, x toward the open side. With the scoop level the hand points straight down and the scoop's floor centre is 0.12 m ahead of the gripper TCP along tool x and 0.04 m below it. The grey adapter enters at the middle of the back (tool -x) wall: a 12 mm wide post protrudes 6 mm inward from floor level up to 35 mm, and a bar protrudes 12 mm inward 29-41 mm above the floor, above the wall top. Start: left floor centre at (-0.015, -0.04, 0.19), level, axes aligned with the world (open side facing +x). Right floor centre at (0.175, -0.04, 0.187), level, rotated 180 deg about z (open side facing -x). The two open edges thus face each other across a gap of about 2 cm, with the right floor 3 mm lower. Role labels per phase (left, right): left_inertial_slip: inertial_donor, matched_receiver; right_receive_and_brake: cleared_donor, braking_receiver; reverse_geometry: preparing_receiver, loaded_carrier; left_receive_and_brake: braking_receiver, inertial_donor; final_support_deposit: deliverer, cleared_partner.diff --git a/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/DIGEST b/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/DIGESTindex 385684e46b..f0e261ab19 100644--- a/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/DIGEST+++ b/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/DIGEST@@ -1 +1 @@-sha256:204c2a39971f97c2716c0fcec5f5f3f69815a4e4e350bb3ed8dd53e7e244e3a2+sha256:00738ef20bf032f272a0df19914d9ef6c8e5acec1b989e93287c749c5cc53a71diff --git a/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/instruction.md b/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/instruction.mdindex d17c0eb76e..34459e6fca 100644--- a/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/instruction.md+++ b/tasks/pandadyn-d13-supported-cube-flip-relay-i00-privileged/instruction.md@@ -5,7 +5,7 @@ You control two simulated **Franka Panda** arms (`panda-0` on the left, `panda-1This is a *fixed scene instance*: everything starts the same way after every reset, and you may reset and retry as manytimes as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a general-policy. Things move by themselves from the first control step on: the scene does not wait for the robot.+policy.## SceneTwo Pandas facing each other along x. panda-0 (left): base at (-0.55, -0.22, 0), yaw 0 (facing +x). Its tool is a tray with a 5 mm floor, inside 0.24 x 0.24 m (2 x `left_tool_half`, 0.12 at this instance), with walls 12 mm high and 5 mm thick on all four sides. The tool frame is the centre of the inside floor surface, z up, x pointing away from the arm's base. With the tray level the hand points straight down and the floor centre is 0.12 m ahead of the gripper TCP along tool x and 0.04 m below it. The grey adapter enters at the middle of the back (tool -x) wall: a 12 mm wide post protrudes 6 mm inward from the floor up to 35 mm, and a bar protrudes 12 mm inward 29-41 mm above the floor, above the 12 mm wall. Start: floor centre at (0.04, -0.035, 0.23), level, axes aligned with the world. panda-1 (right): base at (0.74, 0.22, 0), yaw pi (facing -x). Its tool is a pusher: a small rigid plate 8 mm thick (along tool x), 50 mm wide (tool y) and 12 mm tall (tool z), with the tool frame at its centre and x normal to its face, pointing away from the arm's base. The pusher centre is 0.12 m ahead of the TCP along tool x and 0.04 m below it. A grey adapter (a horizontal bar from the hand and a short post) ends about 5 cm behind it on the hand side; plate and adapter form one rigid tool link. Start: pusher centre at (0.16, 0.02, 0.268), rotated 180 deg about z (face normal = world -x, toward the tray). Role labels per phase (left, right): support_presentation: tray_support, preparing_pusher; first_inertial_flip: moving_support, impulse_pusher; second_contact_geometry: repositioning_support, cleared_pusher; second_inertial_flip: moving_support, impulse_pusher; oriented_output: oriented_carrier, cleared_pusher.diff --git a/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/DIGEST b/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/DIGESTindex 07a4d30997..8bcdebd400 100644--- a/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/DIGEST+++ b/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/DIGEST@@ -1 +1 @@-sha256:af91e95ee6c53e18d2c14a72b8773b500e97ed99ee89d4f0e91649a670d84cb1+sha256:cb539941632bd697175694dd162966cabb3597e04e6c0cc7f56ec5934587e89ddiff --git a/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/instruction.md b/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/instruction.mdindex a1cef8fa30..7514b144af 100644--- a/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/instruction.md+++ b/tasks/pandadyn-s06-cube-flip-route-recover-i00-privileged/instruction.md@@ -5,7 +5,7 @@ You control one simulated **Franka Panda** arm (7 joints, its standard hand, andThis is a *fixed scene instance*: everything starts the same way after every reset, and you may reset and retry as manytimes as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a general-policy. Things move by themselves from the first control step on: the scene does not wait for the robot.+policy.## SceneOne Panda, base at (-0.40, 0, 0), yaw 0 (facing +x). Its hand carries a small blue pusher blade: a box 8 mm thick (tool x) x 50 mm wide (tool y) x 12 mm tall (tool z), centred at the tool frame origin; its pushing faces are normal to the tool x axis. The blade hangs from a rigid side adapter (part of the tool): from the hand a horizontal bar at tool z = 0.035 runs from tool x = -0.12 to 0 at tool y = +0.13, then along y to y = 0.07, ending in a short 12 mm x 12 mm post at (0, 0.07) reaching down from z = 0.036 to z = 0 (the blade's mid-height); the post stands 45 mm beyond the blade's +y end and is not joined to it visibly, but blade, bars and post are one rigid tool. The Panda TCP is at (-0.12, 0.13, 0.04) in the tool frame, so with the blade level the gripper points straight down. At the start the blade is level (tool axes aligned with the world axes, pushing faces normal to world x), its centre at (-0.05, -0.08, 0.179).diff --git a/tasks/roboolympics-fencing-bout-i01-standard/DIGEST b/tasks/roboolympics-fencing-bout-i01-standard/DIGESTnew file mode 100644index 0000000000..4f9bb230a6--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/DIGEST@@ -0,0 +1 @@+sha256:2838fbda4ac0b91922f93fc8610552431e40a061a81095e6f6366053e9bc4b74diff --git a/tasks/roboolympics-fencing-bout-i01-standard/README.md b/tasks/roboolympics-fencing-bout-i01-standard/README.mdnew file mode 100644index 0000000000..48ce5db0ad--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/README.md@@ -0,0 +1,49 @@+# roboolympics-fencing-bout-i01-standard++| | |+|---|---|+| Benchmark | RoboOlympics |+| Mode | standard (`eai-standard-turn/1.0`) |+| Twin | — (none: a task RoboOlympics exports with its own service, PROTOCOL §4c; a turn-based match has no trajectory deliverable) |+| Simulator / robot | `mujoco` / `unitree-g1` |+| Family / instance | `fencing_bout` / seed 39 |+| Oracle | `full` — in process (fencing-7): the oracle beats level 1 on this seed 15:11; over 40 player seeds the reference wins this instance 62.5 %, the equilibrium mix 47.5 % (fresh-seed means 61.5 %, 53.5 %); none of the nine constant intentions nor a random player wins it; live on vanilla Harbor 0.23.0 (2026-10-15, the exported task) the oracle won 15:11 in 25 phrases, replay identical (the world is deterministic) |+| Agent time budget | 7200 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-olympiad:0.1.0` |++## Task+Robot epee fencing against the scripted opponent (level 1), program play: two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time.++## Difficulty+Frozen development instance: seed 39, level 1, chess clock 3600 s per player. Not one of+the sport's official (hidden) seeds, so results here are previews, not official RoboOlympics results.++## Reference solution+`solution/`: our camera-only reference player through the same HTTP interface. in process (fencing-7): the oracle beats level 1 on this seed 15:11; over 40 player seeds the reference wins this instance 62.5 %, the equilibrium mix 47.5 % (fresh-seed means 61.5 %, 53.5 %); none of the nine constant intentions nor a random player wins it; live on vanilla Harbor 0.23.0 (2026-10-15, the exported task) the oracle won 15:11 in 25 phrases, replay identical (the world is deterministic).++## Verification+Separate sandbox, no network. The sim service replays the recorded match in a fresh process; the verifier+(`tests/grade.py`, our core's grader) checks that the replay agrees with the live match, applies the validity rule+(technical failures void the trial, a player's own problems are a valid loss), and writes reward.json; success = a+valid, finished match that the agent won. `tests/fexam_reward.py` adds the hub's fields (`infra_error`, `realtime`,+`slowdown`, `opponent_level`; `realtime` = 0 for a turn-based match).++## Compute resources+Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]` in `task.toml`). The agent phase counts every container of the trial at once (the agent's, and in standard modes the simulator sidecar); the verifier phase runs after it.++| | Agent phase | Verifier |+|---|---|---|+| CPU cores | 3 | 2 |+| Memory | 5 GB | 3 GB |+| GPU memory | 0 GB | 0 GB |++- GPU: not needed.+- Measured: vanilla Harbor 0.23.0 on ws-3 (32 cores), 2026-10-15, oracle and nop of both tasks, docker stats every 5 s: the sim peaks at 4.0 CPUs (its cap) and 0.71 GiB (the replay in a fresh process and the video after the bout; a bout is about 20 s of service time), the oracle's container under 0.1 GiB (a model's harness needs more: RoboOlympics' agent default); turn-based, so fewer CPUs only slow it down; CPU only+- Limits in the agent phase (docs/PROTOCOL.md §2.10; `[metadata.resources.limits]`, shown to the agent in `instruction.md`; always measured and reported, and exceeding one fails the trial only when the run sets `RCB_LIMITS_ENFORCE=1`), the agent's container: no GPU, 4 GiB memory, 512 processes, 20 GiB of new files under `/app`, `/tmp`, `/root`; 60 s within 120 s. Expected peak of the whole trial: 0 GiB GPU memory, 12 GiB memory. Limits measured: design defaults of RoboOlympics' exported matches (the agent 4 GiB under its 6 GiB cap; whole trial: + the sim's 8 GiB cap); measured peaks 2026-10-15: sim 0.71 GiB, oracle container under 0.1 GiB.++## Details++### Notes+Source: RoboOlympics task `fencing-bout-wallclock-program-standard`, revision `fencing-7+core-0.2`. The rules, the referee, the scripted+opponent, the observation, the review between points and the grader are ours, unchanged; only the seat is+unmetered (Harbor records the model's usage) and the instance is frozen.diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/Dockerfile b/tasks/roboolympics-fencing-bout-i01-standard/environment/Dockerfilenew file mode 100644index 0000000000..4d1e89d49b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/Dockerfile@@ -0,0 +1,10 @@+# The player's container: no simulator, only Python with the standard client pins and the generic `game`+# command of the core (core/game.py, the sport's shortcuts filled in by tools/generate.py).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /opt/client-requirements.txt+RUN pip install --no-cache-dir -r /opt/client-requirements.txt+COPY game /usr/local/bin/game+RUN chmod +x /usr/local/bin/game && mkdir -p /app/output+ENV SEAT=A+ENV SIM_URL=http://localhost:8000+WORKDIR /appdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/client-requirements.txt b/tasks/roboolympics-fencing-bout-i01-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/docker-compose.yaml b/tasks/roboolympics-fencing-bout-i01-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..26ac384316--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/docker-compose.yaml@@ -0,0 +1,77 @@+# Exported by RoboOlympics tools/export_fexam.py (do not edit). The `sim` sidecar runs our simulator service+# unchanged (core/launch.py: the match service, eai-standard-turn/1.0); the agent's container (main)+# reaches it at localhost:8000: under Harbor's egress control both share the egress sidecar's network+# namespace (keep [agent] network_mode = "allowlist"). The seat is unmetered: no metering proxy and no+# credential here (Harbor records the model's usage). CPU only (MuJoCo, OSMesa). cap_drop NET_RAW: no raw+# sockets and no SO_MARK, which could bypass the egress proxy's mark.+services:+ main:+ pids_limit: 8192 # rcb-monitor+ volumes: # rcb-monitor+ - rcb_limits:/run/rcb-limits:ro # rcb-monitor+ depends_on: [sim]+ cap_drop: [NET_RAW]+ sim:+ image: ghcr.io/mll-lab-nu/eai-olympiad:0.1.0+ volumes:+ - rcb_observe:/run/rcb-observe:ro # rcb-monitor+ - ./sim:/srv:ro+ working_dir: /srv+ command: python3 /srv/core/launch.py+ cpus: 4+ mem_limit: 8g+ pids_limit: 256+ cap_drop: [NET_RAW]+ environment:+ RCB_DATA: "/data"+ MUJOCO_GL: "osmesa"+ PYOPENGL_PLATFORM: "osmesa"+ OPENBLAS_NUM_THREADS: "1"+ OMP_NUM_THREADS: "1"+ RO_PLUGIN: "/srv/sport/plugin.py"+ RO_SPORT: "fencing"+ RO_FORMAT: "bout"+ RO_SEATS: "A"+ RO_SEED: "39"+ RO_SEED_SALT: ""+ RO_SEED_INDEX: ""+ RO_FIRST: "A"+ RO_LEVEL: "1"+ RO_RENDERER: "mujoco"+ RCB_ACTION_LEVEL: "low"+ RCB_PLAY: "program"+ RCB_ACT_RULE: "program"+ CLOCK_S: "3600"+ START_TIMEOUT_S: "1800"+ READY_TIMEOUT_S: "300"+ SEAT_HOSTS: ""+ RCB_RENDER_VIDEO: "1"+ RCB_BROADCAST: "1"+ RO_REPLAY_TIMEOUT_S: "600"+ RCB_VIDEO_TIMEOUT_S: "900"+ RO_VIDEO_RENDERER: ""+ PLAYER_MODE_A: "unmetered"+ RCB_WALL_CLOCK_S: "7200"+ # >>> rcb_monitor (resource limits monitor, docs/PROTOCOL.md §2.10; generated by scripts/rcb_monitor/inject.py)+ rcb_monitor:+ image: ghcr.io/mll-lab-nu/eai-monitor:0.1.0@sha256:f2c910f53f79c2bfa4a71298b10c78383cae3afc40720ca562cc845b8d20fb0c+ pid: host # sees every container's processes (and NVML's host PIDs); the agent never sees it+ cgroup: host # reads each container's own cgroup (memory, OOM kills, caps)+ network_mode: none+ cap_add: [SYS_PTRACE] # reads /proc of processes running as other users+ cpus: 0.5+ mem_limit: 256m+ pids_limit: 64+ restart: on-failure:3+ working_dir: /var/rcb-monitor+ volumes:+ - ./rcb_monitor:/opt/rcb_monitor:ro+ - rcb_limits:/run/rcb-limits+ - rcb_observe:/run/rcb-observe+ environment:+ RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} # 1: stop the agent at a confirmed violation, and fail the trial+ command: ["python3", "/opt/rcb_monitor/monitor.py", "run"]+ # <<< rcb_monitor+volumes: # rcb-monitor+ rcb_limits: # rcb-monitor+ rcb_observe: # rcb-monitordiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/game b/tasks/roboolympics-fencing-bout-i01-standard/environment/gamenew file mode 100755index 0000000000..d5069faa64--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/game@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""game - your seat in the match (the same commands for every sport; the actions are the sport's, see `game spec`).++ game spec the sport: actions (types, fields, ranges), cameras, units, rules, timing+ game status the current state, no images+ game start you are ready (preparation over); the match begins when every seat has started+ game wait [SECONDS] turn-based: block until it is your turn; real time: let the world run SECONDS (<= 1)+ game observe [QUERY_JSON] the state and the camera images (saved as PNG under /app/output/views/)+ game act ACTION_JSON one action, e.g. game act '{"type": "throw", ...}' (if the sport shows the result+ in images, they are saved like observe's, as reply_*.png)+ game ready "WHY" "PLAN" your review (after each of your actions, turn-based; at each review, real time)+ game say "TEXT" team formats: a message to your teammates (never shown to the other side)+ game team [SINCE] team formats: your teammates' messages after seq SINCE (default 0); reading never+ consumes them (observe / status show the recent ones and team_seq, the newest seq)+Sport shortcuts (generated from the sport's declaration):+ game phrase INTENTION"""+import base64+import json+import os+import sys+import tempfile+import urllib.error+import urllib.request++COMMANDS = json.loads('{"phrase": ["phrase", "intention"]}') # shortcut -> [action type, field, field, ...]+VIEWS = "/app/output/views"+BASE = os.environ.get("SIM_URL", "http://sim:8000") + "/" + os.environ.get("SEAT", "A")+++def call(ep, body=None):+ req = urllib.request.Request(BASE + "/" + ep, data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=600) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ try:+ out = json.load(e)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+++def save(b64, name):+ os.makedirs(VIEWS, exist_ok=True)+ fd, p = tempfile.mkstemp(dir=VIEWS, prefix=name + "_", suffix=".png")+ with os.fdopen(fd, "wb") as f:+ f.write(base64.b64decode(b64))+ return p+++def show(o):+ ob = o.get("observation")+ if isinstance(ob, dict) and ob.get("image_png_b64"):+ ob["image_file"] = save(ob.pop("image_png_b64"), "reply" if ob.get("of") else "obs")+ for k in [k for k in o if k.endswith("_image_b64")]:+ if o[k]:+ o[k[:-4] + "_file"] = save(o.pop(k), k[:-10])+ else:+ o.pop(k)+ print(json.dumps(o, indent=1))+++def arg(name, x):+ """A shortcut's argument as the act body carries it: `entity` as written (an id), true / false as booleans, a+ number as a number, anything else (an enum value) as written; the core checks every field against the schema."""+ if name == "entity":+ return x+ if x in ("true", "false"):+ return x == "true"+ try:+ return float(x)+ except ValueError:+ return x+++def main(a):+ turn = call("spec").get("protocol", "").startswith("eai-standard-turn") if a[:1] == ["wait"] else None+ if a == ["spec"]:+ show(call("spec"))+ elif a == ["status"]:+ show(call("status"))+ elif a == ["start"]:+ show(call("start", {}))+ elif a[:1] == ["wait"] and len(a) <= 2:+ if turn:+ while True:+ o = call("wait", {"timeout_s": 60})+ st = o.get("state") or {}+ if "error" in o or st.get("done") or st.get("your_turn"):+ break+ show(o)+ else:+ show(call("wait", {"dt": float(a[1]) if len(a) == 2 else 0.1}))+ elif a[:1] == ["observe"] and len(a) <= 2:+ show(call("observe", {"query": json.loads(a[1])} if len(a) == 2 else {}))+ elif a[:1] == ["act"] and len(a) == 2:+ show(call("act", json.loads(a[1])))+ elif a[:1] == ["ready"] and len(a) == 3:+ show(call("ready", {"why": a[1], "plan": a[2]}))+ elif a[:1] == ["say"] and len(a) == 2:+ show(call("say", {"text": a[1]}))+ elif a[:1] == ["team"] and len(a) <= 2:+ show(call("team", {"since": int(a[1]) if len(a) == 2 else 0}))+ elif a and a[0] in COMMANDS and len(a) == len(COMMANDS[a[0]]):+ kind, *names = COMMANDS[a[0]]+ show(call("act", {"type": kind, **{n: arg(n, x) for n, x in zip(names, a[1:])}}))+ else:+ sys.exit(__doc__)+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/limits.json b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/limits.jsonnew file mode 100644index 0000000000..8bc7217428--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/limits.json@@ -0,0 +1,39 @@+{+ "agent_timeout_sec": 7200,+ "caps": {+ "main": {+ "cpus": 2.0,+ "memory_gb": 6.0,+ "pids": 8192+ },+ "sim": {+ "cpus": 4.0,+ "memory_gb": 8.0,+ "pids": 256+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": false,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 0.0,+ "max_memory_gb": 4.0,+ "max_processes": 512,+ "mode": "standard",+ "scope": "agent",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "roboolympics-fencing-bout-i01-standard",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 0.0,+ "trial_max_memory_gb": 12.0,+ "window_sec": 120.0+}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/monitor.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/monitor.pynew file mode 100644index 0000000000..e87516ba84--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/monitor.py@@ -0,0 +1,1127 @@+#!/usr/bin/env python3+"""rcb_monitor: the trusted resource-limits monitor sidecar of every task (docs/PROTOCOL.md §2.10, record rcb-monitor/1).++Runs as the compose service `rcb_monitor` (generated by scripts/rcb_monitor/inject.py): `pid: host`, `cgroup: host`,+`network_mode: none`, CAP_SYS_PTRACE, the task's GPU reservation, its code read-only from the task directory. The agent+cannot see it (another PID namespace), reach it (no network) or write its record (its own file system).++Which containers it watches: the services that mount the trial's beacon volume `rcb_limits` (read-only at+/run/rcb-limits) are in scope, the ones that mount `rcb_observe` are only recorded (the benchmark's own services: the+simulator sidecar of standard modes, RoboPaint's privileged `scorer`). The compose project names both volumes, so they are unique to the trial; the monitor finds the containers as+the mount namespaces whose /run/rcb-limits is the same directory as its own (docker compose exec'd processes included).+A namespace that does not show the beacon is asked again at every tick (a container that is still being set up has the+host's root until its pivot_root: "no" is never remembered); a "yes" is kept only while the process that proved it lives.+A process whose first thread has exited is found through a thread that lives; a zombie counts in its parent's container.++Every tick (5 s; disk every 60 s) it samples, per container and summed over the scope: GPU memory (NVML, per process,+compute and graphics), memory (cgroup anon+shmem when the container has its own cgroup, else PSS anon+shmem), processes+(TGIDs, zombies included), disk growth under the limits' disk_paths in the agent's container (complete walks only, in+slices between the samples), CPU (recorded only). It appends to /var/rcb-monitor/samples.jsonl and+events.jsonl and writes the agent-visible /run/rcb-limits/usage.json: the current values, the limits and the agent's+clock (`elapsed_s`, `time_left_s`, `deadline_utc`: the task's `[agent] timeout_sec`, counted from the monitor's start,+which is the trial environment's start, a little before the agent's session starts, so it never overstates the time left).++The agent-side session log (robot_coding_bench #233): the privileged tooling writes /app/output/rcb_session_log.jsonl+from the agent's own process, so the agent can delete or rewrite it. Every tick the monitor copies what was appended to+it, append-only, into its record (session_log/<segment>.jsonl; a truncated, replaced or rewritten file starts a new+segment, a removed one keeps its copy; `session_log_rewritten` / `session_log_removed` events). The verifier step+(rcb_limits.sanitize, before the grader) gives the grader that copy when the agent's file is not what was written.++Kernel OOM kills (`oom` events) are read from each watched container's cgroup `memory.events` by a thread of its own+(OomWatch), many times a second: a kill that takes the container's main process with it ends the container, and compose+restarts it with a new cgroup whose counters start at 0, within milliseconds -- a reading once per tick never sees it.+Every event says whom it hit (`scope`: a container the limits bind, or a benchmark-owned service that is only+recorded) and why (`cause`): "cap" when the container's own `oom` counter rose with it (the kernel says its memory+reached its own cap), else "host" (the host's OOM killer, or an enclosing cgroup's: not this container's doing).+Only a "cap" kill in the scope is a violation (rcb_limits.violations); the verifier step reports the others.++RCB_LIMITS_ENFORCE=1 (run-time switch; compose default 0; 0/1/true/false, anything else is a fatal record): once a+violation is confirmed (rcb_limits.violations, the verifier's own rule) the monitor SIGKILLs every in-scope process+except each container's PID 1, so the agent stops at once and Harbor goes on to collection and the verifier (an agent+killed this way ends like one that exited non-zero). It also protects the host (`emergency_kill` events, never a+violation by themselves): above EMERGENCY_GPU_FACTOR x the GPU-memory limit at one sample it kills the scope's process+that holds the most GPU memory; where the runtime applies no kernel memory cap, it stands in for it and kills the+largest process once the scope is above its declared memory caps.+0: it only records.++ python3 monitor.py run # the service's command+ python3 monitor.py seal --wait 90 # the first sidecar collect hook: seal the record (summary.json), print it+ python3 monitor.py beacon # for a runner whose container runtime cannot run the monitor (no `pid: host`,+ # e.g. rootless podman without cgroups): the same service without pid/cgroup host,+ # writing only the agent's clock and `"measured": false` to usage.json+"""+import ctypes+import json+import os+import select+import signal+import stat as stat_mod+import sys+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import rcb_limits # noqa: E402+import selftest # noqa: E402++REC = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+PROC, CGROUP = "/proc", "/sys/fs/cgroup" # module globals: scripts/rcb_monitor/test_monitor.py points them at a fake tree+SCOPE_BEACON, OBSERVE_BEACON = "/run/rcb-limits", "/run/rcb-observe"+LIMITS = os.path.join(HERE, "limits.json")+HZ = os.sysconf("SC_CLK_TCK")+PAGE = os.sysconf("SC_PAGE_SIZE")+GIB = float(2 ** 30)+EMERGENCY_GPU_FACTOR = 1.5 # host protection (enforced runs): above this x the GPU-memory limit at one sample+DISK_SLICE_SEC = 1.5 # of every tick a running disk walk may take (the monitor's CPU cap is half a core)+DISK_WALK_MAX_SEC = 300.0 # a walk not finished by then is partial: a gap in the record, never a baseline+OOM_COLD_SEC = 0.02 # OomWatch: every memory.events is read this often (or at once, when the kernel notifies)+OOM_HOT_SEC = 0.002 # ... and this often for OOM_HOT_FOR_SEC after any of them changed (memory pressure)+OOM_HOT_FOR_SEC = 2.0+OOM_CAP_WINDOW_SEC = 10.0 # a kill is the container's own cap's when its `oom` counter rose with it or this shortly before+OOM_FORGET_SEC = 600.0 # a cgroup not seen by the sampler for this long is no longer watched+SESSION_LOG = "app/output/rcb_session_log.jsonl" # in the agent's container (rcb_limits.SESSION_LOG_NAME)+SESSION_LOG_MAX = 64 * 2 ** 20 # bytes copied at most (rcb_limits.MAX_SESSION_LOG: what a grader is given to read)+SESSION_LOG_TAIL = 4096 # bytes of the copied tail compared at every tick (a rewrite of what was copied)+++# --------------------------------------------------------------------------------------------------- small helpers+def now():+ return time.time()+++def rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def read(p):+ try:+ with open(p) as f:+ return f.read()+ except OSError:+ return None+++def stat_id(p):+ try:+ st = os.stat(p)+ return (st.st_dev, st.st_ino)+ except OSError:+ return None+++def stat_of(base):+ """(starttime, utime+stime) of the process or thread at /proc path `base`, or None."""+ s = read(base + "/stat")+ if not s:+ return None+ try:+ f = s.rsplit(")", 1)[1].split()+ return int(f[19]), int(f[11]) + int(f[12])+ except (IndexError, ValueError):+ return None+++def proc_stat(pid):+ return stat_of(f"{PROC}/{pid}")+++def status(pid):+ s = read(f"{PROC}/{pid}/status")+ if not s:+ return {}+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v.strip()+ return d+++def kb(v):+ try:+ return int((v or "0").split()[0])+ except (ValueError, IndexError):+ return 0+++def append(name, obj):+ with open(os.path.join(REC, name), "a") as f:+ f.write(json.dumps(obj, separators=(",", ":")) + "\n")+++def write_json(path, obj):+ tmp = path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f, indent=1)+ os.replace(tmp, path)+++def event(kind, **kw):+ kw.update(t=round(now(), 2), event=kind)+ append("events.jsonl", kw)+++def clock(t, start, timeout):+ """The agent's clock for usage.json (robot_coding_bench #231): seconds since `start` (the trial environment's start)+ and, with the task's time limit, the time left and the deadline. Counted from before the agent's session starts, so+ `time_left_s` is never more than the agent really has."""+ out = {"elapsed_s": round(max(0.0, t - start), 1)}+ if timeout:+ out.update(time_limit_s=int(timeout), time_left_s=round(max(0.0, start + timeout - t), 1),+ deadline_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(start + timeout)))+ return out+++def usage_limits(lim):+ return {k: lim.get(k) for k in ("max_gpu_memory_gb", "max_memory_gb", "max_processes", "max_disk_gb", "sustain_sec",+ "window_sec")}+++def open_in_root(root, rel):+ """A read-only fd of the regular file `rel` under the directory `root` (a container's /proc/<pid>/root), never+ through a symbolic link (an absolute link would resolve in the monitor's own file system), or None."""+ fd = None+ try:+ fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY)+ parts = rel.split("/")+ for part in parts[:-1]:+ nfd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)+ os.close(fd)+ fd = nfd+ f = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd)+ if not stat_mod.S_ISREG(os.fstat(f).st_mode):+ os.close(f)+ return None+ return f+ except OSError:+ return None+ finally:+ if fd is not None:+ os.close(fd)+++class SessionLogCopy:+ """Append-only copy of the agent's session log into the record (#233). State (inode, offset, segment, tail hash)+ lives in the record's state.json, so a restarted monitor goes on where it was."""++ def __init__(self, state=None):+ self.s = dict(state or {"ino": None, "off": 0, "seg": 0, "tail": "", "copied": 0, "gone": False})++ def step(self, root):+ import hashlib+ fd = open_in_root(root, SESSION_LOG)+ if fd is None:+ if self.s["ino"] is not None and not self.s["gone"]:+ self.s["gone"] = True+ event("session_log_removed", copied=self.s["copied"], segment=self.s["seg"])+ return+ try:+ st = os.fstat(fd)+ s = self.s++ def tail_of(end):+ os.lseek(fd, max(0, end - SESSION_LOG_TAIL), 0)+ return hashlib.sha256(os.read(fd, min(SESSION_LOG_TAIL, end))).hexdigest()++ if s["ino"] is not None and (st.st_ino != s["ino"] or st.st_size < s["off"] or s["gone"]+ or (s["off"] and tail_of(s["off"]) != s["tail"])):+ event("session_log_rewritten", copied=s["off"], size=st.st_size, segment=s["seg"] + 1,+ why="replaced" if st.st_ino != s["ino"] else "truncated" if st.st_size < s["off"] else+ "back after removal" if s["gone"] else "rewritten")+ s.update(off=0, seg=s["seg"] + 1, tail="")+ s.update(ino=st.st_ino, gone=False)+ n = min(st.st_size - s["off"], SESSION_LOG_MAX - s["copied"])+ if n <= 0:+ return+ os.lseek(fd, s["off"], 0)+ data = b""+ while len(data) < n:+ chunk = os.read(fd, n - len(data))+ if not chunk:+ break+ data += chunk+ d = os.path.join(REC, "session_log")+ os.makedirs(d, exist_ok=True)+ with open(os.path.join(d, "%d.jsonl" % s["seg"]), "ab") as out:+ out.write(data)+ s["off"] += len(data)+ s["copied"] += len(data)+ s["tail"] = tail_of(s["off"])+ finally:+ os.close(fd)+++def no_dump():+ """Not dumpable: without CAP_SYS_PTRACE nobody (not even the same uid) can open /proc/<monitor>/{root,mem,fd}."""+ try:+ ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLE = 4+ except Exception:+ pass+++# --------------------------------------------------------------------------------------------------- NVML+class Nvml:+ """Per-process GPU memory (host PIDs: the monitor runs in the host PID namespace) and per-card use, via libnvidia-ml+ (ctypes; no nvidia-smi child processes)."""++ class Proc(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong),+ ("gpuInstanceId", ctypes.c_uint), ("computeInstanceId", ctypes.c_uint)]++ class Proc1(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong)]++ class Mem(ctypes.Structure):+ _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]++ def __init__(self):+ self.lib = ctypes.CDLL("libnvidia-ml.so.1")+ if self.lib.nvmlInit_v2() != 0:+ raise RuntimeError("nvmlInit failed")+ n = ctypes.c_uint(0)+ self.lib.nvmlDeviceGetCount_v2(ctypes.byref(n))+ self.handles = []+ for i in range(n.value):+ h = ctypes.c_void_p()+ if self.lib.nvmlDeviceGetHandleByIndex_v2(i, ctypes.byref(h)) == 0:+ self.handles.append(h)+ self.fns = []+ for name, st in (("nvmlDeviceGetComputeRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses", self.Proc1),+ ("nvmlDeviceGetGraphicsRunningProcesses", self.Proc1)):+ kind = "compute" if "Compute" in name else "graphics"+ if any(k == kind for k, _, _ in self.fns):+ continue+ try:+ self.fns.append((kind, getattr(self.lib, name), st))+ except AttributeError:+ pass++ def sample(self):+ """({host pid: MiB}, {card index: (used MiB, total MiB)}, {host pids whose memory NVML does not tell})."""+ per, cards, unknown = {}, {}, set()+ for i, h in enumerate(self.handles):+ m = self.Mem()+ if self.lib.nvmlDeviceGetMemoryInfo(h, ctypes.byref(m)) == 0:+ cards[i] = (m.used // 2 ** 20, m.total // 2 ** 20)+ seen = {}+ for _kind, fn, st in self.fns:+ cnt = ctypes.c_uint(0)+ rc = fn(h, ctypes.byref(cnt), None)+ if rc not in (0, 7): # 7 = NVML_ERROR_INSUFFICIENT_SIZE: cnt now holds the count+ continue+ cnt = ctypes.c_uint(cnt.value + 16)+ arr = (st * cnt.value)()+ if fn(h, ctypes.byref(cnt), arr) != 0:+ continue+ for k in range(cnt.value):+ mem = arr[k].usedGpuMemory+ if mem >= 2 ** 63: # NVML_VALUE_NOT_AVAILABLE (MIG / vGPU / WSL): not a zero+ unknown.add(arr[k].pid)+ mib = 0+ else:+ mib = mem // 2 ** 20+ seen[arr[k].pid] = max(seen.get(arr[k].pid, 0), mib) # a C+G process is in both lists+ for p, v in seen.items():+ per[p] = per.get(p, 0) + v+ return per, cards, unknown+++# --------------------------------------------------------------------------------------------------- disk+class DiskWalk:+ """One measurement of the files under `paths` below `root` (the agent container's root, seen through /proc): the+ sum of st_blocks, every hard-linked file once, never descending into another mount (a directory on another device;+ files are not asked for theirs: on an overlay root whose layers sit on different file systems they report their+ layer's), `exclude` skipped. It runs in+ slices (step) between the monitor's samples, so a large tree delays no sample. `done` only when every directory was+ read: only then is `bytes` a measurement; before that it is a lower bound."""++ def __init__(self, root, paths, exclude):+ self.root, self.t0 = root, now()+ self.bytes = self.entries = 0+ self.done, self.why = False, None+ self._it = self._walk(list(paths), {root + x.rstrip("/") for x in exclude})++ def _walk(self, paths, excl):+ linked = set() # (dev, ino) of files with several names: counted once+ for base in paths:+ top = self.root + base+ try:+ dev = os.lstat(top).st_dev+ except FileNotFoundError:+ continue # the path does not exist in this container: nothing under it+ except OSError as e:+ self.why = f"{base}: {type(e).__name__}"+ return+ stack = [top]+ while stack:+ d = stack.pop()+ try:+ it = os.scandir(d)+ except FileNotFoundError:+ continue # removed since its parent was read+ except OSError as e:+ self.why = f"{d[len(self.root):]}: {type(e).__name__}"+ return+ with it:+ for e in it:+ try:+ st = e.stat(follow_symlinks=False)+ except OSError:+ continue # removed meanwhile+ if stat_mod.S_ISDIR(st.st_mode):+ if st.st_dev != dev or e.path in excl:+ continue # another mount (never crossed: not the container's own files)+ stack.append(e.path)+ elif st.st_nlink > 1:+ k = (st.st_dev, st.st_ino)+ if k in linked:+ continue+ linked.add(k)+ self.bytes += st.st_blocks * 512+ self.entries += 1+ if self.entries % 256 == 0:+ yield+ yield+ self.done = True++ def step(self, budget_sec):+ """Walk on for at most `budget_sec`; True when the walk has ended (done, or failed with `why`)."""+ end = now() + budget_sec+ for _ in self._it:+ if now() >= end:+ return False+ return True+++# --------------------------------------------------------------------------------------------------- OOM kills+class OomWatch:+ """Kernel OOM kills of the watched containers, from each one's cgroup v2 `memory.events`:+ oom times the cgroup's memory reached its own limit (memory.max) and an allocation was about to fail+ oom_kill processes of the cgroup killed by any OOM killer (its own limit's, an enclosing cgroup's, the host's)+ A kill whose `oom` counter rose with it (or within OOM_CAP_WINDOW_SEC before) happened at the container's own cap+ (`cause: "cap"`); one without is the host's or an enclosing cgroup's OOM killer (`cause: "host"`), which the+ container did not cause by its own use (PROTOCOL §2.10: nothing another trial does can fail a trial).++ The counters live and die with the cgroup, and a container whose main process is killed is gone (and restarted by+ compose with fresh counters) within milliseconds. So the files are read by this object's own thread, every+ OOM_COLD_SEC, at once when the kernel signals a change (poll: memory.events notifies), and every OOM_HOT_SEC for a+ while after any change (the `max` counter rises under memory pressure, before a kill). A kill that removes the+ cgroup within about a millisecond can still be missed: such a kill is then in no record.++ scan() reads every file once; the sampler calls it at each tick when the thread does not run (the tests). The+ thread ends when the record is sealed."""++ def __init__(self):+ self.lock = threading.Lock()+ self.w = {} # cgroup dir -> {"role", "scope", "fd", "kill", "oom", "sig", "cap_t", "seen"}+ self.hot_until = 0.0+ self.thread = None+ self.stopped = False # set at the seal: the record is closed, like the samples++ def watch(self, cg, role, scope, t):+ """The sampler saw this container's cgroup at time t."""+ with self.lock:+ e = self.w.get(cg)+ if e is None:+ e = self.w[cg] = {"fd": None, "kill": None, "oom": None, "sig": None, "cap_t": None}+ e.update(role=role, scope=bool(scope), seen=t)++ @staticmethod+ def _close(e):+ if e["fd"] is not None:+ try:+ os.close(e["fd"])+ except OSError:+ pass+ e["fd"] = None++ def _read(self, cg, e):+ """The counters of the cgroup's memory.events ({} when the file cannot be read: the container is not up).+ A file that stops answering belonged to a cgroup that is gone; the same path opened again is a new cgroup (the+ container restarted: another directory, by its inode and creation time), whose counters all belong to the+ trial: they are compared with 0. The same cgroup opened again keeps what was already counted."""+ for _ in (0, 1):+ try:+ if e["fd"] is None:+ e["fd"] = os.open(cg + "/memory.events", os.O_RDONLY)+ st = os.stat(cg)+ ident = (st.st_dev, st.st_ino, st.st_ctime_ns)+ if e["sig"] is not None and ident != e.get("ident"):+ e["kill"] = e["oom"] = 0 # read before, gone, here again: another instance of the cgroup+ e["ident"] = ident+ os.lseek(e["fd"], 0, os.SEEK_SET)+ out = {}+ for line in os.read(e["fd"], 8192).decode("ascii", "replace").splitlines():+ k, _, v = line.partition(" ")+ if v.strip().isdigit():+ out[k] = int(v)+ return out+ except OSError:+ self._close(e)+ return {}++ def scan(self):+ """Read every watched file once and record the kills since the last reading. True when a counter changed."""+ changed = False+ with self.lock:+ t = now()+ for cg, e in list(self.w.items()):+ if t - e["seen"] > OOM_FORGET_SEC:+ self._close(e)+ del self.w[cg]+ continue+ c = self._read(cg, e)+ if "oom_kill" not in c:+ continue+ kill, oom = c["oom_kill"], c.get("oom", 0)+ sig = (kill, oom, c.get("max", 0))+ if e["kill"] is None or kill < e["kill"] or oom < e["oom"]:+ # the first reading is the baseline; counters that went back are a new cgroup under the same path+ e["kill"], e["oom"] = (kill, oom) if e["kill"] is None else (0, 0)+ changed |= sig != e["sig"]+ if oom > e["oom"]:+ e["cap_t"] = t+ if kill > e["kill"]:+ at_cap = e["cap_t"] is not None and t - e["cap_t"] <= OOM_CAP_WINDOW_SEC+ kw = {"role": e["role"], "scope": e["scope"], "count": kill - e["kill"],+ "cause": "cap" if at_cap else "host", "cap_hits": oom - e["oom"]}+ for name, key in (("memory.max", "memory_cap_gb"), ("memory.current", "memory_current_gb")):+ v = (read(cg + "/" + name) or "").strip() # evidence only: the cause is the counters'+ if v.isdigit():+ kw[key] = round(int(v) / GIB, 3)+ event("oom", **kw)+ e["kill"], e["oom"], e["sig"] = kill, oom, sig+ return changed++ def start(self):+ self.thread = threading.Thread(target=self._loop, name="rcb-oom-watch", daemon=True)+ self.thread.start()++ def _loop(self):+ said = False+ while not self.stopped:+ try:+ if self.scan():+ self.hot_until = now() + OOM_HOT_FOR_SEC+ if now() < self.hot_until:+ time.sleep(OOM_HOT_SEC)+ continue+ with self.lock:+ fds = [e["fd"] for e in self.w.values() if e["fd"] is not None]+ if not fds:+ time.sleep(OOM_COLD_SEC)+ continue+ p = select.poll() # memory.events notifies its readers (POLLPRI) when it changes+ for fd in fds:+ p.register(fd, select.POLLPRI | select.POLLERR)+ if p.poll(OOM_COLD_SEC * 1000):+ self.hot_until = now() + OOM_HOT_FOR_SEC+ except Exception as e: # never stop watching+ if not said:+ said = True+ try:+ event("error", why=f"oom watch: {type(e).__name__}: {e}"[:300])+ except Exception:+ pass+ time.sleep(OOM_COLD_SEC)+++# --------------------------------------------------------------------------------------------------- the monitor+class Monitor:+ def __init__(self):+ self.lim = rcb_limits.read_json(LIMITS) or {}+ self.tick = float(self.lim.get("tick_sec", 5))+ self.disk_tick = float(self.lim.get("disk_tick_sec", 60))+ self.enforce, self.switch_error = rcb_limits.parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ self.me_mnt = rl(f"{PROC}/self/ns/mnt")+ self.beacon = {"scope": stat_id(SCOPE_BEACON), "observe": stat_id(OBSERVE_BEACON)}+ self.cls = {} # mnt ns -> {"kind", "role", "witness": (proc path, starttime)}: only what IS watched+ self.neg, self.ok = set(), set() # this tick: namespaces that said no / whose witness still lives+ self.via = {} # pid -> /proc path of a living thread, for a process whose first thread has exited+ self.prev_cpu = {} # pid -> (starttime, ticks, t)+ self.oomw = OomWatch() # kernel OOM kills of the watched containers (its own thread in run())+ self.disk_base = None # GiB under disk_paths at the first complete walk (kept in state.json across restarts)+ self.disk_last = 0.0+ self.disk_gb = None+ self.walk = None # (DiskWalk, mnt ns, proc path, starttime) of the measurement under way+ self.slog = SessionLogCopy()+ self.series = [] # [(t, {metric: value})] of the last window, for enforcement decisions+ self.confirmed = {} # metric -> time+ self.kill_until = 0.0+ self.killed = 0+ self.emergency = [] # the emergency_kill events of this run+ self.scope_seen = False+ self.gpu_unknown = False+ self.caps = selftest.capabilities()+ self.nvml = None+ try:+ self.nvml = Nvml()+ except Exception as e:+ self.caps["nvml_error"] = f"{type(e).__name__}: {e}"[:200]+ self.caps["nvml"] = int(self.nvml is not None)+ self.caps["nvml_devices"] = len(self.nvml.handles) if self.nvml else 0+ self.t0 = now()+ self.clock_t0 = self.t0 # the agent's clock (usage.json): the first start's, across restarts (run())+ self.timeout = float(self.lim.get("agent_timeout_sec") or 0)+ self._usage_vals = None+ self._last_measures, self._gpu_per = [], {}+ self.fatal_scope = False++ # ---- scope discovery+ def base(self, pid):+ """The /proc path to read a process's namespaces, root and memory from."""+ return self.via.get(pid) or f"{PROC}/{pid}"++ def classify(self, mnt, base):+ """{"kind": "scope" | "observe", "role": "main" | "sidecar"} when the mount namespace `mnt` (of the process or+ thread at /proc path `base`) is one of the trial's containers, else None.++ "No" is never remembered beyond this tick: while a container is set up, its init process is already in a new+ mount namespace but still has the host's root, and the beacon appears only with its pivot_root. "Yes" is+ remembered while the process that proved it lives in the namespace (the kernel may give the number of a+ namespace that ended to a new one)."""+ if mnt in self.ok:+ return self.cls[mnt]+ if mnt in self.neg:+ return None+ c = self.cls.get(mnt)+ if c is not None:+ wbase, wstart = c["witness"]+ ws = stat_of(wbase)+ if ws and ws[0] == wstart and rl(wbase + "/ns/mnt") == mnt:+ self.ok.add(mnt)+ return c+ del self.cls[mnt]+ root = base + "/root"+ kind = None+ if self.beacon["scope"] and stat_id(root + SCOPE_BEACON) == self.beacon["scope"]:+ kind = "scope"+ elif self.beacon["observe"] and stat_id(root + OBSERVE_BEACON) == self.beacon["observe"]:+ kind = "observe"+ st = stat_of(base)+ here = st is not None and rl(base + "/ns/mnt") == mnt # a vanished process tells nothing: ask the next+ if kind and here:+ c = {"kind": kind, "role": "main" if os.path.isdir(root + "/logs/agent") else "sidecar",+ "witness": (base, st[0])}+ self.cls[mnt] = c+ self.ok.add(mnt)+ return c+ if here:+ self.neg.add(mnt)+ return None++ def live_thread(self, pid):+ """/proc path of a thread of `pid` that still runs (its first thread has exited: /proc/<pid>/ns is empty)."""+ try:+ tids = os.listdir(f"{PROC}/{pid}/task")+ except OSError:+ return None+ for tid in tids:+ b = f"{PROC}/{pid}/task/{tid}"+ if tid != str(pid) and rl(b + "/ns/mnt"):+ return b+ return None++ def groups(self):+ """{mnt ns: {"kind", "role", "pids": [...], "zombies": n}} of the watched containers."""+ self.neg, self.ok, self.via = set(), set(), {}+ out, where, lost = {}, {}, []+ try:+ names = os.listdir(PROC)+ except OSError:+ names = []+ for d in names:+ if not d.isdigit():+ continue+ pid = int(d)+ mnt = rl(f"{PROC}/{pid}/ns/mnt")+ if mnt is None:+ lost.append(pid)+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, f"{PROC}/{pid}")+ if c:+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ zombies = []+ for pid in lost:+ b = self.live_thread(pid)+ if not b:+ zombies.append(pid)+ continue+ mnt = rl(b + "/ns/mnt") # its first thread exited, the others run on: a process like any other+ if mnt is None:+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, b)+ if c:+ self.via[pid] = b+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ for pid in zombies:+ st = status(pid)+ if st.get("State", "").startswith("Z"): # a zombie holds a PID until its parent reaps it: counted there+ try:+ g = out.get(where.get(int(st.get("PPid", "0"))))+ except ValueError:+ g = None+ if g:+ g["zombies"] += 1+ self.cls = {m: c for m, c in self.cls.items() if m in self.ok}+ return out++ # ---- per-container measurements+ def cgroup_of(self, pids):+ """The container's own cgroup v2 directory (under the host tree, `cgroup: host`) when every process in it is this+ container's (rootless podman without cgroup delegation leaves containers in a shared one), else None."""+ paths = set()+ for p in pids[:8]:+ s = read(f"{PROC}/{p}/cgroup") or ""+ for line in s.splitlines():+ if line.startswith("0::"):+ paths.add(line[3:].strip())+ if len(paths) != 1:+ return None+ d = CGROUP + paths.pop()+ procs = read(d + "/cgroup.procs")+ if procs is None:+ return None+ members = {int(x) for x in procs.split() if x.isdigit()}+ return d if members and members <= set(pids) else None++ def mem_pss(self, pids):+ tot = 0+ for p in pids:+ s = read(self.base(p) + "/smaps_rollup")+ if s is None:+ st = status(p)+ tot += kb(st.get("RssAnon")) + kb(st.get("RssShmem"))+ continue+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v+ tot += (kb(d.get("Pss_Anon")) + kb(d.get("Pss_Shmem"))) if "Pss_Anon" in d else kb(d.get("Pss"))+ return tot / 1024.0 / 1024.0 # GiB++ def measure(self, g, gpu_per, t, gpu_unknown=()):+ pids = g["pids"]+ threads = cpu = 0.0+ for p in pids:+ threads += int(status(p).get("Threads", "0") or 0)+ ps = proc_stat(p)+ if ps:+ pv = self.prev_cpu.get(p)+ if pv and pv[0] == ps[0] and t > pv[2]:+ cpu += max(0, ps[1] - pv[1]) / HZ / (t - pv[2])+ self.prev_cpu[p] = (ps[0], ps[1], t)+ cg = self.cgroup_of(pids)+ m = {"kind": g["kind"], "role": g["role"], "processes": len(pids) + g.get("zombies", 0),+ "zombies": g.get("zombies", 0), "threads": int(threads), "cpu": round(cpu, 2),+ "gpu_memory_gb": round(sum(gpu_per.get(p, 0) for p in pids) / 1024.0, 3), "cgroup": int(cg is not None)}+ unknown = sum(1 for p in pids if p in gpu_unknown)+ if unknown:+ m["gpu_unmeasured"] = unknown # processes on the GPU whose memory NVML does not tell+ if cg:+ st = {}+ for line in (read(cg + "/memory.stat") or "").splitlines():+ k, _, v = line.partition(" ")+ st[k] = v+ try:+ m["memory_gb"] = round((int(st.get("anon", 0)) + int(st.get("shmem", 0))) / GIB, 3)+ except ValueError:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ mx = (read(cg + "/memory.max") or "").strip()+ m["memory_cap_gb"] = None if mx in ("", "max") else round(int(mx) / GIB, 2)+ self.oomw.watch(cg, g["role"], g["kind"] == "scope", now())+ else:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ return m++ # ---- disk+ def main_proc(self, groups):+ """(mnt ns, pid) to reach the agent container's files through: its PID 1 when visible (it outlives the others)."""+ for mnt, g in groups.items():+ if g["kind"] == "scope" and g["role"] == "main" and g["pids"]:+ init = [p for p in g["pids"] if (status(p).get("NSpid") or "").split()[-1:] == ["1"]]+ return mnt, (init[0] if init else min(g["pids"]))+ return None, None++ def disk_step(self, t, groups):+ """The disk value of this sample: GiB the files under disk_paths grew since the baseline, or None (not measured+ at this tick). Only a complete walk of a container that is still there is a measurement; only such a walk sets+ the baseline. A walk that did not finish is a lower bound: it can show that the limit is exceeded, never that it+ is not, and it never becomes the baseline."""+ if self.walk is None:+ mnt, pid = self.main_proc(groups)+ if pid is None or t - self.disk_last < self.disk_tick:+ return None+ b = self.base(pid)+ st = stat_of(b)+ if st is None:+ return None+ self.disk_last = t+ self.walk = (DiskWalk(b + "/root", self.lim.get("disk_paths") or ["/app"], self.lim.get("disk_exclude") or []),+ mnt, b, st[0])+ w, mnt, b, start = self.walk+ ended = w.step(DISK_SLICE_SEC)+ if not ended and now() - w.t0 <= DISK_WALK_MAX_SEC:+ return None # goes on at the next tick+ self.walk = None+ st = stat_of(b)+ there = st is not None and st[0] == start and rl(b + "/ns/mnt") == mnt # the same container, still up+ gb = w.bytes / GIB+ if ended and w.done and there:+ if self.disk_base is None:+ self.disk_base = gb+ self.save_state()+ event("disk_baseline", gb=round(gb, 3), entries=w.entries)+ self.disk_gb = round(max(0.0, gb - self.disk_base), 3)+ return self.disk_gb+ why = "the container's process ended during the walk" if not there else (w.why or "not finished in time")+ event("disk_partial", why=why, gb=round(gb, 3), entries=w.entries, sec=round(now() - w.t0, 1))+ lim = float(self.lim.get("max_disk_gb") or 0)+ if there and self.disk_base is not None and lim and gb - self.disk_base > lim:+ self.disk_gb = round(gb - self.disk_base, 3) # already over the limit, whatever the rest holds+ return self.disk_gb+ return None++ # ---- state that must outlive a restart of the monitor (restart: on-failure)+ def save_state(self):+ try:+ write_json(os.path.join(REC, "state.json"), {"disk_base": self.disk_base, "session_log": self.slog.s})+ except OSError:+ pass++ def restore(self):+ """After a restart: the disk baseline, the confirmed violations and the last window of samples come back from+ the record, so that a crash neither resets the baseline nor forgets time already spent over a limit."""+ st = rcb_limits.read_json(os.path.join(REC, "state.json")) or {}+ if isinstance(st.get("disk_base"), (int, float)):+ self.disk_base = float(st["disk_base"])+ if isinstance(st.get("session_log"), dict):+ self.slog = SessionLogCopy(st["session_log"])+ _, samples, events = rcb_limits.load_record(REC)+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [(s["t"], s.get("scope") or {}) for s in samples+ if isinstance(s.get("t"), (int, float)) and s["t"] >= self.t0 - window - 3 * self.tick]+ for e in events:+ k = e.get("event")+ if k == "violation" and e.get("metric"):+ self.confirmed.setdefault(e["metric"], e.get("t") or self.t0)+ elif k in ("kill", "emergency_kill"):+ self.killed += int(e.get("processes") or 0)+ if k == "emergency_kill":+ self.emergency.append(e)+ elif k == "scope_found":+ self.scope_seen = True+ if self.enforce and self.confirmed and self.t0 - max(self.confirmed.values()) < 60:+ self.kill_until = max(self.confirmed.values()) + 60++ # ---- enforcement+ @staticmethod+ def spared(pids):+ """The container's own processes that must outlive a kill: its PID 1 and what PID 1 started with it (Harbor's+ `sh -c "sleep infinity"` keepalive). Agent processes are exec'd into the container (their parent is outside+ it) or, when orphaned, adopted by PID 1 later: those are never spared."""+ st = {p: status(p) for p in pids}+ init = [p for p in pids if (st[p].get("NSpid") or "").split()[-1:] == ["1"]]+ if not init:+ return set()+ t1 = (proc_stat(init[0]) or (0, 0))[0]+ keep = set(init)+ for p in pids:+ ns_ppid = None+ ns = (st[p].get("NSpid") or "").split()+ if ns and st[p].get("PPid") is not None:+ # PPid in /proc/<pid>/status is in the reader's namespace (host); compare with PID 1's host PID+ ns_ppid = int(st[p]["PPid"])+ ps = proc_stat(p)+ if ns_ppid == init[0] and ps and ps[0] - t1 <= 2 * HZ: # started with the container, not adopted later+ keep.add(p)+ return keep++ def kill_scope(self, groups, why):+ n = 0+ for mnt, g in groups.items():+ if g["kind"] != "scope":+ continue+ snap = {p: proc_stat(p) for p in g["pids"]}+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue # PID 1 and its keepalive: the container stays up for collection+ if rl(self.base(p) + "/ns/mnt") != mnt or not snap[p] or proc_stat(p) is None \+ or proc_stat(p)[0] != snap[p][0]:+ continue # gone, or its PID now names another process+ try:+ os.kill(p, signal.SIGKILL)+ n += 1+ except OSError:+ pass+ if n:+ self.killed += n+ event("kill", why=why, processes=n)+ return n++ def scope_memory_cap(self):+ """GiB: the declared memory caps of the services the limits bind, summed (None: not declared)."""+ caps = self.lim.get("caps") or {}+ names = self.lim.get("scope_services") or (+ [n for n in caps if n != "*"] if self.lim.get("scope") == "trial" else ["main"])+ vals = [float(caps[n]["memory_gb"]) for n in names if isinstance(caps.get(n), dict) and caps[n].get("memory_gb")]+ return sum(vals) if vals else None++ def check(self, t, scope_vals, groups):+ self.series.append((t, scope_vals))+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [x for x in self.series if x[0] >= t - window - 3 * self.tick]+ samples = [{"t": a, "scope": b} for a, b in self.series]+ for v in rcb_limits.violations(samples, self.lim):+ if v["metric"] not in self.confirmed:+ self.confirmed[v["metric"]] = t+ event("violation", **v)+ if self.enforce:+ self.kill_until = t + 60+ if self.enforce and t <= self.kill_until:+ self.kill_scope(groups, ",".join(sorted(self.confirmed)))+ # Host protection (enforced runs only; PROTOCOL §2.10). An emergency kill is never a violation by itself: the+ # trial fails only by the sustained rule above or a kernel OOM kill at its own memory cap. Both conditions are+ # the trial's own doing (its scope's use against its own limit or caps), never the state of a card or host it+ # shares with other trials.+ if self.enforce:+ cap = self.scope_memory_cap()+ lim_gpu = float(self.lim.get("max_gpu_memory_gb") or 0)+ if cap and scope_vals["memory_gb"] > cap and not any(+ m.get("memory_cap_gb") for m in self._last_measures if m["kind"] == "scope"):+ # no kernel memory cap holds here (e.g. rootless podman without cgroups): stand in for it+ self._emergency(groups, "memory", cap, scope_vals["memory_gb"], key="mem")+ if lim_gpu and scope_vals["gpu_memory_gb"] > EMERGENCY_GPU_FACTOR * lim_gpu:+ self._emergency(groups, "gpu_memory", lim_gpu, scope_vals["gpu_memory_gb"], key="gpu")++ def _emergency(self, groups, why, limit, observed, key):+ best, bv = None, 0 # only a process that holds some: never one with none of it+ for g in groups.values():+ if g["kind"] != "scope":+ continue+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue+ v = self._gpu_per.get(p, 0) if key == "gpu" else self.rss_kb(p)+ if v > bv:+ best, bv = p, v+ if best:+ try:+ os.kill(best, signal.SIGKILL)+ self.killed += 1+ e = {"why": why, "limit": limit, "observed": round(observed, 3), "processes": 1}+ event("emergency_kill", **e)+ self.emergency.append(dict(e, t=round(now(), 2)))+ except OSError:+ pass++ def rss_kb(self, p):+ v = kb(status(p).get("VmRSS"))+ if not v and p in self.via: # the first thread has exited: its status has no memory lines+ for line in (read(self.via[p] + "/status") or "").splitlines():+ if line.startswith("VmRSS:"):+ v = kb(line.partition(":")[2])+ return v++ # ---- main loop+ def run(self):+ os.makedirs(REC, exist_ok=True)+ restarted = os.path.exists(os.path.join(REC, "meta.json"))+ meta = {"format": rcb_limits.FORMAT, "started": round(self.t0, 2), "enforce": self.enforce, "limits": self.lim,+ "capabilities": self.caps, "beacons": {k: bool(v) for k, v in self.beacon.items()}}+ if self.switch_error:+ meta["switch_error"] = self.switch_error+ if restarted:+ self.clock_t0 = (rcb_limits.read_json(os.path.join(REC, "meta.json")) or {}).get("started") or self.t0+ self.restore()+ event("restart", capabilities=self.caps)+ else:+ write_json(os.path.join(REC, "meta.json"), meta)+ event("start", enforce=self.enforce, capabilities=self.caps)+ if self.switch_error:+ event("fatal", why=self.switch_error + " (nothing is enforced; the trial is not a result)")+ if not self.beacon["scope"]:+ event("fatal", why="no scope beacon mounted at /run/rcb-limits")+ if self.lim.get("gpu") and not self.nvml:+ event("fatal", why="GPU task but NVML is unavailable: " + str(self.caps.get("nvml_error")))+ sys.setswitchinterval(0.001) # the OOM watch must get its turn within a millisecond+ self.oomw.start()+ while not os.path.exists(os.path.join(REC, "seal.request")):+ t = now()+ try:+ self.tick_once(t)+ except Exception as e: # a vanished process mid-read must never stop the record+ import traceback+ traceback.print_exc()+ event("error", why=f"{type(e).__name__}: {e}"[:300])+ self.write_usage(t) # every tick, a failed one too: the agent's clock never stops+ for p in list(self.prev_cpu):+ if t - self.prev_cpu[p][2] > 60:+ del self.prev_cpu[p]+ time.sleep(max(0.2, self.tick - (now() - t)))+ self.seal()+ while True: # stay up: Harbor copies the record after the hook+ time.sleep(3600)++ def tick_once(self, t):+ groups = self.groups()+ gpu_per, cards, gpu_unknown = self.nvml.sample() if self.nvml else ({}, {}, set())+ self._gpu_per = gpu_per+ ms = [self.measure(g, gpu_per, t, gpu_unknown) for g in groups.values()]+ self._last_measures = ms+ if self.oomw.thread is None:+ self.oomw.scan() # no thread (tests): read the OOM counters with the sample+ scope = [m for m in ms if m["kind"] == "scope"]+ if scope and not self.scope_seen:+ self.scope_seen = True+ event("scope_found", containers=len(scope), roles=sorted(m["role"] for m in scope))+ if not self.scope_seen and not self.fatal_scope and t - self.t0 > 120:+ self.fatal_scope = True+ event("fatal", why="no container mounting the trial's beacon found within 120 s")+ disk_now = self.disk_step(t, groups)+ _, pid = self.main_proc(groups)+ if pid is not None:+ before = dict(self.slog.s)+ self.slog.step(self.base(pid) + "/root")+ if self.slog.s != before:+ self.save_state()+ vals = {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in scope), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in scope), 3),+ "processes": sum(m["processes"] for m in scope), "disk_gb": disk_now}+ unknown = sum(m.get("gpu_unmeasured", 0) for m in scope)+ if unknown:+ vals["gpu_unmeasured"] = unknown+ if not self.gpu_unknown:+ self.gpu_unknown = True+ event("gpu_unmeasured", processes=unknown,+ why="NVML does not tell the GPU memory of processes in scope (MIG / vGPU?): counted as 0")+ obs = [m for m in ms if m["kind"] == "observe"]+ append("samples.jsonl", {"t": round(t, 2), "scope": vals,+ "observe": {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in obs), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in obs), 3),+ "processes": sum(m["processes"] for m in obs)},+ "cards": {str(k): v for k, v in cards.items()}, "containers": ms})+ self._usage_vals = vals+ self.check(t, vals, groups)++ def write_usage(self, t):+ """The agent-visible /run/rcb-limits/usage.json: the last sample's values (none before the first one), the+ limits, what enforcement did, and the agent's clock."""+ vals = self._usage_vals or {}+ u = {"t": round(t, 2), "measured": bool(vals)}+ u.update({k: vals.get(k) for k in ("gpu_memory_gb", "memory_gb", "processes")})+ u.update(disk_gb=self.disk_gb, enforced=self.enforce, limits=usage_limits(self.lim),+ violations=sorted(self.confirmed),+ # processes the monitor killed at once to protect the host (not violations by themselves)+ emergency_kills=len(self.emergency), last_emergency_kill=(self.emergency or [None])[-1])+ u.update(clock(t, self.clock_t0, self.timeout))+ try:+ write_json(SCOPE_BEACON + "/usage.json", u)+ except OSError:+ pass++ def seal(self):+ try:+ self.oomw.scan() # the counters once more, whatever the watch thread is doing+ except Exception:+ pass+ # The record ends here, for OOM kills as for the samples: what happens to a sidecar in the collect hooks that+ # follow (its replays) is the grader's to judge, from the hook's own evidence.+ self.oomw.stopped = True+ summary, samples, events = rcb_limits.load_record(REC)+ viol = rcb_limits.violations(samples, self.lim, events)+ meta = rcb_limits.read_json(os.path.join(REC, "meta.json")) or {}+ out = {+ "format": rcb_limits.FORMAT, "sealed": True, "enforce": meta.get("enforce", self.enforce),+ "started": meta.get("started"), "ended": round(now(), 2), "n_samples": len(samples),+ "scope_seen": self.scope_seen or any((s.get("scope") or {}).get("processes") for s in samples),+ "peaks": rcb_limits.peaks(samples), "violations": viol,+ "killed": sum(int(e.get("processes") or 0) for e in events if e.get("event") in ("kill", "emergency_kill")),+ "emergency_kills": sum(1 for e in events if e.get("event") == "emergency_kill"),+ "disk_baseline_gb": self.disk_base,+ "disk_partial_walks": sum(1 for e in events if e.get("event") == "disk_partial"),+ "restarts": sum(1 for e in events if e.get("event") == "restart"),+ "capabilities": meta.get("capabilities", self.caps), "limits": self.lim}+ if meta.get("switch_error") or self.switch_error:+ out["switch_error"] = meta.get("switch_error") or self.switch_error+ write_json(os.path.join(REC, "summary.json"), out)+ event("seal", violations=len(viol))+++def seal_cmd(wait):+ open(os.path.join(REC, "seal.request"), "a").close()+ path = os.path.join(REC, "summary.json")+ t_end = now() + wait+ while now() < t_end and not os.path.exists(path):+ time.sleep(0.5)+ s = rcb_limits.read_json(path)+ print(json.dumps({k: (s or {}).get(k) for k in ("sealed", "enforce", "n_samples", "peaks", "violations", "killed")}))+ return 0+++BEACON_WHY = ("this runner cannot run the resource monitor (its container runtime refuses `pid: host`): usage is not "+ "measured and the limits are not enforced; the clock is kept")+++def beacon(rounds=None):+ """`monitor.py beacon`: usage.json with the agent's clock and `"measured": false`, every tick, for a runner whose+ container runtime cannot create the monitor service (it rewrites the service to run this instead of `run`). The+ start is kept in the service's own /var/rcb-monitor/beacon.json, so a restart does not reset the clock."""+ lim = rcb_limits.read_json(LIMITS) or {}+ tick, timeout = float(lim.get("tick_sec", 5)), float(lim.get("agent_timeout_sec") or 0)+ start = now()+ try:+ os.makedirs(REC, exist_ok=True)+ st = rcb_limits.read_json(os.path.join(REC, "beacon.json")) or {}+ if isinstance(st.get("started"), (int, float)):+ start = float(st["started"])+ else:+ write_json(os.path.join(REC, "beacon.json"), {"started": round(start, 2)})+ except OSError:+ pass+ n = 0+ while rounds is None or n < rounds:+ t = now()+ u = {"t": round(t, 2), "measured": False, "why": BEACON_WHY, "enforced": 0, "limits": usage_limits(lim)}+ u.update(clock(t, start, timeout))+ try:+ write_json(SCOPE_BEACON + "/usage.json", u)+ except OSError:+ pass+ n += 1+ if rounds is None or n < rounds:+ time.sleep(tick)+ return 0+++def main(argv):+ if argv[:1] == ["beacon"]:+ return beacon()+ if argv[:1] == ["seal"]:+ wait = float(argv[argv.index("--wait") + 1]) if "--wait" in argv else 90.0+ return seal_cmd(wait)+ if argv[:1] in (["run"], []):+ no_dump()+ Monitor().run()+ return 0+ print(__doc__)+ return 2+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/rcb_limits.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/rcb_limits.pynew file mode 100644index 0000000000..3c996ca1f2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/rcb_limits.py@@ -0,0 +1,536 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The session log (robot_coding_bench #233): sanitize() also compares the agent's /app/output/rcb_session_log.jsonl with+the monitor's append-only copy of it (session_log/ in the record) and, when the agent's file is missing or is not what+was written (removed, truncated, rewritten), gives the grader the copy instead (session_log_source()); verify() adds+session_log_tampered (0/1) and session_log_from_monitor (0/1) to reward.json. Only the graders' cost fields read the log.++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ sl = read_json(os.path.join(log, SESSION_LOG_STATUS)) # sanitize()'s session-log comparison (#233)+ if isinstance(sl, dict):+ add["session_log_tampered"] = int(bool(sl.get("tampered")))+ add["session_log_from_monitor"] = int(bool(sl.get("from_monitor")))+ detail["session_log"] = sl+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ try:+ msg = session_log_source(log, max_log)+ if msg:+ done.append(msg)+ except Exception as e: # never keep the grader from running+ done.append(f"session log: not compared with the monitor's copy ({type(e).__name__}: {e})")+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++SESSION_LOG_STATUS = "session_log.json" # in /logs/verifier: what session_log_source() did, read back by verify()+++def session_log_source(log, max_log=MAX_SESSION_LOG, record=None):+ """The session log the grader reads (#233). The monitor copies what the agent's tooling appends to it, append-only,+ into its record (session_log/<segment>.jsonl; a new segment each time the file was truncated, replaced or+ rewritten). The agent's file stays when it is the copy plus at most what was appended after the last tick; else+ (removed, truncated, rewritten, or the copy has segments) the grader gets the copy: the segments' lines in order,+ in a later segment a line an earlier one already gave left out (a rewrite copies the file again). No copy (no monitor on the runner, or no log+ written): nothing changes, nothing is written. Else writes /logs/verifier/session_log.json; returns a line for the+ log, or None."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ d = os.path.join(record, "session_log")+ segs = sorted((int(n.split(".")[0]) for n in (os.listdir(d) if os.path.isdir(d) else ())+ if n.endswith(".jsonl") and n.split(".")[0].isdigit()))+ events = [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)]+ tamper = [e for e in events if e.get("event") in ("session_log_rewritten", "session_log_removed")]+ status = {"from_monitor": 0, "tampered": int(bool(tamper)), "monitor_copy": bool(segs), "events": tamper[:20]}+ msg = None+ if segs:+ copies = []+ for n in segs:+ with open(os.path.join(d, "%d.jsonl" % n), "rb") as f:+ copies.append(f.read(max_log))+ agent = None+ if os.path.isfile(log) and not os.path.islink(log):+ with open(log, "rb") as f:+ agent = f.read(max_log)+ if len(segs) == 1 and not tamper and agent is not None and agent.startswith(copies[0]):+ pass # the agent's file is what was written (and maybe a last tick more)+ else:+ given, out = {}, [] # line -> most times one earlier segment had it+ for c in copies:+ again, lines, here = dict(given), c.splitlines(True), {}+ for line in lines:+ here[line] = here.get(line, 0) + 1+ if again.get(line):+ again[line] -= 1 # the rewrite's copy of a line given before+ continue+ out.append(line)+ for line, k in here.items():+ given[line] = max(given.get(line, 0), k)+ data = b"".join(out)[:max_log]+ if os.path.lexists(log):+ os.unlink(log)+ with open(log, "wb") as f:+ f.write(data)+ status.update(from_monitor=1, tampered=1, agent_bytes=None if agent is None else len(agent),+ copy_bytes=len(data))+ msg = (f"replaced {log} with the monitor's copy ({len(data)} bytes; the agent's file was "+ + ("missing" if agent is None else f"{len(agent)} bytes, not what was written") + ")")+ if not segs and not tamper:+ return None # no copy (no monitor, or no log written): nothing to say+ logs = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ try:+ os.makedirs(logs, exist_ok=True)+ with open(os.path.join(logs, SESSION_LOG_STATUS), "w") as f:+ json.dump(status, f, indent=1)+ except OSError:+ pass+ return msg+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/selftest.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/selftest.pynew file mode 100644index 0000000000..89d553743f--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/rcb_monitor/selftest.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""What the resource monitor can measure where it runs (capabilities(), written into its record), and a self-test of+the shared violation rule and the verifier step (no containers needed; ci_checks/check-monitor.py runs it):++ python3 scripts/rcb_monitor/selftest.py+"""+import json+import os+import sys+import tempfile++HERE = os.path.dirname(os.path.abspath(__file__))+++def _rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def capabilities():+ """Facts the verifier and the results footnotes need: does the monitor see the host's processes (pid: host), the+ host's cgroup tree (cgroup: host; per-container memory and OOM counts), """+ c = {}+ try:+ pids = [d for d in os.listdir("/proc") if d.isdigit()]+ except OSError:+ pids = []+ try:+ c["pid_host"] = int(len(pids) > 1 and open("/proc/1/comm").read().strip() != open("/proc/self/comm").read().strip())+ except OSError:+ c["pid_host"] = 0+ own = ""+ try:+ own = [ln[3:].strip() for ln in open("/proc/self/cgroup") if ln.startswith("0::")][0]+ except (OSError, IndexError):+ pass+ c["cgroup_v2"] = int(os.path.exists("/sys/fs/cgroup/cgroup.controllers"))+ c["cgroup_host"] = int(bool(own) and own != "/" and os.path.isdir("/sys/fs/cgroup" + own))+ return c+++# --------------------------------------------------------------------------------------------------- self-test+def _check(cond, msg):+ if not cond:+ raise AssertionError(msg)+++def test_rule():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ tick = 5.0+ over = [(i * tick, 10.0 if 20 <= i < 33 else 1.0) for i in range(60)] # 65 s over the limit+ _check(abs(r.sustained(over, 5, 60, 120, tick) - 160.0) < 0.01, "65 s over: confirmed at 60 s")+ short = [(i * tick, 10.0 if 20 <= i < 31 else 1.0) for i in range(60)] # 55 s+ _check(r.sustained(short, 5, 60, 120, tick) is None, "55 s over: no violation")+ flap = [(i * tick, 10.0 if (i % 2 == 0 and i >= 20) else 1.0) for i in range(80)] # half the time, never 60 s straight+ _check(r.sustained(flap, 5, 60, 120, tick) is not None, "59 s on / 1 s off does not escape: 60 s in any 120 s")+ sparse = [(i * 25.0, 10.0) for i in range(4)] # 25 s gaps count 15 s each+ _check(r.sustained(sparse, 5, 60, 120, tick) is None, "gaps never count against the agent")+ _check(r.sustained(over, 0, 60, 120, tick) is None, "limit 0 = not limited")+ disk = [(0, 1.0), (60, 30.0), (120, 1.0), (180, 30.0), (240, 31.0)]+ _check(r.consecutive(disk, 20) == 240, "disk: two consecutive measurements over")+++def test_verify():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ lim = {"max_gpu_memory_gb": 4.0, "max_memory_gb": 8.0, "max_processes": 100, "max_disk_gb": 10.0,+ "sustain_sec": 60, "window_sec": 120, "tick_sec": 5}+ for enforce, gpu, want in ((1, 6.0, "fail"), (0, 6.0, "observe"), (1, 3.0, "pass")):+ with tempfile.TemporaryDirectory() as d:+ rec, tests, logs = (os.path.join(d, x) for x in ("rec", "tests", "logs"))+ for x in (rec, tests, logs):+ os.makedirs(x)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ with open(os.path.join(rec, "samples.jsonl"), "w") as f:+ for i in range(40):+ f.write(json.dumps({"t": 1000 + 5 * i, "scope": {"gpu_memory_gb": gpu if i > 5 else 0.5,+ "memory_gb": 2.0, "processes": 10,+ "disk_gb": 0.1 if i % 12 == 0 else None}}) + "\n")+ open(os.path.join(rec, "events.jsonl"), "w").close()+ json.dump({"format": r.FORMAT, "sealed": True, "enforce": enforce, "scope_seen": True},+ open(os.path.join(rec, "summary.json"), "w"))+ json.dump({"success": 1, "infra_error": 0}, open(os.path.join(logs, "reward.json"), "w"))+ open(os.path.join(logs, "reward.txt"), "w").write("1\n")+ import shutil+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=rec, RCB_VERIFIER_LOGS=logs)+ import subprocess+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ txt = open(os.path.join(logs, "reward.txt")).read().strip()+ if want == "fail":+ _check(out["success"] == 0 and out["resource_limit_exceeded"] == 1 and out["success_before_limits"] == 1+ and txt == "0" and out["over_gpu_memory_gb"] == 1, f"enforced violation fails: {out}")+ elif want == "observe":+ _check(out["success"] == 1 and out["limits_violation_observed"] == 1 and txt == "1"+ and "resource_limit_exceeded" not in out, f"observe mode only records: {out}")+ else:+ _check(out["success"] == 1 and out["limits_violation_observed"] == 0 and out["resource_monitor_missing"] == 0,+ f"within limits: {out}")+ _check(out["peak_gpu_memory_gb"] == gpu, "peak recorded")+ # no record at all: enforced = infra, observed = flagged only+ for enforce in (1, 0):+ with tempfile.TemporaryDirectory() as d:+ logs, tests = os.path.join(d, "logs"), os.path.join(d, "tests")+ os.makedirs(logs)+ os.makedirs(tests)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ json.dump({"success": 1}, open(os.path.join(logs, "reward.json"), "w"))+ import shutil+ import subprocess+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=os.path.join(d, "none"), RCB_VERIFIER_LOGS=logs,+ RCB_LIMITS_ENFORCE=str(enforce))+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ _check(out["resource_monitor_missing"] == 1 and out.get("infra_error", 0) == enforce,+ f"missing record (enforce={enforce}): {out}")+++def main():+ if sys.argv[1:2] == ["caps"]:+ print(json.dumps(capabilities()))+ return 0+ test_rule()+ test_verify()+ print("rcb_monitor selftest: ok")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/__init__.pynew file mode 100644index 0000000000..eeacb3c0af--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/__init__.py@@ -0,0 +1,69 @@+"""RoboOlympics robot resource library (bodies/README.md, "机器人资源库"): shared robots, the attachments on their+common wrist mount, the one trusted limit / servo path, and optional control libraries. Not a part of the framework+(players / sports / core / tools): a library the sports draw from; core never imports it.++ from bodies import load_body, assemble+ B = load_body("wheeled_humanoid") # a robot: model, joints, actuators, real limits (body.toml)+ cfg = assemble("wheeled_humanoid", "paddle", controllers=["wholebody"]) # robot + attachment + controllers+ cfg.id # "wheeled_humanoid@wh-3+paddle+wholebody#<hash>"++A sport declares in sport.toml++ [body]+ name = "wheeled_humanoid"+ hand = "paddle"+ controllers = ["wholebody"] # optional: bodies/control/<name>.py the sport imports++tools/generate.py then copies the robot (without its fine meshes and provenance tools), the attachments, the limit+/ servo path and the declared control libraries into the task's simulator directory, with configuration.json (the+assembled configuration's id and hash). The fixed-base arms (franka_panda, franka_fr3, kuka_iiwa14: limits only, each+sport's scene carries the arm's MJCF) are declared with [arm] body instead; the limits-only legged robots (booster_t1:+the sport's scene carries the model and its walking policy; bodies/servo.py Actuators + WalkCommand) with [legs] body.+"""+from __future__ import annotations++import importlib+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+# library robots with a model, a rig and a servo (load_body); "status" in each body.toml says what they may be used for+BODIES = ("wheeled_humanoid", "unitree_g1", "unitree_h1", "galaxea_r1pro", "tianji_marvin_pro", "abb_irb1100")+ARMS = ("franka_panda", "franka_fr3", "kuka_iiwa14") # limits-only entries (bodies/limits.py)+LEGS = ("booster_t1",) # limits-only legged entries (bodies/servo.py Actuators + WalkCommand; the+ # sport's scene carries the model and the walking policy): sport.toml [legs] body+PLANAR = ("ssl_robot",) # planar-base robots with their own interface (MjSpec mount, rig with kick /+ # dribble: bodies/ssl_robot/README.md); load_body works, the arm checks do not apply+ROBOTS = BODIES + ARMS + LEGS + PLANAR+CONTROLLERS = ("wholebody", "arbiter", "kinematics") # bodies/control/: optional, a sport imports them+++def _path():+ if str(HERE.parent) not in sys.path:+ sys.path.insert(0, str(HERE.parent))+++def load_body(name: str):+ """A library robot (bodies/<name>/body.py load()): mount into a scene, rig, robot-only export."""+ if name not in BODIES + PLANAR:+ raise ValueError(f"unknown body {name!r}; one of {list(BODIES + PLANAR)}")+ _path()+ return importlib.import_module(f"bodies.{name}.body").load()+++def planner(name: str):+ """The whole-body planner module (bodies/control/wholebody.py), the same for every body with the wheeled+ humanoid's controlled vector (and the legged ones' planar copies)."""+ if name not in BODIES:+ raise ValueError(f"unknown body {name!r}; one of {list(BODIES)}")+ _path()+ return importlib.import_module("bodies.control.wholebody")+++def assemble(robot: str, attachment: str | None = None, other_attachment: str | None = None, controllers=(),+ arm: str = "right"):+ """robot + attachment(s) + declared controllers -> an assembled configuration with its own version hash+ (bodies/assembly.py)."""+ _path()+ from bodies import assembly+ return assembly.assemble(robot, attachment, other_attachment, controllers, arm)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/assembly.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/assembly.pynew file mode 100644index 0000000000..dfa297859d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/assembly.py@@ -0,0 +1,132 @@+"""Assembled configurations (bodies/README.md "三个概念"): a robot of the library + its attachment(s) (bodies/hands)++ the control libraries a sport declares = one configuration with its own version hash.++The robot's revision (body.toml) says when the robot changed; the configuration's hash says when anything that+decides how the assembled robot behaves changed: the robot's model, meshes, declarations and code, the attachment's+declaration and model, the declared control libraries, and the shared limit / servo path. Tasks and results record+the configuration id, so a result names exactly the robot it was played with.++ from bodies import assemble+ cfg = assemble("unitree_g1", "paddle", controllers=["wholebody"])+ cfg.id # "unitree_g1@g1-2+paddle+wholebody#3f9c0a1b2c4d"+ cfg.hash # the full sha256+ cfg.record() # a dict for configuration.json, a sport's /spec or its results+ cfg.write(sim_dir / "bodies" / "configuration.json")++ from bodies.assembly import recorded+ recorded(sim_dir) # what tools/generate.py wrote into a task's simulator directory (None if nothing)++Stable: the hash is a sha256 over a canonical JSON of the inputs and the sha256 of every file that takes part+(read as bytes; no timestamps, no paths outside bodies/), so the same files give the same hash in a checkout and in a+task's simulator directory (tools/sportlib.copy_body copies exactly these files).+"""+from __future__ import annotations++import hashlib+import json+import tomllib+from dataclasses import dataclass, field+from pathlib import Path++HERE = Path(__file__).resolve().parent+SHARED = ("limits.py", "servo.py", "selfcollision.py") # the trusted limit / servo path, self-collision+ROBOT_FILES = ("body.toml", "model.xml", "*.py", "meshes/*", "meshes_25k/*", "policy/*.npz") # behaviour, players' images+FILE_NAME = "configuration.json"+++def _sha(p: Path) -> str:+ return hashlib.sha256(p.read_bytes()).hexdigest()+++def robot_files(robot: str, root: Path = HERE) -> list[Path]:+ """The files of bodies/<robot>/ that decide its behaviour (not the fine meshes, provenance tools, licences)."""+ d = root / robot+ out = set()+ for pat in ROBOT_FILES:+ out.update(p for p in d.glob(pat) if p.is_file() and "__pycache__" not in p.parts)+ return sorted(out)+++@dataclass+class Configuration:+ robot: str+ revision: str+ title: str+ status: str+ attachment: str | None+ other_attachment: str | None+ arm: str+ controllers: list+ files: dict = field(default_factory=dict) # path relative to bodies/ -> sha256+ hash: str = ""++ @property+ def id(self) -> str:+ parts = [f"{self.robot}@{self.revision}", self.attachment or "bare"]+ if self.other_attachment:+ parts.append(f"{self.other_attachment}(other)")+ parts += list(self.controllers)+ return "+".join(parts) + "#" + self.hash[:12]++ def record(self) -> dict:+ return dict(id=self.id, hash=self.hash, robot=self.robot, revision=self.revision, title=self.title,+ status=self.status, attachment=self.attachment, other_attachment=self.other_attachment,+ arm=self.arm, controllers=list(self.controllers), files=dict(self.files))++ def write(self, path) -> Path:+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(self.record(), indent=1, sort_keys=True) + "\n")+ return path+++def assemble(robot: str, attachment: str | None = None, other_attachment: str | None = None, controllers=(),+ arm: str = "right", root: Path | str | None = None) -> Configuration:+ """robot + attachment(s) + declared controllers -> a Configuration with its hash. root: the bodies/ directory+ (default: this one; a task's sim/bodies works the same)."""+ root = Path(root or HERE)+ decl = tomllib.loads((root / robot / "body.toml").read_text())+ b = decl["body"]+ files = {}+ for p in robot_files(robot, root):+ files[str(p.relative_to(root))] = _sha(p)+ for f in SHARED:+ if (root / f).exists():+ files[f] = _sha(root / f)+ hand_decl = {}+ for h in (attachment, other_attachment):+ if h:+ hands = tomllib.loads((root / "hands" / "hands.toml").read_text())+ if h not in hands:+ raise ValueError(f"unknown attachment {h!r}; one of {sorted(hands)}")+ hand_decl[h] = hands[h]+ files[f"hands/{hands[h]['file']}"] = _sha(root / "hands" / hands[h]["file"])+ controllers = sorted(set(controllers))+ for c in controllers:+ p = root / "control" / f"{c}.py"+ if not p.exists():+ raise ValueError(f"unknown controller {c!r} (bodies/control/{c}.py)")+ files[f"control/{c}.py"] = _sha(p)+ if b.get("kind") == "arm" and (attachment or other_attachment):+ raise ValueError(f"{robot} is a limits-only arm entry: its sport's scene carries the tool")+ canon = dict(robot=robot, revision=b["revision"], attachment=attachment, other_attachment=other_attachment,+ arm=arm, controllers=controllers, attachments=hand_decl, files=dict(sorted(files.items())))+ h = hashlib.sha256(json.dumps(canon, sort_keys=True, separators=(",", ":")).encode()).hexdigest()+ return Configuration(robot, b["revision"], b["title"], b.get("status", "library"), attachment, other_attachment,+ arm, controllers, dict(sorted(files.items())), h)+++def recorded(sim_dir) -> dict | None:+ """The configuration a task's simulator directory was generated with (sim/bodies/configuration.json), or None."""+ p = Path(sim_dir) / "bodies" / FILE_NAME+ return json.loads(p.read_text()) if p.exists() else None+++def verify(sim_dir) -> tuple[bool, str]:+ """Recompute the recorded configuration from the files in sim_dir/bodies: (same hash?, the id)."""+ rec = recorded(sim_dir)+ if rec is None:+ return False, "no configuration.json"+ cfg = assemble(rec["robot"], rec["attachment"], rec["other_attachment"], rec["controllers"], rec["arm"],+ root=Path(sim_dir) / "bodies")+ return cfg.hash == rec["hash"], cfg.iddiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/configuration.json b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/configuration.jsonnew file mode 100644index 0000000000..03f0eb6188--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/configuration.json@@ -0,0 +1,99 @@+{+ "arm": "right",+ "attachment": "epee",+ "controllers": [],+ "files": {+ "hands/epee.xml": "b5dde39a11acd81eac48b0f11f42bde1c88e8ddcf8c6951cb4f5ba1ed3f3f500",+ "limits.py": "3c1c255c17edcd97e2a9f817632073c72b5e2255b5c9cea92af51c2418ff4fe2",+ "selfcollision.py": "92634c19d3e7cb005f79b7ffe5af9a119bda1538a4ceab1cd32927029277c7c2",+ "servo.py": "8fda6665e86e2d214e712013547b0e9235e7f585b6372f0a544eb23902e4613e",+ "unitree_g1/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",+ "unitree_g1/agile.py": "34f2ba002a957f4a833479c8aeb0f161f3b00b019d0361ca58c5ffa7c42275a8",+ "unitree_g1/body.py": "8b78d0635a096f33b8251a1112cb83d68061d1c312bc1e3e500c1bf142a0cb0d",+ "unitree_g1/body.toml": "2325acc68a7ac0a1e622726eb5d1a7769a7d316fb284ac3f38247d6517ea5789",+ "unitree_g1/falcon.py": "54766d6d95c115b6123b57ff2e47c400b500d83c7e4f6a3e3e5c87313ac5a392",+ "unitree_g1/kick.py": "c664f7b536ac81667426decde49f937f1068d775c5fb7605a812cc0e95d5e110",+ "unitree_g1/meshes/head_link.stl": "7f521c99e468cda5381b88de4ec05dfee599d53659371a97748f611eb711ddb1",+ "unitree_g1/meshes/left_ankle_pitch_link.stl": "1dca4a92c90edce064bd358a697a09078d456b97ba71c9753ce0c89ce5e95e20",+ "unitree_g1/meshes/left_ankle_roll_link.stl": "daeb41423a730353c32a663a25081249adab1e0d2b1f75680032427286c98d47",+ "unitree_g1/meshes/left_elbow_link.stl": "11b90a65c436cc6e29732665e69b262770550f85495ef818a31c9843a48e9453",+ "unitree_g1/meshes/left_hip_pitch_link.stl": "23b44cf14be710741889451e7ca22e57df9c80d74aec0ea6945827962bd807b8",+ "unitree_g1/meshes/left_hip_roll_link.stl": "169e1d38fde7752d66ba0a604d83dfb1c6bd7cb75669f380fae03fe01184d4f5",+ "unitree_g1/meshes/left_hip_yaw_link.stl": "cc6d89db6683d52c02b859b92601b3d98a7d46883c0d16a327811d976fd8a827",+ "unitree_g1/meshes/left_knee_link.stl": "7d566d51ea3fe5dde90470f36cd9809bbc2edd36aecc9b119512bfb2d4495893",+ "unitree_g1/meshes/left_rubber_hand.stl": "be14d2b3e72e59094e119b2d0cba50f2b780ce74ab351c90282afe29061b80fb",+ "unitree_g1/meshes/left_shoulder_pitch_link.stl": "d671bd2a7831a8b4c9d5c5487676ca5d94d84f5cb86026acfcd833f549197bc9",+ "unitree_g1/meshes/left_shoulder_roll_link.stl": "8f491a0fbe1f34947de1e16c81658bd26dfe0f2958c59ae83829192044672131",+ "unitree_g1/meshes/left_shoulder_yaw_link.stl": "8151d536bc0bbd6d38277a047e0109649aa174b17b15fc2878253d47d2a0d548",+ "unitree_g1/meshes/left_wrist_pitch_link.stl": "b57e59744483c9b389373e326a9e9597047b32e78ed6df7d8c7a6c3a96105701",+ "unitree_g1/meshes/left_wrist_roll_link.stl": "5d2e89cab6c5583269179cd573a7b8e09a7a9eec86ad842f680df8ee9c8f7fc5",+ "unitree_g1/meshes/left_wrist_yaw_link.stl": "5fa6603d707585f94259ad63d0a9ae0ebc430116443bf6c491b98e411a88436b",+ "unitree_g1/meshes/logo_link.stl": "033edba23cd6314aac5a9710c81d4cfc0b77f28b9bdbafade3fdec7bfeb1438b",+ "unitree_g1/meshes/pelvis.stl": "7fc122ba00b406a79014370b9a5e6d81cb75e12def7faf5a313f6ea55f1cb371",+ "unitree_g1/meshes/pelvis_contour_link.stl": "86838d78054520c8a7987632cb8fc102d06e310ae04a0c211a96fc1173f8f33f",+ "unitree_g1/meshes/right_ankle_pitch_link.stl": "5dba280683a0fe546b75cd17677b35e128098947dc7df15240fec645622b064b",+ "unitree_g1/meshes/right_ankle_roll_link.stl": "1f9b09689332ae170e309a91dcb28b685cac310c897a3bb689d8bc85a8050f4a",+ "unitree_g1/meshes/right_elbow_link.stl": "fdb1d4142e9a6cc64f4b6602538dde3310eda04589899f5f534a90922a574732",+ "unitree_g1/meshes/right_hip_pitch_link.stl": "0073660201fd7db9f04153f27af02ed50f48393e32c6168fc7eadeb404bdc053",+ "unitree_g1/meshes/right_hip_roll_link.stl": "35c50fe31dd2c87b4dd249c3d7706039525b760e1068fcc2b28737f771289661",+ "unitree_g1/meshes/right_hip_yaw_link.stl": "8971d1918c578ab17df99f2dccc1c8679f1e00f7e46ae39bb63c984aea321aad",+ "unitree_g1/meshes/right_knee_link.stl": "53dd565d24d70730499f7a41087fd46c54413e5dc3b30defb481e6d688550aec",+ "unitree_g1/meshes/right_rubber_hand.stl": "8916bd1b87d7abfb7f9ce3bbbae1223dd597b9df7e7590ed64e373d579c43f6e",+ "unitree_g1/meshes/right_shoulder_pitch_link.stl": "874e9386b11996653323b0a27812de93c8604b5cd26c951e2db5c94fc7ed878c",+ "unitree_g1/meshes/right_shoulder_roll_link.stl": "50de6c85248dbf89c64c3c9ff9c97b6a4203cf9811cabd81e0a93cdef107cdaf",+ "unitree_g1/meshes/right_shoulder_yaw_link.stl": "b46b13c35fe1e8aedb600ea46ea5e6703a9988fd8a6b5a065a3a6fb5436a7fb7",+ "unitree_g1/meshes/right_wrist_pitch_link.stl": "0a453978ebf4624d6962f0908768be89182c108d3762499ff0f0a40934db7911",+ "unitree_g1/meshes/right_wrist_roll_link.stl": "1a8f1274d785cce6bd40035b46d7206256bda51cb8c0d16ac75a4feb7da126ea",+ "unitree_g1/meshes/right_wrist_yaw_link.stl": "e75956daf0cb161e28815ff0f3f04d6a5e5cb27f2516b61ae06973c02f9d4b37",+ "unitree_g1/meshes/torso_link_rev_1_0.stl": "49d4916cac621b3cc03bddf4a4095eae32c318ea5075ecb275c7f1c5fddfe2f4",+ "unitree_g1/meshes/waist_roll_link_rev_1_0.stl": "f8eb2b56bb080b8bd89778d931d7f060d0106acc3ea5a662a2f5ef1313d10814",+ "unitree_g1/meshes/waist_yaw_link_rev_1_0.stl": "6cda482220cf900e8eb72ac08499c0c0f49ff020e3cbe6176293ea0fd0815e4f",+ "unitree_g1/meshes_25k/head_link.stl": "b0b7459e77a9b361cbd3b42d75cdf8f54280e5771ae6655890920a15048d31e0",+ "unitree_g1/meshes_25k/left_ankle_pitch_link.stl": "d61e414cbeb7f87800c8216959a5d4f34dea746fcdf390f6920f7abe7f473d82",+ "unitree_g1/meshes_25k/left_ankle_roll_link.stl": "ac56add2f6f6c4cd2b3b33274d8b8a10b49acceed658cffc6b36cb4a317923ea",+ "unitree_g1/meshes_25k/left_elbow_link.stl": "6043e71584dec9e8832f1e1e0e061074ad868ed4cf83c63a2684a47650547b32",+ "unitree_g1/meshes_25k/left_hip_pitch_link.stl": "7c5fe35b1d28fad41dbe2865dd6a395255ab54911e5702ea11553635b808261e",+ "unitree_g1/meshes_25k/left_hip_roll_link.stl": "7e0f0ff6a935a6bdf79dd79b7cd206b6225ef1d813aa81bad3b1e8627fae4f24",+ "unitree_g1/meshes_25k/left_hip_yaw_link.stl": "cf13b4e40a0f06ee8f3cf89e5e2a962223912251dd8707a5f8474e66b3df7e5c",+ "unitree_g1/meshes_25k/left_knee_link.stl": "78fa5f7cfea0b075e32de93ee5303cfcb3fe30b21cbb9422d9d3e307ef513530",+ "unitree_g1/meshes_25k/left_rubber_hand.stl": "03a87a3e22dddf9d77fb7ce8189ead6629e90cde3ad8479acf4480afd15f3926",+ "unitree_g1/meshes_25k/left_shoulder_pitch_link.stl": "3163bd3e1e473e4fa48900a74c844a5647b46f6c6ae30e94a1d51183d026cc75",+ "unitree_g1/meshes_25k/left_shoulder_roll_link.stl": "8fe40e7a3c4c62735346e16900e1bf3de7e9373273bb881f232c4a0be7ca470d",+ "unitree_g1/meshes_25k/left_shoulder_yaw_link.stl": "2ef7a79abb015d2fefed54ced7c46b7949c3c6dcb774b6500b2f59522a7ebd52",+ "unitree_g1/meshes_25k/left_wrist_pitch_link.stl": "50baada401939b9ee9e8cd03988f1ad800727394491eef6f4dd88a136f8f1f12",+ "unitree_g1/meshes_25k/left_wrist_roll_link.stl": "233ba263c0ad165460af24c49172d112c476333c64c23cc65f4eec130f75defc",+ "unitree_g1/meshes_25k/left_wrist_yaw_link.stl": "354af14f646a5a29a41142ed1436e9dbda1903755ebe96030d4b518cde989445",+ "unitree_g1/meshes_25k/lod.json": "b7fb97ab3499fa28076a572c26b3125dc3efc069d16b64a756ea9485b4429f3a",+ "unitree_g1/meshes_25k/logo_link.stl": "555ec8563662a7d9dc8c02d731a9657fa77194858a3a252f444aa946aa5f339e",+ "unitree_g1/meshes_25k/pelvis.stl": "a5e7b076649f4899a0fbfcf7e1ee0368cf84fbb2e68bab695398ab6c1ca77d99",+ "unitree_g1/meshes_25k/pelvis_contour_link.stl": "d016ed38115363429e2740aaa047dbd1d4e49fe796f24232099ade2295adcaa0",+ "unitree_g1/meshes_25k/right_ankle_pitch_link.stl": "0c5c9eca53d7370207426be70e45032afcb9f41be13dce246f259e5252e0c6b7",+ "unitree_g1/meshes_25k/right_ankle_roll_link.stl": "e3ac204d29d5f91e97e1cef60691d5edb1fdda026b954e2169c914ab541cffd3",+ "unitree_g1/meshes_25k/right_elbow_link.stl": "233ae8c8f2f55588be7cc6d17cfaa66f9b5c37d0eaf32dbdee3807542478244d",+ "unitree_g1/meshes_25k/right_hip_pitch_link.stl": "9b744118b6b7ffe69d7982ce4579eb20b35a9496b8a13d6aa6ab3145f1163e34",+ "unitree_g1/meshes_25k/right_hip_roll_link.stl": "4c9c886c2977ba0881e87a3ed9712a90a149e5e996cb7a47b7c263926fa99856",+ "unitree_g1/meshes_25k/right_hip_yaw_link.stl": "79954979142fddcf9f234c3cf8b946529ac2b87bc18295b762bf305885e80051",+ "unitree_g1/meshes_25k/right_knee_link.stl": "807714c0d515988cbc17ee929e91e4538e3ce16d867d11fd0b07b2153d5dc210",+ "unitree_g1/meshes_25k/right_rubber_hand.stl": "6ba8ebbdf198df47a175a0fc8c7c14597ebb7e2b6bfeae81f538baf6452aa03f",+ "unitree_g1/meshes_25k/right_shoulder_pitch_link.stl": "c0ccf9540f9cbde63165983e7b62d9aa58ef38e8c552d0e3fcff75f7fec5d715",+ "unitree_g1/meshes_25k/right_shoulder_roll_link.stl": "e5787ae15464c086f4542b29c2dab43f5bd528c5f3ee56f2812545fe5e519bdf",+ "unitree_g1/meshes_25k/right_shoulder_yaw_link.stl": "f4a044687ef796f79e286a3bad4dc2c80be65b212132f938e3582a3ca268e399",+ "unitree_g1/meshes_25k/right_wrist_pitch_link.stl": "226f48f17024005dccaa4f3d3ad5f7e8e16bc357a1aba87de173b20cc6ce6d82",+ "unitree_g1/meshes_25k/right_wrist_roll_link.stl": "fec3af45b3b66aa16bf046cb320f72d0c9933dfed6266e253d78f9223ae925c9",+ "unitree_g1/meshes_25k/right_wrist_yaw_link.stl": "b1f689265c15a16c51cd48cbcae54485486a95596de623b8d13b003456295200",+ "unitree_g1/meshes_25k/torso_link_rev_1_0.stl": "3edf21bb662f94969e70da9a8688851c11cc7a5539ffd7548a2fe0caf16040f7",+ "unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stl": "8d994abdb0d933c51fa1e70f3f409b68cb505f4b4fe230f9e52267e96102ef51",+ "unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stl": "8cc0d812b24b8ce39eb563e74e90570415c4016242a290a557276a5afe2c3284",+ "unitree_g1/model.xml": "00aa6a6949c5e694c153985a9e7298064058864021f7ce9cd490caad0894e33c",+ "unitree_g1/policy/agile_g1_velocity_height.npz": "e4b2c05ed1cfce8c4b679fabdc7b4368f4e3022389a3c494adf07d1294eda4ee",+ "unitree_g1/policy/falcon_g1_29dof.npz": "b9e97b9a4d35fc4be1bbba801890246fec659677b78e8b1ce86559e4391af8de",+ "unitree_g1/policy/motion.npz": "d7d7ca64bdc0ca23de845b3cbfa660ad18012b82c674f23aa4e20a2fa803e89d"+ },+ "hash": "972dc62dacadb7d08fe2271f846d803177d50d674afdc6d73f2630e92353360c",+ "id": "unitree_g1@g1-4+epee#972dc62dacad",+ "other_attachment": null,+ "revision": "g1-4",+ "robot": "unitree_g1",+ "status": "library",+ "title": "legged humanoid (Unitree G1, 29 DOF)"+}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/contacts.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/contacts.pynew file mode 100644index 0000000000..caa6d1c1d2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/contacts.py@@ -0,0 +1,100 @@+"""Contacts between robots (construction step 2, physical consistency: "机器人之间有接触"). The library's robots never+touch each other or a second robot: their collision geoms are contype 4 / conaffinity 0 (bodies/selfcollision.py; each+robot's own parts touch through its explicit self-collision pairs), and a hand's contact geoms (contype 1 /+conaffinity 1) touch the world, a ball and each other. A sport whose robots meet (fencing, basketball, soccer) turns+their contacts on here, on the compiled model:++ from bodies import contacts+ m = mujoco.MjModel.from_xml_string(scene)+ info = contacts.between(m, ["A_", "B_"]) # robot prefixes (as mounted); after compiling, before stepping++Robot k gets two bits above the sports' own (BASE and up, two per robot): its body bit on every collision geom of+its body and hand (the library's contype 4 geoms and the hand's), its tool bit on its hand's contact geoms (the blade,+the racket's strings, ...). Each robot's geoms then touch every other robot's body and tools; a robot never touches+itself through these bits (its self-collision stays with its pairs); everything the geoms touched before they still+touch (the bits are added, none removed). Geoms with contype 0 and conaffinity 0 (drawings) are left alone, and so+are geoms whose names match `skip` (sensing volumes such as the G1's kick strike boxes, contype 8).++MuJoCo's broad phase filters body pairs by body_contype / body_conaffinity, which the compiler sets from the bodies'+geoms (the OR of their bits): changing a geom's bits after compiling is not enough, so the bodies' bits are recomputed+here (without it the robots' bodies are still filtered out and they still pass through each other; found in the+fencing and basketball screenings, 2026-10-11).+"""+from __future__ import annotations++import re++BASE = 16 # the first bit used here; bits 0-15 stay the sports' and the library's (1, 4, 8, ...)+MAX_ROBOTS = (31 - BASE) // 2 # contype is a signed 32-bit int+++def bits(k: int) -> tuple[int, int]:+ """(body bit, tool bit) of the k-th robot."""+ if not 0 <= k < MAX_ROBOTS:+ raise ValueError(f"at most {MAX_ROBOTS} robots")+ return 1 << (BASE + 2 * k), 1 << (BASE + 2 * k + 1)+++def _robot_geoms(m, prefix: str) -> list[int]:+ import mujoco as mj+ out = []+ for g in range(m.ngeom):+ b = mj.mj_id2name(m, mj.mjtObj.mjOBJ_BODY, int(m.geom_bodyid[g])) or ""+ if b.startswith(prefix) and (m.geom_contype[g] or m.geom_conaffinity[g]):+ out.append(g)+ return out+++def between(m, prefixes, skip: str = r"_strike$") -> dict:+ """Turn on the contacts between the robots mounted with these prefixes (and between each robot and the others'+ tools) on the compiled model m. Returns {prefix: {body_bit, tool_bit, geoms, tools}}."""+ import mujoco as mj+ import numpy as np+ prefixes = list(prefixes)+ if len(set(prefixes)) != len(prefixes):+ raise ValueError("duplicate prefixes")+ skip_re = re.compile(skip) if skip else None+ info, sets = {}, {}+ for k, p in enumerate(prefixes):+ body_bit, tool_bit = bits(k)+ gs = []+ for g in _robot_geoms(m, p):+ name = mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, g) or ""+ if skip_re is not None and skip_re.search(name):+ continue+ gs.append(g)+ tools = [g for g in gs if (mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, g) or "").startswith(p + "hand_")+ and int(m.geom_contype[g]) & 1] # the hand's contact geoms (body.py: "contact" in hands.toml)+ sets[p] = (gs, tools)+ info[p] = dict(body_bit=body_bit, tool_bit=tool_bit, geoms=len(gs), tools=len(tools))+ every_body = sum(bits(k)[0] for k in range(len(prefixes)))+ every_tool = sum(bits(k)[1] for k in range(len(prefixes)))+ touched = set()+ for k, p in enumerate(prefixes):+ body_bit, tool_bit = bits(k)+ gs, tools = sets[p]+ for g in gs:+ m.geom_contype[g] |= body_bit+ m.geom_conaffinity[g] |= (every_body & ~body_bit) | (every_tool & ~tool_bit)+ touched.add(int(m.geom_bodyid[g]))+ for g in tools:+ m.geom_contype[g] |= tool_bit+ for b in touched: # the broad phase's body filter (see the module docstring)+ sel = m.geom_bodyid == b+ m.body_contype[b] = int(np.bitwise_or.reduce(m.geom_contype[sel]))+ m.body_conaffinity[b] = int(np.bitwise_or.reduce(m.geom_conaffinity[sel]))+ return info+++def contacts_between(m, d, prefix_a: str, prefix_b: str) -> list[tuple[str, str]]:+ """The active contacts between two robots' geoms (names), for checks and records."""+ import mujoco as mj+ out = []+ for c in d.contact[:d.ncon]:+ n1 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, int(c.geom1)) or ""+ n2 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, int(c.geom2)) or ""+ b1 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_BODY, int(m.geom_bodyid[c.geom1])) or ""+ b2 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_BODY, int(m.geom_bodyid[c.geom2])) or ""+ if (b1.startswith(prefix_a) and b2.startswith(prefix_b)) or (b1.startswith(prefix_b) and b2.startswith(prefix_a)):+ out.append((n1, n2))+ return outdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/board.xml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/board.xmlnew file mode 100644index 0000000000..7a08a84359--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/board.xml@@ -0,0 +1,10 @@+<mujoco model="hand_board">+ <!-- Draft: a flat board hand for volleyball (passing and setting surface), normal = local +x. -->+ <worldbody>+ <body name="hand">+ <geom name="wrist" type="cylinder" fromto="0 0 0 0 0 0.04" size="0.035" mass="0.10" rgba="0.2 0.2 0.22 1" group="2"/>+ <geom name="board" type="box" pos="0 0 0.15" size="0.012 0.11 0.15" mass="0.35" rgba="0.95 0.95 0.97 1" group="2"/>+ <site name="center" pos="0.012 0 0.15" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/epee.xml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/epee.xmlnew file mode 100644index 0000000000..a27d76d0df--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/epee.xml@@ -0,0 +1,22 @@+<mujoco model="hand_epee">+ <!-- An epee (FIE Material Rules, August 2026: m.14 under 770 g ready for use, no balance rule; m.16.3 blade at most+ 90 cm; m.17.1 guard through a 13.5 cm gauge). Blade along +z from the grip at the mount.+ Mass (2026-10-11, from Leon Paul's catalogue, leonpaulusa.com: FIE maraging blades 150-183 g at 89-89.5 cm,+ electric guards 86-133 g at 13.3 cm, grips 42-62 g, French pommels up to 200 g; "an epee made with all standard+ parts and a traditional blade weighs 454 g"): grip, pommel and nut 0.14 kg (centre 0.05 m), guard 0.13 kg (a+ disc at 0.105 m), blade with its wire 0.175 kg (tapered: centre of mass 35 % along it, 0.425 m), point 0.01 kg+ (1.01 m): 0.455 kg, centre of mass 0.231 m from the mount (12 cm in front of the guard). The inertial below+ carries it (inertia about the centre of mass: the blade and grip as rods, the guard as a disc); the geoms carry+ the shape only. Until 2026-10-11 the draft had 0.76 kg with a 0.45 kg blade (centre 0.375 m): a G1 holding it on+ guard used 76 % of its wrist pitch motor's torque, 37 % with this one (docs/screening/fencing.md, F0). -->+ <worldbody>+ <body name="hand">+ <inertial pos="0 0 0.2310" mass="0.455" diaginertia="0.03138 0.03138 0.00030"/>+ <geom name="grip" type="capsule" fromto="0 0 0 0 0 0.10" size="0.015" mass="0" rgba="0.15 0.15 0.15 1" group="2"/>+ <geom name="guard" type="cylinder" fromto="0 0 0.10 0 0 0.11" size="0.0675" mass="0" rgba="0.8 0.8 0.85 1" group="2"/>+ <geom name="blade" type="capsule" fromto="0 0 0.11 0 0 1.01" size="0.005" mass="0" rgba="0.75 0.77 0.8 1" group="2"/>+ <geom name="tip" type="sphere" pos="0 0 1.01" size="0.007" mass="0" rgba="0.2 0.2 0.2 1" group="2"/>+ <site name="tip" pos="0 0 1.017" size="0.004" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/gripper.xml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/gripper.xmlnew file mode 100644index 0000000000..cbc385ee31--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/gripper.xml@@ -0,0 +1,18 @@+<mujoco model="hand_gripper">+ <!-- Draft: a parallel gripper that holds and releases (throwing). Two fingers on slide joints, 0-4 cm each; the+ sport adds the finger actuators and the release rule. -->+ <worldbody>+ <body name="hand">+ <geom name="palm" type="box" pos="0 0 0.04" size="0.03 0.06 0.04" mass="0.40" rgba="0.2 0.2 0.22 1" group="2"/>+ <body name="finger_l_body" pos="0 0.045 0.08">+ <joint name="finger_l" type="slide" axis="0 1 0" range="0 0.04"/>+ <geom name="finger_l" type="box" pos="0 0 0.04" size="0.012 0.008 0.04" mass="0.05" rgba="0.8 0.8 0.85 1" group="2"/>+ </body>+ <body name="finger_r_body" pos="0 -0.045 0.08">+ <joint name="finger_r" type="slide" axis="0 -1 0" range="0 0.04"/>+ <geom name="finger_r" type="box" pos="0 0 0.04" size="0.012 0.008 0.04" mass="0.05" rgba="0.8 0.8 0.85 1" group="2"/>+ </body>+ <site name="center" pos="0 0 0.12" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/hands.toml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/hands.tomlnew file mode 100644index 0000000000..7b98300f28--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/hands.toml@@ -0,0 +1,59 @@+# Hands and tools on the common wrist mount (bodies/README.md). A hand is an MJCF fragment whose root body is named+# "hand"; body.py attaches it to the mount body <arm>_mount (+z away from the wrist) and prefixes every name with the+# robot's prefix + "hand_" (so geom "blade" becomes e.g. "A_hand_blade"). Collision: "contact" geoms take part in the+# sport's own contact rules (contype 1, conaffinity 1: the sport adds its <pair>s); every other hand geom is part of+# the robot (contype 4, conaffinity 0: it touches the ball and the world but never the robot itself).+# status: ready = used by a sport and tested there; draft = geometry only, the sport that needs it finishes it.+# Limits (audit 2026-10-08, G10): no hand is actuated yet (the gripper's fingers and the suction cup have no motor).+# The sport that first actuates one declares the real tool it stands for here, with sources, and drives it through+# bodies/servo.py: e.g. the Franka Hand (30-70 N continuous grip, 80 mm stroke, 50 mm/s per finger; product manual+# R50010 v1.2), the RB-Y1 gripper (0.05 m/s, rby1-sdk URDF), the R1 Pro gripper (0-100 mm stroke).++[paddle]+file = "paddle.xml"+status = "ready"+sports = ["tabletennis"]+contact = ["blade"]+site = "center" # the blade centre; face normal = the hand body's local +x+note = "the table-tennis paddle of the Franka tasks (15 x 15 x 1.5 cm blade, 0.14 m beyond the flange, 0.14 kg)"++[racket]+file = "racket.xml"+status = "draft"+sports = ["tennis", "badminton"]+contact = ["strings"]+site = "center"+note = "an oval head on a 0.40 m shaft (tennis: head 0.27 x 0.20 m, 0.30 kg; badminton scales the head and mass)"++[board]+file = "board.xml"+status = "draft"+sports = ["volleyball"]+contact = ["board"]+site = "center"+note = "a flat 0.30 x 0.22 m board (forearm pass and set surface), normal = local +x"++[suction]+file = "suction.xml"+status = "draft"+sports = ["basketball dribble"]+contact = ["cup"]+site = "center"+note = "a switchable suction cup (0.08 m radius): the sport turns the grip on and off (a weld or adhesion actuator)"++[epee]+file = "epee.xml"+status = "draft"+sports = ["fencing"]+contact = ["blade", "tip"]+site = "tip"+note = "an epee: bell guard, a 0.90 m blade along +z, the point (tip) at its end; 0.455 kg, centre of mass 0.231 m from the mount (a standard-parts epee, Leon Paul catalogue; epee.xml)"+mass_source = "Leon Paul catalogue (leonpaulusa.com, 2026-10-11): FIE maraging blade 150-183 g, electric guard 86-133 g, grip 42-62 g, pommel up to 200 g, 'an epee made with all standard parts and a traditional blade weighs 454 g'; FIE m.14 (< 770 g)"++[gripper]+file = "gripper.xml"+status = "draft"+sports = ["throwing"]+contact = ["finger_l", "finger_r"]+site = "center"+note = "a parallel gripper that holds and releases (two fingers on slide joints, 0-8 cm); the release is the sport's action"diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/paddle.xml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/paddle.xmlnew file mode 100644index 0000000000..cbf773b921--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/paddle.xml@@ -0,0 +1,13 @@+<mujoco model="hand_paddle">+ <!-- The table-tennis paddle of the Franka tasks (sports/tabletennis/sim/scene/tt_scene.xml), on the wrist mount:+ handle along +z, blade centre 0.14 m beyond the flange, face normal = local +x. -->+ <worldbody>+ <body name="hand">+ <geom name="handle" type="capsule" fromto="0 0 0 0 0 0.06" size="0.014" mass="0.05" rgba="0.55 0.35 0.2 1"+ group="2"/>+ <geom name="blade" type="box" pos="0 0 0.14" size="0.0075 0.075 0.075" mass="0.09" rgba="0.75 0.08 0.08 1"+ group="2"/>+ <site name="center" pos="0 0 0.14" size="0.005" rgba="1 1 1 1" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/racket.xml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/racket.xmlnew file mode 100644index 0000000000..a1766e8c6e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/racket.xml@@ -0,0 +1,16 @@+<mujoco model="hand_racket">+ <!-- Draft: a tennis racket on the wrist mount (shaft along +z, head centre 0.53 m beyond the flange, face normal =+ local +x). The strings are a thin box; tennis / badminton set their own contact parameters. -->+ <worldbody>+ <body name="hand">+ <geom name="grip" type="capsule" fromto="0 0 0 0 0 0.20" size="0.017" mass="0.12" rgba="0.1 0.1 0.12 1" group="2"/>+ <geom name="throat" type="capsule" fromto="0 0 0.20 0 0 0.40" size="0.010" mass="0.05" rgba="0.85 0.85 0.9 1"+ group="2"/>+ <geom name="frame" type="ellipsoid" pos="0 0 0.53" size="0.012 0.10 0.135" mass="0.10" rgba="0.85 0.85 0.9 1"+ group="2"/>+ <geom name="strings" type="box" pos="0 0 0.53" size="0.004 0.09 0.125" mass="0.03" rgba="0.9 0.9 0.6 0.6"+ group="2"/>+ <site name="center" pos="0 0 0.53" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/suction.xml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/suction.xmlnew file mode 100644index 0000000000..807d35a57b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/hands/suction.xml@@ -0,0 +1,11 @@+<mujoco model="hand_suction">+ <!-- Draft: a switchable suction hand (basketball dribble). The cup faces +z; the sport adds the grip (an adhesion+ actuator or a weld that it switches on and off) and its rules. -->+ <worldbody>+ <body name="hand">+ <geom name="body" type="cylinder" fromto="0 0 0 0 0 0.08" size="0.04" mass="0.30" rgba="0.2 0.2 0.22 1" group="2"/>+ <geom name="cup" type="cylinder" fromto="0 0 0.08 0 0 0.10" size="0.08" mass="0.10" rgba="0.95 0.45 0.1 1" group="2"/>+ <site name="center" pos="0 0 0.10" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/limits.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/limits.pynew file mode 100644index 0000000000..f11fe77e22--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/limits.py@@ -0,0 +1,445 @@+"""Real-robot arm limits for RoboOlympics bodies (numpy only; shared by every sport with a robot arm).++A body's limits are data: `bodies/<body>/body.toml [limits.arm]` holds the manufacturer's numbers with their sources+(Franka Panda / FER and Franka Research 3: Franka "Control Interface Specification and Robot Limits"; KUKA LBR iiwa 14+R820: KUKA's data sheet). This module turns them into the three things a sport's controller needs, so that no arm can+do what the real robot cannot:++ plan_line(q0, q1, lim, T) a time-optimal straight-line joint move, rest to rest, under the joint velocity,+ acceleration and jerk limits (a 7-segment jerk-limited "S-curve" on the path+ parameter, the slowest joint setting the pace); optionally stretched to T seconds+ JerkLimiter the robot's 1 kHz setpoint generator: it follows any joint reference (the 10 ms targets+ of a sport's controller, a player's low-level trajectory) and guarantees that the+ setpoint it sends to the servo never exceeds the velocity, acceleration and jerk limits+ (what libfranka's rate limiter and a real motion generator do); a reference that is+ itself within the limits is followed with a few milliseconds of lag+ TorqueRateLimiter the servo's output stage: the commanded joint torque changes by at most dtau_max per+ second and stays within tau_max (libfranka's kMaxTorqueRate and the motor torques)+ check_rows(...) a low-level trajectory (rows of joint targets at a fixed step) against the velocity and+ acceleration limits: None or the reason to refuse it+ stats(...) per-joint p50 / p95 / p99 / max of |velocity|, |acceleration|, |jerk|, |torque|,+ |torque rate| against the limits (tools/arm_limits.py measures matches with it)++What it does not change: the physics of balls, contacts and the world; the sports' own base / rail / cart limits (a+sport states those); joint ranges (the MJCF's).++Body-agnostic by design: the wheeled humanoid of the unified body (bodies/wheeled_humanoid, `Rig.apply`) can put its+targets through a JerkLimiter and its servo output through a TorqueRateLimiter in the same way, with its own+body.toml [limits.arm] (accel_rad_s2, jerk_rad_s3, torque_rate_nm_s once a source for them exists).+"""++from __future__ import annotations++import math+import tomllib+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np++HERE = Path(__file__).resolve().parent+++# ------------------------------------------------------------------------------------------------ the limits+@dataclass(frozen=True)+class ArmLimits:+ """One arm's joint limits (arrays of the arm's joints, in order) and where they come from."""++ body: str+ model: str+ range_lo: np.ndarray+ range_hi: np.ndarray+ vel: np.ndarray # rad/s+ acc: np.ndarray | None # rad/s^2 (None: the manufacturer publishes none)+ jerk: np.ndarray | None # rad/s^3+ tau: np.ndarray # N m+ dtau: np.ndarray | None # N m/s+ sources: dict = field(default_factory=dict)+ cartesian: dict = field(default_factory=dict)++ @property+ def n(self) -> int:+ return len(self.vel)++ def scaled(self, k: float) -> "ArmLimits":+ """velocity, acceleration and jerk limits times k (a sport that declares a deviation; torques unchanged)"""+ f = lambda a, p: None if a is None else a * k**p+ return ArmLimits(+ self.body,+ self.model + f" (x{k:g})",+ self.range_lo,+ self.range_hi,+ self.vel * k,+ f(self.acc, 1),+ f(self.jerk, 1),+ self.tau,+ self.dtau,+ self.sources,+ self.cartesian,+ )++ def with_jerk(self, jerk) -> "ArmLimits":+ """the same limits with these jerk limits (e.g. jerk_caps(): what the torque rate allows at a pose)"""+ return ArmLimits(+ self.body,+ self.model,+ self.range_lo,+ self.range_hi,+ self.vel,+ self.acc,+ np.asarray(jerk, float),+ self.tau,+ self.dtau,+ self.sources,+ self.cartesian,+ )++ def table(self) -> dict:+ """the limits as plain lists (for /spec and the instructions)"""+ r = lambda a, nd=4: None if a is None else [round(float(x), nd) for x in a]+ return dict(+ body=self.body,+ model=self.model,+ range_rad=[r(self.range_lo), r(self.range_hi)],+ velocity_rad_s=r(self.vel),+ acceleration_rad_s2=r(self.acc),+ jerk_rad_s3=r(self.jerk, 1),+ torque_nm=r(self.tau, 2),+ torque_rate_nm_s=r(self.dtau, 1),+ )+++def load(body: str, root: Path | str | None = None) -> ArmLimits:+ """The arm limits of bodies/<body>/body.toml (root: the directory holding bodies/<body>; default: this one)."""+ d = tomllib.loads((Path(root or HERE) / body / "body.toml").read_text())+ L = d["limits"]["arm"]+ arr = lambda k: None if L.get(k) is None else np.asarray(L[k], float)+ return ArmLimits(+ body=body,+ model=d["body"]["title"],+ range_lo=arr("range_lo_rad"),+ range_hi=arr("range_hi_rad"),+ vel=arr("speed_rad_s"),+ acc=arr("accel_rad_s2"),+ jerk=arr("jerk_rad_s3"),+ tau=arr("torque_nm"),+ dtau=arr("torque_rate_nm_s"),+ sources=dict(d.get("sources", {})),+ cartesian=dict(d.get("limits", {}).get("cartesian", {})),+ )+++# ------------------------------------------------------------------------------------------------ S-curve+def _scurve_params(D, V, A, J):+ """rest-to-rest S-curve over distance D >= 0 under V, A, J: (Tj, Ta, Tv, vp, ap): jerk time, acceleration-phase+ time, cruise time, peak velocity, peak acceleration. Time-optimal (the 7-segment profile)."""+ if D <= 0.0:+ return 0.0, 0.0, 0.0, 0.0, 0.0+ vp = V+ Ta = 2.0 * math.sqrt(V / J) if V * J < A * A else V / A + A / J+ if D < vp * Ta: # the peak velocity is not reached+ vp = (D * D * J / 4.0) ** (1.0 / 3.0)+ if vp <= A * A / J:+ Ta = 2.0 * math.sqrt(vp / J)+ else:+ vp = 0.5 * A * (-A / J + math.sqrt(A * A / (J * J) + 4.0 * D / A))+ Ta = vp / A + A / J+ Tj = min(Ta / 2.0, A / J)+ ap = J * Tj+ Tv = max(0.0, D / vp - Ta) if vp > 0 else 0.0+ return Tj, Ta, Tv, vp, ap+++def _acc_phase(t, Tj, Ta, vp, ap, J):+ """(p, v, a) at time t in the acceleration phase [0, Ta]"""+ if t <= Tj:+ return J * t**3 / 6.0, 0.5 * J * t * t, J * t+ if t <= Ta - Tj:+ u = t - Tj+ return J * Tj**3 / 6.0 + 0.5 * J * Tj * Tj * u + 0.5 * ap * u * u, 0.5 * J * Tj * Tj + ap * u, ap+ tau = max(0.0, Ta - t)+ return vp * Ta / 2.0 - (vp * tau - J * tau**3 / 6.0), vp - 0.5 * J * tau * tau, J * tau+++class Line:+ """A straight-line joint move q(t) = q0 + s(t) (q1 - q0), s an S-curve from 0 to 1 (rest to rest)."""++ def __init__(self, q0, q1, lim: ArmLimits, T: float = 0.0, margin: float = 1.0):+ self.q0, self.q1 = np.asarray(q0, float).copy(), np.asarray(q1, float).copy()+ dq = np.abs(self.q1 - self.q0)+ big = dq > 1e-12+ if not big.any():+ self.t_min = self.T = 0.0+ self.p = (0.0, 0.0, 0.0, 0.0, 0.0)+ self.V = self.A = self.J = 1.0+ self.k = 1.0+ return+ acc = lim.acc if lim.acc is not None else np.full(lim.n, np.inf)+ jerk = lim.jerk if lim.jerk is not None else np.full(lim.n, np.inf)+ self.V = float(np.min(lim.vel[big] / dq[big])) * margin+ self.A = float(np.min(acc[big] / dq[big])) * margin+ self.J = float(np.min(jerk[big] / dq[big])) * margin+ self.A = min(self.A, 1e9)+ self.J = min(self.J, 1e12)+ self.p = _scurve_params(1.0, self.V, self.A, self.J)+ Tj, Ta, Tv, vp, ap = self.p+ self.t_min = 2.0 * Ta + Tv+ self.T = max(float(T), self.t_min)+ self.k = self.t_min / self.T if self.T > 0 else 1.0 # time scaling of a stretched move++ def s(self, t):+ """(s, ds/dt, d2s/dt2) at time t >= 0"""+ if self.t_min <= 0.0:+ return 1.0, 0.0, 0.0+ u = min(max(t * self.k, 0.0), self.t_min)+ Tj, Ta, Tv, vp, ap = self.p+ if u <= Ta:+ p, v, a = _acc_phase(u, Tj, Ta, vp, ap, self.J)+ elif u <= Ta + Tv:+ p, v, a = vp * Ta / 2.0 + vp * (u - Ta), vp, 0.0+ else:+ p, v, a = _acc_phase(self.t_min - u, Tj, Ta, vp, ap, self.J)+ p, a = 1.0 - p, -a+ return p, v * self.k, a * self.k * self.k++ def at(self, t):+ """(q, qd, qdd) at time t"""+ s, sd, sdd = self.s(t)+ d = self.q1 - self.q0+ return self.q0 + s * d, sd * d, sdd * d++ def samples(self, dt):+ """q at t = dt, 2 dt, ..., n dt with n = ceil(T / dt) (the last sample is q1)"""+ n = max(1, int(math.ceil(self.T / dt - 1e-9)))+ return [self.at(i * dt)[0] if i < n else self.q1.copy() for i in range(1, n + 1)]+++def plan_line(q0, q1, lim: ArmLimits, T: float = 0.0, margin: float = 1.0) -> Line:+ return Line(q0, q1, lim, T, margin)+++def hermite(q0, v0, q1, v1, T, n):+ """a cubic Hermite segment from (q0, v0) to (q1, v1) over T seconds, sampled at T j / n, j = 1..n: (q, qd) arrays+ (n x joints). Turns rows of targets one control step apart into a smooth reference for the JerkLimiter."""+ q0, v0, q1, v1 = (np.asarray(x, float) for x in (q0, v0, q1, v1))+ s = (np.arange(1, n + 1) / n)[:, None]+ h00, h10, h01, h11 = 2 * s**3 - 3 * s**2 + 1, s**3 - 2 * s**2 + s, -2 * s**3 + 3 * s**2, s**3 - s**2+ d00, d10, d01, d11 = 6 * s**2 - 6 * s, 3 * s**2 - 4 * s + 1, -6 * s**2 + 6 * s, 3 * s**2 - 2 * s+ q = h00 * q0 + h10 * T * v0 + h01 * q1 + h11 * T * v1+ qd = (d00 * q0 + d01 * q1) / T + d10 * v0 + d11 * v1+ return q, qd+++def jerk_caps(M, lim: ArmLimits, share: float = 0.7):+ """The joint jerks the torque-rate limit allows with the arm's joint-space inertia M (joints x joints, at a pose):+ the inertia part of the torque rate is M qddd, so joint i may use at most share x dtau_max_i / sum_j |M_ij| (every+ joint at its own cap keeps every torque rate within share of its limit; the rest is left to gravity, Coriolis and+ the servo's corrections). Never above the jerk limits. Without a torque-rate limit: the jerk limits."""+ if lim.dtau is None:+ return lim.jerk+ cap = share * lim.dtau / np.maximum(np.sum(np.abs(np.asarray(M, float)), axis=1), 1e-9)+ return cap if lim.jerk is None else np.minimum(lim.jerk, cap)+++# ------------------------------------------------------------------------------------------------ setpoint limiter+def _sqrt_ctrl(err, k, d):+ """the sqrt controller: linear (gain k) near zero, sqrt(2 d |err|) beyond (braking at d), elementwise"""+ lin = d / (k * k)+ a = np.abs(err)+ out = np.where(a <= lin, k * err, np.sign(err) * np.sqrt(np.maximum(0.0, 2.0 * d * (a - 0.5 * lin))))+ return out+++def brake_speed(dist, A, J):+ """The largest speed from which a jerk-limited stop (acceleration from 0, at most A, jerk J) ends within dist:+ the inverse of d(v) = v sqrt(v / J) (v <= A^2 / J) or v^2 / (2 A) + v A / (2 J). Elementwise."""+ dist = np.maximum(np.asarray(dist, float), 0.0)+ A, J = np.asarray(A, float), np.asarray(J, float)+ small = dist <= A**3 / J**2+ v_small = np.cbrt(dist * dist * J)+ v_big = 0.5 * (-A * A / J + np.sqrt(A**4 / J**2 + 8.0 * A * dist))+ return np.where(small, v_small, v_big)+++class JerkLimiter:+ """The robot's setpoint generator at the physics rate: per joint a third-order state (q, qd, qdd) that follows a+ reference (position r, velocity rd) and never exceeds |qd| <= vel, |qdd| <= acc, |dqdd/dt| <= jerk.++ A cascade (position -> velocity -> acceleration -> jerk) with the reference velocity as feed-forward; the jerk is+ clipped, so the acceleration and velocity bounds hold by construction (the velocity bound with a margin of one+ step of jerk and one of acceleration: the discrete steps' overshoot). The velocity loop is the sqrt law at the jerk+ limit. The position loop brakes within both the acceleration and the jerk in force at this step (brake_speed, on+ the error left once the present acceleration has ramped to zero): the jerk a step may use is the tighter of the+ jerk limit and the step's jerk_cap (limits.jerk_caps(): the torque rate's share at the pose, a few hundred rad/s^3+ on a Panda's shoulder in play), and a position loop that assumed the deceleration there at once (a sqrt law at+ BRAKE x the acceleration limit, this class until 2026-10-11) overshot at such a jerk and rang in a self-sustained+ limit cycle (a 2.9 deg step at 231 rad/s^3: out to 6.4 deg, then +-3.5 deg at 2.5 Hz). servo.SetpointGenerator's+ law, with the coast distance taken relative to the reference's velocity (qd - rd): with qd alone a moving+ reference looked overshot and the setpoint braked early (servo.SetpointGenerator and PlanarBase the same since+ 2026-10-12). Deterministic (plain float64 numpy)."""++ KP, KV = 60.0, 300.0 # 1/s: position and velocity loop gains (the linear zone of the sqrt laws)+ BRAKE = 0.6 # position loop brakes at BRAKE x the acceleration limit (room for the jerk)++ def __init__(self, lim: ArmLimits, dt: float, q0=None):+ self.lim, self.dt = lim, float(dt)+ n = lim.n+ self.A = lim.acc if lim.acc is not None else np.full(n, 1e6)+ self.J = lim.jerk if lim.jerk is not None else np.full(n, 1e9)+ # the velocity bound one step of jerk and one of acceleration below the limit (the discrete steps' overshoot)+ margin = (0.0 if lim.jerk is None else lim.jerk * self.dt**2) + (0.0 if lim.acc is None else lim.acc * self.dt)+ self.V = np.maximum(lim.vel - margin, 0.5 * lim.vel)+ self.reset(np.zeros(n) if q0 is None else q0)++ def reset(self, q, qd=None, qdd=None):+ n = self.lim.n+ self.q = np.asarray(q, float).copy()+ self.qd = np.zeros(n) if qd is None else np.asarray(qd, float).copy()+ self.qdd = np.zeros(n) if qdd is None else np.asarray(qdd, float).copy()++ def step(self, r, rd=None, jerk_cap=None):+ """advance one step towards the reference r (velocity rd); jerk_cap: tighter jerk limits for this step (e.g.+ jerk_caps() at the current pose: a soft limit, which the velocity bound may override up to the jerk limit).+ Returns (q, qd, qdd) of the new setpoint"""+ dt, V, A, Jh = self.dt, self.V, self.A, self.J+ J = Jh if jerk_cap is None else np.minimum(Jh, jerk_cap)+ r = np.asarray(r, float)+ rd = np.zeros_like(r) if rd is None else np.asarray(rd, float)+ # the position loop sees the error left once the present acceleration has ramped to zero at this step's jerk+ # (the distance it still covers, relative to the reference moving at rd) and brakes within the acceleration+ # and that jerk (brake_speed). Relative: with qd alone a moving reference looked overshot and the setpoint+ # braked early (2026-10-12: table-tennis strokes delivered too little blade speed, B9 248/284)+ e = r - self.q+ t = np.abs(self.qdd) / J+ e = e - ((self.qd - rd) * t + 0.5 * self.qdd * t * t - np.sign(self.qdd) * J * t**3 / 6.0)+ v_pos = np.sign(e) * np.minimum(self.KP * np.abs(e), brake_speed(np.abs(e), self.BRAKE * A, J))+ v_cmd = np.clip(rd + v_pos, -V, V)+ a_cmd = np.clip(_sqrt_ctrl(v_cmd - self.qd, self.KV, J), -A, A)+ # never run past the velocity limit: the acceleration must be able to fall to zero (at the jerk limit)+ # before |qd| reaches V; planned with the soft jerk, enforced with the hard one if the soft one changed+ room_up, room_dn = np.maximum(0.0, V - self.qd), np.maximum(0.0, V + self.qd)+ a_cmd = np.clip(a_cmd, -np.sqrt(2.0 * J * room_dn), np.sqrt(2.0 * J * room_up))+ hard = (self.qdd > np.sqrt(2.0 * Jh * room_up)) | (self.qdd < -np.sqrt(2.0 * Jh * room_dn))+ a_cmd = np.where(hard, np.clip(a_cmd, -np.sqrt(2.0 * Jh * room_dn), np.sqrt(2.0 * Jh * room_up)), a_cmd)+ jl = np.where(hard, Jh, J)+ j = np.clip((a_cmd - self.qdd) / dt, -jl, jl)+ self.q = self.q + self.qd * dt + 0.5 * self.qdd * dt * dt + j * dt**3 / 6.0+ self.qd = self.qd + self.qdd * dt + 0.5 * j * dt * dt+ self.qdd = self.qdd + j * dt+ return self.q, self.qd, self.qdd+++class TorqueRateLimiter:+ """The servo's output stage: |tau| <= tau_max and |tau - tau_prev| <= dtau_max * dt every step."""++ def __init__(self, lim: ArmLimits, dt: float, tau0=None):+ self.tau_max = lim.tau+ self.step_max = None if lim.dtau is None else lim.dtau * float(dt)+ self.reset(np.zeros(lim.n) if tau0 is None else tau0)++ def reset(self, tau):+ self.tau = np.clip(np.asarray(tau, float), -self.tau_max, self.tau_max)++ def __call__(self, tau_des):+ t = np.asarray(tau_des, float)+ if self.step_max is not None:+ t = np.clip(t, self.tau - self.step_max, self.tau + self.step_max)+ self.tau = np.clip(t, -self.tau_max, self.tau_max)+ return self.tau+++# ------------------------------------------------------------------------------------------------ low-level rows+def check_rows(rows, dt, lim: ArmLimits, prev=None, prev_vel=None, tol=1.001):+ """Rows of joint targets (n x joints) one step dt apart, against the velocity and acceleration limits; prev, the+ targets in force before the first row (and prev_vel, their velocity), join the check if given. Returns None or the+ reason. Jerk is not checked at this step: the JerkLimiter smooths it at the physics rate."""+ a = np.asarray(rows, float)+ if prev is not None:+ a = np.vstack([np.asarray(prev, float)[None], a])+ if len(a) < 2:+ return None+ v = np.diff(a, axis=0) / dt+ if np.any(np.abs(v) > lim.vel * tol + 1e-9):+ i, j = np.argwhere(np.abs(v) > lim.vel * tol + 1e-9)[0]+ return f"joint {j + 1}: {abs(v[i, j]):.3f} rad/s between rows exceeds its speed limit {lim.vel[j]:.3f} rad/s"+ if lim.acc is None:+ return None+ if prev_vel is not None and prev is not None:+ v = np.vstack([np.asarray(prev_vel, float)[None], v])+ if len(v) < 2:+ return None+ acc = np.diff(v, axis=0) / dt+ bad = np.abs(acc) > lim.acc * tol + 1e-9+ if np.any(bad):+ i, j = np.argwhere(bad)[0]+ return (+ f"joint {j + 1}: {abs(acc[i, j]):.2f} rad/s^2 between rows exceeds its acceleration limit "+ f"{lim.acc[j]:.2f} rad/s^2"+ )+ return None+++# ------------------------------------------------------------------------------------------------ measurement+QUANTITIES = (+ ("vel", "velocity", "rad/s"),+ ("acc", "acceleration", "rad/s^2"),+ ("jerk", "jerk", "rad/s^3"),+ ("tau", "torque", "N m"),+ ("dtau", "torque rate", "N m/s"),+)+++def derivatives(q, dt, breaks=None):+ """velocity, acceleration and jerk of a sampled joint path q (steps x joints) by finite differences; `breaks`+ (step indices where the world was reset) cut the differences. Returns dict of arrays (NaN where undefined)."""+ q = np.asarray(q, float)+ v = np.full_like(q, np.nan)+ v[1:] = np.diff(q, axis=0) / dt+ for b in breaks or ():+ v[b] = np.nan+ a = np.full_like(q, np.nan)+ a[1:] = np.diff(v, axis=0) / dt+ j = np.full_like(q, np.nan)+ j[1:] = np.diff(a, axis=0) / dt+ return dict(vel=v, acc=a, jerk=j)+++def stats(series: dict, lim: ArmLimits, joints=None) -> dict:+ """series: name -> (steps x joints) array (NaN = undefined) for vel, acc, jerk, tau, dtau (any subset).+ Returns per quantity: per joint p50, p95, p99, p99.9, max of |x|, the limit, p99 / limit, max / limit and the+ share of samples above the limit."""+ names = joints or [f"A{i + 1}" for i in range(lim.n)]+ out = {}+ for key, title, unit in QUANTITIES:+ x = series.get(key)+ if x is None:+ continue+ L = getattr(lim, key)+ rows = []+ for j in range(lim.n):+ col = np.abs(np.asarray(x, float)[:, j])+ col = col[np.isfinite(col)]+ if not len(col):+ rows.append(None)+ continue+ p = np.percentile(col, [50, 95, 99, 99.9])+ r = dict(+ joint=names[j],+ n=int(len(col)),+ p50=float(p[0]),+ p95=float(p[1]),+ p99=float(p[2]),+ p999=float(p[3]),+ max=float(col.max()),+ )+ if L is not None:+ lj = float(L[j])+ r.update(+ limit=lj,+ p99_ratio=float(p[2] / lj),+ max_ratio=float(col.max() / lj),+ over_share=float(np.mean(col > lj * 1.001)),+ )+ rows.append(r)+ out[key] = dict(title=title, unit=unit, joints=rows)+ return outdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/selfcollision.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/selfcollision.pynew file mode 100644index 0000000000..bb408e4142--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/selfcollision.py@@ -0,0 +1,657 @@+"""Self-collision (bodies/README.md "自碰撞"; real limits B0): a real arm cannot pass through its own body, so the+simulated one cannot either. One declaration per robot (body.toml [self_collision]) says which parts of the robot+touch which; this module turns it into MuJoCo contact pairs, counts the contacts during play, and checks the+declaration against the model.++What collides (body.toml [self_collision], the rules below):+ parts every body of the robot belongs to a part by a regular expression on its name (without the robot's+ prefix / suffix): an arm (`left_arm`, `right_arm`; a single arm: `arm`) or `body` (torso, waist, head,+ pelvis, legs, the base and its wheels, a pedestal). A body that matches nothing inherits its parent's part;+ one hanging below an arm without matching is the arm's TOOL (the hand on the wrist mount: paddle, racket,+ epee). The bodies a fixed-base arm stands on (its pedestal, gantry carriage, rail cart: the ancestors of the+ robot's matched bodies) are `body`.+ rules every arm geom x every body geom (arm_body; legs count as body here); left arm x right arm, tools+ included (arm_arm); a tool x the links of its own arm (tool_own_arm); with same_arm = true also link x+ link of the same arm (a single arm such as the Franka, whose links fold onto each other). Legs (parts+ `left_leg`, `right_leg`): leg_leg = true, left leg x right leg; same_leg = true, link x link of one leg+ (shin x foot). ignore_geoms (a regular expression on geom names) leaves out sensing volumes.+ excluded automatically: two geoms of one rigid group (bodies welded together: a link, its mount and its tool) and+ of two rigid groups joined by one joint (a link and its parent: the joint's housing overlaps by design,+ MuJoCo's own parent filter); by declaration: [[self_collision.exclude]] entries (two body-name patterns+ and a reason), for hulls that overlap at a joint housing one link further away. Every exclusion is+ written down with its reason; the check below fails an exclusion that matches nothing.++How: explicit MuJoCo <pair>s (named <tag>_<i>, tag = the robot's prefix + "selfcol" + suffix), so the robot's+geoms keep their contype / conaffinity (the library's robots: contype 4 / conaffinity 0, they never touch each+other or a second robot) and a pair adds exactly one tested geom pair; the contact parameters are MuJoCo's defaults+(condim 3, friction 1) with a stiff solref (SOLREF: rigid shells). The contacts+block the motion physically, as the real robot's shell does; the servo is not told (a real controller is not+either: the arm stalls against itself, its PD torque rises to the torque limit).++What is recorded (Monitor, fed by every rig.apply): self-collision events (a pair coming into contact; a bouncing+contact is one event), the time in contact, the peak normal force, its peak 10 ms mean and the impulse, per pair;+events whose 10 ms mean force exceeds the declared threshold ([self_collision] warn_force_n) are counted as+warnings. Recorded only: no penalty (the sports decide; see README).++ from bodies import selfcollision as SC+ plan = SC.plan(template_root, decl["self_collision"], prefix="A_") # stdlib only: pairs + exclusions+ SC.add_pairs(scene_root, plan) # <contact><pair .../></contact>+ mon = SC.Monitor(model, plan.tag, warn_force_n=30.0); mon.update(d) per physics step; mon.summary()+ python -m bodies.selfcollision check [robot ...] # needs mujoco (CI installs it)+ python -m bodies.selfcollision pairs ROBOT # the enabled and excluded pairs+ python -m bodies.selfcollision scene sports/SPORT # a sport's scenes: write the pairs++The planning part (plan, add_pairs, scene_block) is stdlib only; Monitor and check import numpy / mujoco.+"""+from __future__ import annotations++import re+import sys+import xml.etree.ElementTree as ET+from dataclasses import dataclass, field+from pathlib import Path++HERE = Path(__file__).resolve().parent+MARK_BEGIN = "<!-- self-collision: generated by bodies/selfcollision.py (scene_block), do not edit -->"+MARK_END = "<!-- /self-collision -->"+++# ------------------------------------------------------------------------------------------------ the model's tree+def _defaults(root: ET.Element) -> dict[str, dict]:+ """class name -> the geom attributes the class gives (nested defaults inherit), "main" for the top level."""+ table: dict[str, dict] = {"main": {}}++ def walk(el, inherited, name):+ attrs = dict(inherited)+ g = el.find("geom")+ if g is not None:+ attrs.update(g.attrib)+ table[name] = attrs+ for ch in el.findall("default"):+ walk(ch, attrs, ch.get("class"))++ for top in root.findall("default"):+ if top.get("class") in (None, "main"):+ walk(top, table["main"], "main")+ else: # a section of classes appended at the top level+ walk(top, table["main"], top.get("class"))+ return table+++def _resolved(geom: ET.Element, cls: str, table: dict) -> dict:+ out = dict(table.get(cls, table["main"]))+ out.update(geom.attrib)+ return out+++def is_collision_geom(attrs: dict) -> bool:+ """The default selection: a geom MuJoCo would collide (contype or conaffinity non-zero; defaults are 1)."""+ return int(attrs.get("contype", "1")) != 0 or int(attrs.get("conaffinity", "1")) != 0+++def is_physical_geom(attrs: dict) -> bool:+ """A geom that is part of the robot's physical shape: a collision geom, or one with mass (the Franka scenes' arm+ meshes are drawn and simulated but switched out of MuJoCo's contacts with contype 0); not a massless drawing."""+ zero = lambda k: attrs.get(k) is not None and float(attrs[k]) == 0.0+ return is_collision_geom(attrs) or not (zero("mass") or zero("density"))+++SELECT = {"collision": is_collision_geom, "physical": is_physical_geom}+++@dataclass+class Plan:+ tag: str # pair names: <tag>_<i>+ pairs: list = field(default_factory=list) # (geom1, geom2, body1, body2, rule)+ excluded: list = field(default_factory=list) # (body1, body2, reason)+ parts: dict = field(default_factory=dict) # body name -> (part, is_tool)+ unused_exclusions: list = field(default_factory=list)++ def summary(self) -> dict:+ rules: dict[str, int] = {}+ for p in self.pairs:+ rules[p[4]] = rules.get(p[4], 0) + 1+ return {"tag": self.tag, "pairs": len(self.pairs), "by_rule": rules, "excluded_body_pairs": len(self.excluded)}+++def plan(root: ET.Element, decl: dict, prefix: str = "", suffix: str = "", world_geoms=(), select=None,+ name_unnamed: bool = True) -> Plan:+ """The self-collision pairs of one robot in an MJCF tree (a body's template or a whole scene). decl: body.toml+ [self_collision]. prefix / suffix: what the robot's names carry in this tree ("A_", "_b"). world_geoms: geoms of+ the worldbody that belong to the robot's body (a pedestal drawn in the world). select(attrs) -> bool picks the+ geoms that take part (default: the collision geoms). Unnamed selected geoms get a name (<body>_sc<k>), since a+ <pair> names its geoms."""+ select = select or is_collision_geom+ table = _defaults(root)+ wb = root.find("worldbody")+ norm = lambda n: n[len(prefix):len(n) - len(suffix) if suffix else None] \+ if n and n.startswith(prefix) and n.endswith(suffix) else None+ parts_re = {k: re.compile(v) for k, v in decl["parts"].items()}++ def match(n):+ if n is None:+ return None+ for k, rx in parts_re.items():+ if rx.fullmatch(n):+ return k+ return None++ # walk the tree: parent, weld group (bodies without a joint are welded to their parent), class, part+ info = {} # body element -> dict++ def walk(el, parent, weld_parent_group, cls, inherited):+ for b in el.findall("body"):+ name = b.get("name")+ n = norm(name)+ jointed = b.find("joint") is not None or b.find("freejoint") is not None+ weld = b if jointed else weld_parent_group+ c = b.get("childclass") or cls+ m = match(n)+ if m is not None:+ part, tool = m, False+ elif inherited is not None:+ part, tool = inherited[0], inherited[0] != "body"+ else:+ part, tool = None, False+ info[b] = dict(name=name, norm=n, parent=parent, weld=weld, cls=c, part=part, tool=tool or (+ inherited is not None and inherited[1]))+ walk(b, b, weld, c, (part, info[b]["tool"]) if part is not None else None)++ walk(wb, None, "world", "main", None)+ robot = [b for b, i in info.items() if i["part"] is not None]+ if not robot:+ raise ValueError(f"no body of the robot (prefix {prefix!r}, suffix {suffix!r}) in the tree")+ # the bodies the robot stands on (ancestors of its matched bodies, not matched themselves): its body+ for b in robot:+ p = info[b]["parent"]+ while p is not None and info[p]["part"] is None:+ info[p]["part"], info[p]["tool"] = "body", False+ p = info[p]["parent"]+ weld_parent = {}+ for b, i in info.items():+ w = i["weld"]+ if w != "world" and w not in weld_parent:+ pb = info[w]["parent"]+ weld_parent[w] = info[pb]["weld"] if pb is not None else "world"++ def adjacent(wa, wb_):+ return wa is wb_ or weld_parent.get(wa) is wb_ or weld_parent.get(wb_) is wa++ # the geoms that take part (not those of [self_collision] ignore_geoms: sensing volumes, e.g. a kick's strike box)+ ignore = re.compile(decl["ignore_geoms"]) if decl.get("ignore_geoms") else None+ kind = lambda p: "arm" if p.endswith("arm") else "leg" if p.endswith("leg") else "body"+ geoms = [] # (name, body element or None for the world, part, tool, weld)+ for b, i in info.items():+ if i["part"] is None:+ continue+ k = 0+ for g in b.findall("geom"):+ attrs = _resolved(g, g.get("class") or i["cls"], table)+ if not select(attrs):+ continue+ if ignore is not None and g.get("name") is not None and ignore.fullmatch(norm(g.get("name")) or ""):+ continue+ if g.get("name") is None:+ if not name_unnamed:+ raise ValueError(f"an unnamed collision geom in body {i['name']}")+ g.set("name", f"{i['name']}_sc{k}")+ k += 1+ geoms.append((g.get("name"), b, i["part"], i["tool"], i["weld"]))+ for gname in world_geoms:+ g = next((x for x in wb.findall("geom") if x.get("name") == gname), None)+ if g is None:+ raise ValueError(f"world geom {gname!r} not found")+ geoms.append((gname, None, "body", False, "world"))+ # exclusions by declaration+ ex = [(re.compile(e["bodies"][0]), re.compile(e["bodies"][1]), e["reason"]) for e in decl.get("exclude", [])]+ used = [False] * len(ex)+ bn = lambda b: "world" if b is None else info[b]["norm"] or info[b]["name"]+ rules = decl.get("rules", {})+ out = Plan(tag=f"{prefix}selfcol{suffix}",+ parts={info[b]["name"]: (i["part"], i["tool"]) for b, i in info.items() if i["part"] is not None})+ seen_ex = set()+ for x in range(len(geoms)):+ for y in range(x + 1, len(geoms)):+ g1, b1, p1, t1, w1 = geoms[x]+ g2, b2, p2, t2, w2 = geoms[y]+ if b1 is b2 and b1 is not None:+ continue+ k1, k2 = kind(p1), kind(p2)+ if k1 == "arm" and k2 == "arm":+ if p1 != p2:+ rule = "arm_arm"+ elif t1 != t2:+ rule = "tool_own_arm"+ elif not t1 and rules.get("same_arm", False):+ rule = "same_arm"+ else:+ continue+ elif k1 == "arm" or k2 == "arm": # an arm (or its tool) with the body or a leg+ rule = "tool_body" if (t1 or t2) else "arm_body"+ elif k1 == "leg" and k2 == "leg":+ rule = "leg_leg" if p1 != p2 else "same_leg"+ if not rules.get(rule, False):+ continue+ else: # body x body, leg x body: not tested+ continue+ if not rules.get(rule if rule != "tool_body" else "arm_body", True):+ continue+ if adjacent(w1, w2):+ key = tuple(sorted((bn(b1), bn(b2))))+ if key not in seen_ex:+ seen_ex.add(key)+ out.excluded.append((*key, "AUTO: one rigid group, or two joined by one joint (the joint's "+ "housing; MuJoCo's parent filter)"))+ continue+ n1, n2 = bn(b1), bn(b2)+ hit = None+ for k, (ra, rb, why) in enumerate(ex):+ if (ra.fullmatch(n1) and rb.fullmatch(n2)) or (ra.fullmatch(n2) and rb.fullmatch(n1)):+ hit = k+ break+ if hit is not None:+ used[hit] = True+ key = tuple(sorted((n1, n2)))+ if key not in seen_ex:+ seen_ex.add(key)+ out.excluded.append((*key, ex[hit][2]))+ continue+ out.pairs.append((g1, g2, n1, n2, rule))+ out.unused_exclusions = [decl["exclude"][k]["bodies"] for k in range(len(ex)) if not used[k]]+ return out+++def is_tag(name: str | None, tag: str) -> bool:+ """A pair name of this robot: <tag>_<i> exactly (robot A's tag "selfcol" must not take robot B's "selfcol_b_3")."""+ return bool(name) and re.fullmatch(re.escape(tag) + r"_\d+", name) is not None+++def info(p: Plan | None) -> dict:+ """What a body's mount() returns about its self-collision (p None: switched off)."""+ if p is None:+ return {"selfcol_tag": None, "selfcol_pairs": 0, "selfcol_unused": [], "selfcol_plan": None}+ return {"selfcol_tag": p.tag, "selfcol_pairs": len(p.pairs), "selfcol_unused": p.unused_exclusions,+ "selfcol_plan": p}+++SOLREF = "0.005 1" # stiff (5 ms, critically damped): the shells are rigid; MuJoCo's default 0.02 lets a servo+ # pushing at its torque limit sink an arm 2 cm into the body (conformance 9)+++def pair_elements(p: Plan) -> list[ET.Element]:+ return [ET.Element("pair", name=f"{p.tag}_{i}", geom1=g1, geom2=g2, solref=SOLREF)+ for i, (g1, g2, *_r) in enumerate(p.pairs)]+++def add_pairs(scene: ET.Element, p: Plan) -> int:+ """Append the plan's pairs to the scene's <contact> (created if missing). Returns the number of pairs."""+ con = scene.find("contact")+ if con is None:+ con = ET.SubElement(scene, "contact")+ for el in pair_elements(p):+ con.append(el)+ return len(p.pairs)+++def scene_block(plans: list[Plan], indent: str = " ") -> str:+ """The pairs of fixed scenes (a sport's MJCF file) as text between the generated-block markers."""+ lines = [indent + MARK_BEGIN]+ for p in plans:+ for el in pair_elements(p):+ lines.append(indent + ET.tostring(el, encoding="unicode"))+ lines.append(indent + MARK_END)+ return "\n".join(lines)+++def put_scene_block(text: str, block: str) -> str:+ """Insert (or replace) the generated block in an MJCF text: inside <contact> (created before </mujoco>)."""+ if MARK_BEGIN in text:+ a = text.index(MARK_BEGIN)+ a = text.rfind("\n", 0, a) + 1+ b = text.index(MARK_END) + len(MARK_END)+ return text[:a] + block.lstrip("\n") + text[b:]+ i = text.rfind("</contact>")+ if i >= 0:+ i = text.rfind("\n", 0, i) + 1 # the start of the </contact> line+ return text[:i] + block + "\n" + text[i:]+ j = text.rfind("</mujoco>")+ return text[:j] + " <contact>\n" + block + "\n </contact>\n" + text[j:]+++def sport_scenes(sport_dir: Path) -> list[tuple[Path, list[Plan]]]:+ """The scenes of a sport that carries a library arm in its own scene (sport.toml [self_collision]: body, and+ [[self_collision.scenes]]: scene, robots = [{prefix, suffix, world_geoms}], geoms = "collision" | "physical")+ with their plans (stdlib only)."""+ import tomllib+ st = tomllib.loads((sport_dir / "sport.toml").read_text())+ sc = st.get("self_collision") or {}+ decl = tomllib.loads((HERE / sc["body"] / "body.toml").read_text())["self_collision"]+ out = []+ for e in sc.get("scenes", []):+ f = sport_dir / e["scene"]+ root = ET.fromstring(f.read_text())+ plans = [plan(root, decl, prefix=r.get("prefix", ""), suffix=r.get("suffix", ""),+ world_geoms=r.get("world_geoms", ()), select=SELECT[e.get("geoms", "collision")],+ name_unnamed=False) for r in e["robots"]]+ out.append((f, plans))+ return out+++def write_sport_scenes(sport_dir: Path) -> list[str]:+ """Write (or refresh) the generated pair blocks of a sport's scenes. Returns what it did."""+ done = []+ for f, plans in sport_scenes(sport_dir):+ text = f.read_text()+ new = put_scene_block(text, scene_block(plans))+ if new != text:+ f.write_text(new)+ done.append(f"{f}: {sum(len(p.pairs) for p in plans)} pairs" + ("" if new != text else " (unchanged)"))+ return done+++def scene_pairs(text: str) -> list[tuple[str, str, str]]:+ """The (name, geom1, geom2) of the generated block of an MJCF text (stdlib: for the static CI check)."""+ if MARK_BEGIN not in text:+ return []+ blk = text[text.index(MARK_BEGIN):text.index(MARK_END)]+ return re.findall(r'<pair name="([^"]+)" geom1="([^"]+)" geom2="([^"]+)"', blk)+++# ------------------------------------------------------------------------------------------------ during play+class Monitor:+ """Self-collision contacts of one robot (its pairs: names <tag>_<i>), fed once per physics step (rig.apply, or+ the sport's loop). An event is a pair coming into contact (after more than GAP_S out of contact: a bouncing+ contact is one event); per event its peak normal force and its peak 10 ms mean force (FORCE_WINDOW_S: what a+ real robot's collision detection, which filters its external-force estimate, would see; an impact's+ instantaneous peak depends on the contact stiffness). An event whose 10 ms mean force exceeds warn_force_n is a+ warning. Also the time in contact, the impulse, the deepest penetration. Nothing it does changes the simulation."""++ GAP_S = 0.02+ FORCE_WINDOW_S = 0.01++ def __init__(self, model, tag: str, warn_force_n: float | None = None):+ import numpy as np+ import mujoco as mj+ self.m = model # no module attributes: a sport may pickle its simulator with it+ self.tag, self.warn = tag, warn_force_n+ ng = model.ngeom+ keys, names = [], {}+ gn = lambda g: mj.mj_id2name(model, mj.mjtObj.mjOBJ_GEOM, g)+ for i in range(model.npair):+ if is_tag(mj.mj_id2name(model, mj.mjtObj.mjOBJ_PAIR, i), tag):+ a, b = int(model.pair_geom1[i]), int(model.pair_geom2[i])+ k = min(a, b) * ng + max(a, b)+ keys.append(k)+ names[k] = (gn(a), gn(b))+ self.keys = np.array(sorted(keys), dtype=np.int64)+ self.names = names+ self.dt = float(model.opt.timestep)+ self.gap = max(1, int(round(self.GAP_S / self.dt)))+ self.win = max(1, int(round(self.FORCE_WINDOW_S / self.dt)))+ self._f = np.zeros(6)+ self.reset()++ @property+ def npairs(self):+ return int(self.keys.size)++ def reset(self):+ self.t = 0+ self.open: dict[int, dict] = {} # pair key -> the running event+ self.events = 0+ self.warnings = 0+ self.steps_in_contact = 0+ self.peak_force = 0.0+ self.peak_force_10ms = 0.0+ self.max_depth = 0.0+ self.impulse = 0.0+ self.first_t = None+ self.by_pair: dict[int, list] = {} # key -> [events, peak force, peak 10 ms mean force]++ def update(self, d):+ """One physics step: the contacts MuJoCo found in the last step (d.contact, d.efc_force)."""+ self.t += 1+ n = d.ncon+ if self.keys.size == 0 or (n == 0 and not self.open):+ return+ import numpy as np+ import mujoco as mj+ now: dict[int, float] = {}+ if n:+ g = d.contact.geom[:n]+ k = np.minimum(g[:, 0], g[:, 1]).astype(np.int64) * self.m.ngeom + np.maximum(g[:, 0], g[:, 1])+ for i in np.nonzero(np.isin(k, self.keys))[0]:+ mj.mj_contactForce(self.m, d, int(i), self._f)+ f = abs(float(self._f[0]))+ kk = int(k[i])+ now[kk] = now.get(kk, 0.0) + f+ self.impulse += f * self.dt+ self.max_depth = max(self.max_depth, -float(d.contact.dist[i]))+ for kk in now:+ if kk not in self.open:+ self.events += 1+ if self.first_t is None:+ self.first_t = self.t+ self.by_pair.setdefault(kk, [0, 0.0, 0.0])[0] += 1+ self.open[kk] = {"w": [0.0] * self.win, "i": 0, "s": 0.0, "peak": 0.0, "avg": 0.0, "last": self.t}+ for kk in list(self.open):+ ev = self.open[kk]+ f = now.get(kk, 0.0)+ w, i = ev["w"], ev["i"]+ ev["s"] += f - w[i]+ w[i] = f+ ev["i"] = (i + 1) % self.win+ if f > 0.0:+ ev["last"] = self.t+ ev["peak"] = max(ev["peak"], f)+ ev["avg"] = max(ev["avg"], ev["s"] / self.win)+ bp = self.by_pair[kk]+ bp[1], bp[2] = max(bp[1], ev["peak"]), max(bp[2], ev["avg"])+ self.peak_force = max(self.peak_force, ev["peak"])+ self.peak_force_10ms = max(self.peak_force_10ms, ev["avg"])+ if self.t - ev["last"] > self.gap: # out of contact for longer than the gap: the event is over+ self._close(kk)+ if now:+ self.steps_in_contact += 1++ def _close(self, kk):+ ev = self.open.pop(kk)+ if self.warn is not None and ev["avg"] > self.warn:+ self.warnings += 1++ def summary(self, top: int = 5) -> dict:+ """What a match record carries (JSON-safe)."""+ open_warn = sum(1 for ev in self.open.values() if self.warn is not None and ev["avg"] > self.warn)+ worst = sorted(self.by_pair.items(), key=lambda kv: -kv[1][2])[:top]+ return {"pairs": self.npairs, "events": self.events, "warnings": self.warnings + open_warn,+ "warn_force_n": self.warn, "time_in_contact_s": round(self.steps_in_contact * self.dt, 4),+ "peak_force_n": round(self.peak_force, 3), "peak_force_10ms_n": round(self.peak_force_10ms, 3),+ "impulse_ns": round(self.impulse, 5), "max_depth_m": round(self.max_depth, 5),+ "first_step": self.first_t,+ "worst_pairs": [{"geoms": list(self.names[k]), "events": v[0], "peak_force_n": round(v[1], 3),+ "peak_force_10ms_n": round(v[2], 3)} for k, v in worst]}+++def monitors(model, tags: dict, body: str) -> dict:+ """One Monitor per seat ({seat: pair tag}) for a sport whose scene carries the library arm `body` (its+ body.toml [self_collision] warn_force_n): for the sports' own simulators (sport.toml [self_collision])."""+ import tomllib+ warn = tomllib.loads((HERE / body / "body.toml").read_text())["self_collision"].get("warn_force_n")+ return {seat: Monitor(model, tag, warn) for seat, tag in tags.items()}+++# ------------------------------------------------------------------------------------------------ the check+def rig_sampler(rig, m, rest_qpos):+ """Random legal poses of a library robot: the controlled vector u (lift, waist, the hand arm) uniform inside the+ rig's ranges (rig.LO / rig.HI; the base and the walking command at rest), the other arm's joints uniform inside+ their MJCF ranges; a legged robot's legs uniform in their ranges (its pelvis where it stands); the base at rest."""+ import numpy as np+ o = getattr(rig, "o", 0)+ other = rig.qadr[-7:]+ jr = {int(m.jnt_qposadr[j]): m.jnt_range[j] for j in range(m.njnt)}+ lo_o = np.array([jr[int(a)][0] for a in other])+ hi_o = np.array([jr[int(a)][1] for a in other])+ legs = rig.lqadr if not getattr(rig, "fixed_base", True) else [] # a legged robot's legs: uniform too+ lo_l = np.array([jr[int(a)][0] for a in legs])+ hi_l = np.array([jr[int(a)][1] for a in legs])++ def sample(rng):+ u = np.array(rig.rest, float)+ u[3:] = rng.uniform(rig.LO[3:], rig.HI[3:])+ q = rest_qpos.copy()+ t = rig.joint_targets(u)+ q[rig.qadr[o:]] = t[o:]+ q[other] = rng.uniform(lo_o, hi_o)+ if len(legs):+ q[legs] = rng.uniform(lo_l, hi_l)+ return q+ return sample+++def check_model(m, tag, rest_qpos, sample, n_random=200, seed=0, structural=0.95, tol=1e-4):+ """The static self-collision check of one compiled model: (problems, report). At rest_qpos no pair of `tag`+ penetrates (more than tol); over n_random random legal poses (sample(rng) -> qpos) no pair penetrates in more+ than `structural` of them (a mount overlap: exclude it with a reason)."""+ import numpy as np+ import mujoco as mj+ d = mj.MjData(m)+ pairs = [i for i in range(m.npair) if is_tag(mj.mj_id2name(m, mj.mjtObj.mjOBJ_PAIR, i), tag)]+ gname = lambda g: mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, int(g))+ dist = lambda i, cut: mj.mj_geomDistance(m, d, int(m.pair_geom1[i]), int(m.pair_geom2[i]), cut, None)+ probs = []+ d.qpos[:] = rest_qpos+ mj.mj_kinematics(m, d)+ rest_pen, closest = [], (None, 1.0)+ for i in pairs:+ x = dist(i, 0.05)+ if x < closest[1]:+ closest = ((gname(m.pair_geom1[i]), gname(m.pair_geom2[i])), x)+ if x < -tol:+ rest_pen.append((gname(m.pair_geom1[i]), gname(m.pair_geom2[i]), round(float(x), 4)))+ for a, b, x in rest_pen:+ probs.append(f"at rest {a} x {b} penetrate by {-x * 100:.2f} cm (fix the rest pose or exclude the pair "+ "with a reason)")+ rng = np.random.default_rng(seed)+ cnt = np.zeros(len(pairs), int)+ any_hit = 0+ for _ in range(n_random):+ d.qpos[:] = sample(rng)+ mj.mj_kinematics(m, d)+ hit = False+ for k, i in enumerate(pairs):+ if dist(i, 0.01) < -tol:+ cnt[k] += 1+ hit = True+ any_hit += hit+ for k, i in enumerate(pairs):+ if cnt[k] > structural * n_random:+ probs.append(f"{gname(m.pair_geom1[i])} x {gname(m.pair_geom2[i])} penetrate in {cnt[k]} of {n_random} "+ "random legal poses: a structural overlap (exclude it with a reason)")+ report = {"pairs": len(pairs), "rest_penetrating": rest_pen,+ "rest_closest": [list(closest[0] or ()), round(float(closest[1]), 4)],+ "random_poses": n_random, "random_poses_with_self_contact": int(any_hit),+ "most_frequent": sorted(([gname(m.pair_geom1[i]), gname(m.pair_geom2[i]), int(cnt[k])]+ for k, i in enumerate(pairs) if cnt[k]), key=lambda x: -x[2])[:5]}+ return probs, report+++def configurations():+ """The hands a library robot is checked with: none, then every hand of bodies/hands/hands.toml on the right+ wrist, with its status (a "ready" hand fails the check, a "draft" hand only warns)."""+ import tomllib+ hands = tomllib.loads((HERE / "hands" / "hands.toml").read_text())+ return [(None, "ready")] + [(h, v.get("status", "draft")) for h, v in hands.items()]+++def compiled(B, hand, other_hand=None, **kw):+ """One library robot (prefix A_) alone in an empty world: (model, info)."""+ import mujoco as mj+ root = ET.Element("mujoco", model="selfcol_check")+ ET.SubElement(root, "compiler", angle="radian", autolimits="true")+ ET.SubElement(root, "option", timestep="0.001")+ for sec in ("default", "asset", "worldbody"):+ ET.SubElement(root, sec)+ if other_hand:+ kw["other_hand"] = other_hand+ info = B.mount(root, "A_", (0.0, 0.0, 0.0), 0.0, hand=hand, **kw)+ return mj.MjModel.from_xml_string(ET.tostring(root, encoding="unicode")), info+++def check_body(name, n_random=200) -> tuple[list, list, dict]:+ """(failures, warnings, report) of one library robot: its declaration is used (no unused exclusion), and in+ every configuration the model passes check_model at the rest pose and over random legal poses."""+ import mujoco as mj+ sys.path.insert(0, str(HERE.parent))+ from bodies import load_body+ B = load_body(name)+ fails, warns, rep = [], [], {}+ unused = None+ for hand, status in configurations():+ m, info = compiled(B, hand)+ d = mj.MjData(m)+ rig = B.rig(m, "A_", hand=hand)+ rig.place(d, rig.rest)+ q0 = d.qpos.copy()+ probs, r = check_model(m, info["selfcol_tag"], q0, rig_sampler(rig, m, q0), n_random=n_random)+ rep[hand or "none"] = r+ u = set(map(tuple, info["selfcol_unused"]))+ unused = u if unused is None else unused & u # unused with every hand+ for p in probs:+ (fails if status == "ready" else warns).append(f"{name} hand={hand or 'none'}: {p}")+ if r["pairs"] == 0:+ fails.append(f"{name} hand={hand or 'none'}: no self-collision pair")+ for u in sorted(unused or ()):+ fails.append(f"{name}: exclusion {list(u)} matches no geom pair (remove it)")+ return fails, warns, rep+++def main(argv=None):+ import argparse+ import json+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("cmd", choices=["check", "pairs", "scene"])+ ap.add_argument("robots", nargs="*")+ ap.add_argument("--random", type=int, default=200)+ ap.add_argument("--json")+ a = ap.parse_args(argv)+ sys.path.insert(0, str(HERE.parent))+ from bodies import BODIES+ if a.cmd == "scene": # robots = sport directories: write their scenes' generated blocks+ for sd in a.robots:+ for line in write_sport_scenes(Path(sd)):+ print(line)+ return 0+ robots = a.robots or list(BODIES)+ if a.cmd == "pairs":+ from bodies import load_body+ for r in robots:+ B = load_body(r)+ root = ET.Element("mujoco")+ for sec in ("default", "asset", "worldbody"):+ ET.SubElement(root, sec)+ p = B.mount(root, "", (0.0, 0.0, 0.0), 0.0, hand="paddle")["selfcol_plan"]+ print(f"== {r}: {p.summary()}")+ for x in p.pairs:+ print(f" pair {x[4]:13s} {x[2]} / {x[0]} x {x[3]} / {x[1]}")+ for x in p.excluded:+ print(f" excl {x[0]} x {x[1]}: {x[2]}")+ return 0+ allf, out = [], {}+ for r in robots:+ f, w, rep = check_body(r, a.random)+ out[r] = {"failures": f, "warnings": w, "report": rep}+ for x in w:+ print("WARN [self-collision]", x)+ for x in f:+ print("FAIL [self-collision]", x)+ print(f"self-collision {r}: " + ", ".join(f"{h}: {v['pairs']} pairs, {v['random_poses_with_self_contact']}/"+ f"{v['random_poses']} random poses in contact"+ for h, v in rep.items()) + ("" if f else "; ok"))+ allf += f+ if a.json:+ Path(a.json).write_text(json.dumps(out, indent=1))+ return 1 if allf else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/servo.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/servo.pynew file mode 100644index 0000000000..7922966b66--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/servo.py@@ -0,0 +1,620 @@+"""The robot library's one trusted limit / servo path (bodies/README.md "限位与伺服").++Every robot of the library sends its commands through this module, and nothing else writes a library robot's+actuators: a robot's `body.py` builds its servo here (`Servo`, `Actuators`, `PlanarBase`, `WalkCommand`) from its+`body.toml`, and a sport drives the robot through the robot's rig (`rig.apply`, `rig.begin_step`) or, for the+fixed-base arms of the library (bodies/franka_panda, franka_fr3, kuka_iiwa14), through `bodies/limits.py`'s+`JerkLimiter` and `TorqueRateLimiter` (the primitives this module composes). `ci_checks/check-robot-limits.py` fails a+sport that references a library robot without going through these (or that defines or patches its own limiter).++The real limits are binding (user decision 2026-10-08, "B0"): the values the manufacturer's controller enforces (SDK)+over the URDF's, never unlimited; an unpublished value is a labelled estimate in body.toml ([limits.<group>.source]+says which). What this module enforces, per layer:++ command `Servo.check` / the rigs' `check`: a 10 ms target row inside the ranges, within the speed limits from+ the row before, and (given the row before that) within the acceleration limits; walking commands+ clipped to the real joystick range and rate-limited (`WalkCommand`)+ setpoint every 1 ms physics step the reference (the 10 ms targets, interpolated) passes a jerk-limited setpoint+ generator (`SetpointGenerator`, limits.JerkLimiter's cascade and braking law, which holds for any ratio+ of acceleration to jerk, for joints and joint-like coordinates; `PlanarBase` for a planar base,+ per axis in the robot's own frame like the vendors' chassis SDKs, or on the norm): the setpoint never+ exceeds the velocity, acceleration and jerk limits that body.toml declares+ output `Actuators.write`: the servo torque through the torque-rate limit (where published), the motor's+ torque-speed curve (where published: Unitree's actuator model) and the torque limit; only then+ `d.ctrl`++What it does not change: contacts, collisions and external forces (a joint pushed by a hit moves as physics says;+D9 of the audit: recorded, not prevented), the joint ranges of the MJCF.++Deterministic: plain float64 numpy, no randomness, no threads.+"""++from __future__ import annotations++import math+from dataclasses import dataclass++import numpy as np++from . import limits as AL++from .sources import QUANTITIES, REQUIRED, SOURCE_RE, TRUSTED, source_problems # noqa: F401 (stdlib only)+++# ------------------------------------------------------------------------------------------------ declarations+def _arr(v, n=None):+ if v is None:+ return None+ a = np.atleast_1d(np.asarray(v, float))+ if n is not None and a.size == 1 and n > 1:+ a = np.full(n, float(a[0]))+ return a+++def joint_limits(decl: dict, group: str, n: int | None = None, name: str | None = None) -> AL.ArmLimits:+ """The limits of one joint group of a body.toml ([limits.<group>]) as bodies/limits.py's ArmLimits (scalars+ broadcast to n joints). Missing acceleration / jerk / torque rate stay None (body.toml's source table says why)."""+ L = decl["limits"][group]+ vel = _arr(L["speed_rad_s"], n)+ n = len(vel)+ rng = L.get("range_rad")+ if rng is not None and np.ndim(rng) == 1:+ lo, hi = np.full(n, float(rng[0])), np.full(n, float(rng[1]))+ elif rng is not None:+ lo, hi = np.array([r[0] for r in rng], float), np.array([r[1] for r in rng], float)+ else:+ lo = _arr(L.get("range_lo_rad"), n) if L.get("range_lo_rad") is not None else np.full(n, -np.inf)+ hi = _arr(L.get("range_hi_rad"), n) if L.get("range_hi_rad") is not None else np.full(n, np.inf)+ return AL.ArmLimits(+ body=decl["body"]["name"] if name is None else name, model=decl["body"]["title"] + f" [{group}]",+ range_lo=lo, range_hi=hi, vel=vel, acc=_arr(L.get("accel_rad_s2"), n), jerk=_arr(L.get("jerk_rad_s3"), n),+ tau=_arr(L.get("torque_nm"), n) if L.get("torque_nm") is not None else np.full(n, np.inf),+ dtau=_arr(L.get("torque_rate_nm_s"), n), sources=dict(decl.get("sources", {})))+++def stack(parts: list[AL.ArmLimits], body: str, model: str) -> AL.ArmLimits:+ """Several limit groups as one (the order of `parts`); a quantity one part lacks becomes None for all, unless+ every part has it."""+ cat = lambda k: None if any(getattr(p, k) is None for p in parts) else np.concatenate([getattr(p, k) for p in parts])+ return AL.ArmLimits(body, model, cat("range_lo"), cat("range_hi"), cat("vel"), cat("acc"), cat("jerk"),+ cat("tau"), cat("dtau"), parts[0].sources if parts else {})+++# ------------------------------------------------------------------------------------------------ output stage+class Actuators:+ """The output stage of a group of motors: servo torques -> torque-rate limit (where declared) -> the motors'+ torque-speed curve (where declared) -> the torque limit -> d.ctrl. The only writer of a library robot's motors.++ envelope: per joint (X1, X2, Y1, Y2) of Unitree's actuator model (unitree_rl_lab unitree_actuators.py): a torque+ along the motion is limited to Y1 below X1 rad/s, falling linearly to 0 at X2 (the motor cannot drive faster); a+ torque against the motion (braking) to Y2 at any speed, as the curve's drawing in unitree_actuators.py shows it+ (its code also fades the braking torque beyond X1, which lets a joint pushed past X2 run away unbraked).++ thermal (optional; motor_model() builds it from body.toml [motors.thermal]): (rated, T, derate_from) per motor:+ an I^2 t state h per motor, dh/dt = ((tau / rated)^2 - h) / T (h = 1: the winding at its limit after a long+ time at the rated torque); the torque limit falls linearly from tau_max at h = derate_from to the rated torque at+ h = 1 (a drive's I^2 t foldback). h starts at 0 (a cold motor) and is never reset by reset(): heat stays with the+ motor (cool_down() for a new match).+ power (optional; [motors.bus]): (groups, watts): per group of motors (one robot's), the summed positive+ mechanical power tau * qd is capped at watts; above it the torques doing positive work are scaled down together+ (the battery and the drives cannot deliver more).+ """++ def __init__(self, model, aid, vadr, tau_max, dt, dtau=None, envelope=None, thermal=None, power=None):+ self.aid, self.vadr = np.asarray(aid, int), np.asarray(vadr, int)+ n = len(self.aid)+ self.dt = float(dt)+ self.tau_max = np.minimum(np.asarray(tau_max, float), model.actuator_ctrlrange[self.aid, 1])+ self.step_max = None if dtau is None else np.asarray(dtau, float) * float(dt)+ self.env = None if envelope is None else tuple(np.asarray(e, float) for e in envelope)+ self.thermal = None+ if thermal is not None:+ rated, T, frm = (np.broadcast_to(np.asarray(x, float), (n,)).copy() for x in thermal)+ self.thermal = (np.minimum(rated, self.tau_max), T, frm)+ self.power = None+ if power is not None:+ groups, watts = power+ self.power = ([np.asarray(g, int) for g in groups], float(watts))+ self.h = np.zeros(n)+ self.tau = np.zeros(n)+ self.stats = dict(steps=0, torque_clipped=0, rate_clipped=0, envelope_clipped=0, thermal_derated=0,+ power_capped=0)++ def reset(self, tau=None):+ self.tau = np.zeros(len(self.aid)) if tau is None else np.clip(np.asarray(tau, float), -self.tau_max,+ self.tau_max)++ def cool_down(self):+ """The thermal state of cold motors (a new match)."""+ self.h = np.zeros(len(self.aid))++ def thermal_limit(self):+ """The torque limit per motor now (the I^2 t foldback; tau_max without a thermal model)."""+ if self.thermal is None:+ return self.tau_max+ rated, _, frm = self.thermal+ x = np.clip((self.h - frm) / np.maximum(1.0 - frm, 1e-9), 0.0, 1.0)+ return self.tau_max - (self.tau_max - rated) * x++ def limit(self, qd):+ """The torque limit per motor at joint speeds qd for torques along (+) the motion: (along, against)."""+ if self.env is None:+ return self.tau_max, self.tau_max+ X1, X2, Y1, Y2 = self.env+ a = np.abs(qd)+ with np.errstate(invalid="ignore"): # X1 = X2 = inf: no curve for that joint+ fall = np.clip(1.0 - (a - X1) / np.maximum(X2 - X1, 1e-9), 0.0, 1.0)+ k = np.where(a < X1, 1.0, fall)+ return np.minimum(Y1 * k, self.tau_max), np.minimum(Y2, self.tau_max)++ def write(self, d, tau):+ t = np.asarray(tau, float)+ st = self.stats+ st["steps"] += 1+ if self.step_max is not None:+ c = np.clip(t, self.tau - self.step_max, self.tau + self.step_max)+ st["rate_clipped"] += int(np.any(c != t))+ t = c+ if self.env is not None:+ qd = d.qvel[self.vadr]+ along, against = self.limit(qd)+ lim = np.where(t * qd > 0, along, against)+ c = np.clip(t, -lim, lim)+ st["envelope_clipped"] += int(np.any((np.abs(c) < np.abs(t) - 1e-12) & (lim < self.tau_max)))+ t = c+ c = np.clip(t, -self.tau_max, self.tau_max)+ st["torque_clipped"] += int(np.any(c != t))+ t = c+ if self.thermal is not None:+ th = self.thermal_limit()+ c = np.clip(t, -th, th)+ st["thermal_derated"] += int(np.any(c != t))+ t = c+ if self.power is not None:+ qd = d.qvel[self.vadr]+ groups, watts = self.power+ p = np.maximum(t * qd, 0.0)+ capped = False+ for g in groups:+ ps = float(p[g].sum())+ if ps > watts:+ pos = g[p[g] > 0]+ t[pos] = t[pos] * (watts / ps)+ capped = True+ st["power_capped"] += int(capped)+ if self.thermal is not None:+ rated, T, _ = self.thermal+ self.h = self.h + self.dt * ((t / rated) ** 2 - self.h) / T+ self.tau = t+ d.ctrl[self.aid] = t+ return t+++def unitree_envelope(decl: dict, joint_keys: list):+ """(X1, X2, Y1, Y2) arrays for joints named by their body.toml [motors.assign] keys (None: a joint without a+ motor curve, e.g. a planar copy's base), or None when the body declares no [motors]."""+ mot = decl.get("motors")+ if not mot:+ return None+ inf = dict(X1=np.inf, X2=np.inf, Y1=np.inf, Y2=np.inf)+ curves = [inf if k is None else mot[mot["assign"][k]] for k in joint_keys]+ return tuple(np.array([c[x] for c in curves], float) for x in ("X1", "X2", "Y1", "Y2"))+++def motor_model(decl: dict, joint_keys: list, groups=None) -> dict:+ """Actuators keyword arguments of a body's motor model from body.toml [motors]: the torque-speed envelope+ (unitree_envelope), the thermal derating ([motors.thermal]: rated_frac of the torque limit is the continuous+ torque, the peak torque from cold lasts peak_s before the foldback ends at the rated torque, the foldback starts+ at derate_from) and the bus power cap per group of motors ([motors.bus] power_w; groups: index arrays into+ joint_keys, one per robot; default all one group). Only the parts the body declares."""+ mot = decl.get("motors") or {}+ kw = dict(envelope=unitree_envelope(decl, joint_keys))+ th = mot.get("thermal")+ if th:+ tau = np.array([np.nan if k is None else _leg_torque(decl, k) for k in joint_keys], float)+ rf = float(th["rated_frac"])+ T = float(th["peak_s"]) / -math.log(1.0 - rf ** 2) # h(peak_s) = 1 at the peak torque from cold+ kw["thermal"] = (rf * tau, T, float(th["derate_from"]))+ bus = mot.get("bus")+ if bus:+ kw["power"] = ([np.arange(len(joint_keys))] if groups is None else groups, float(bus["power_w"]))+ return kw+++def _leg_torque(decl: dict, key: str) -> float:+ """The torque limit of a motor by its [motors.assign] key (the [motors] curve's Y1, the URDF torque)."""+ mot = decl["motors"]+ return float(mot[mot["assign"][key]]["Y1"])+++# ------------------------------------------------------------------------------------------------ setpoints+brake_speed = AL.brake_speed # the jerk-limited stopping speed (bodies/limits.py; the same law, one copy)+++class SetpointGenerator:+ """The library's setpoint generator at the physics rate: per coordinate a third-order state (q, qd, qdd) that+ follows a reference (position r, velocity rd) and never exceeds |qd| <= vel, |qdd| <= acc, |dqdd/dt| <= jerk.++ limits.JerkLimiter's law (velocity loop: the sqrt law at the jerk limit; the velocity guard; the jerk clipped;+ the reference velocity as feed-forward; a position loop that brakes within both the acceleration and the jerk+ limit, brake_speed), with the body's own jerk limit at every step (no per-step jerk_cap). A plain sqrt law on the+ position, which assumes the deceleration is there at once, overshoots and rings wherever the jerk needs long to+ build the acceleration: an SDK's slow jerk (the R1 Pro's arm: 4.5 rad/s^2 at 4.5 rad/s^3) and equally the+ Franka's when its jerk is capped by the torque rate at the pose (limits.jerk_caps(): a few hundred rad/s^3 on+ the shoulder), which is why limits.JerkLimiter uses this law too since 2026-10-11 (since 2026-10-12 both take+ the coast distance relative to the reference's velocity, qd - rd). The velocity bound runs one step of+ acceleration and jerk below the limit (the discrete steps' overshoot). Without declared acceleration /+ jerk (Unitree: none published) it is a velocity limiter with a 17 ms lag. Deterministic (float64 numpy)."""++ KP, KV, BRAKE = AL.JerkLimiter.KP, AL.JerkLimiter.KV, AL.JerkLimiter.BRAKE++ def __init__(self, lim: AL.ArmLimits, dt: float, q0=None):+ self.lim, self.dt = lim, float(dt)+ n = lim.n+ self.A = lim.acc if lim.acc is not None else np.full(n, 1e6)+ self.J = lim.jerk if lim.jerk is not None else np.full(n, 1e9)+ margin = (lim.jerk * self.dt ** 2 if lim.jerk is not None else 0.0) + \+ (lim.acc * self.dt if lim.acc is not None else 0.0)+ self.V = np.maximum(lim.vel - margin, 0.5 * lim.vel)+ self.reset(np.zeros(n) if q0 is None else q0)++ def reset(self, q, qd=None, qdd=None):+ n = self.lim.n+ self.q = np.asarray(q, float).copy()+ self.qd = np.zeros(n) if qd is None else np.clip(np.asarray(qd, float), -self.V, self.V)+ self.qdd = np.zeros(n) if qdd is None else np.asarray(qdd, float).copy()++ def step(self, r, rd=None):+ dt, V, A, J = self.dt, self.V, self.A, self.J+ r = np.asarray(r, float)+ rd = np.zeros_like(r) if rd is None else np.asarray(rd, float)+ e = r - self.q+ # the position loop sees the error left once the present acceleration has ramped to zero at the jerk limit+ # (the distance it still covers, relative to the reference moving at rd): with a slow jerk that distance is+ # what makes a plain sqrt law overshoot; taken with qd alone a moving reference looked overshot and the+ # setpoint braked early (limits.JerkLimiter, 2026-10-12)+ t = np.abs(self.qdd) / J+ e = e - ((self.qd - rd) * t + 0.5 * self.qdd * t * t - np.sign(self.qdd) * J * t ** 3 / 6.0)+ v_pos = np.sign(e) * np.minimum(self.KP * np.abs(e), brake_speed(np.abs(e), self.BRAKE * A, J))+ v_cmd = np.clip(rd + v_pos, -V, V)+ a_cmd = np.clip(AL._sqrt_ctrl(v_cmd - self.qd, self.KV, J), -A, A)+ room_up, room_dn = np.maximum(0.0, V - self.qd), np.maximum(0.0, V + self.qd)+ a_cmd = np.clip(a_cmd, -np.sqrt(2.0 * J * room_dn), np.sqrt(2.0 * J * room_up))+ j = np.clip((a_cmd - self.qdd) / dt, -J, J)+ self.q = self.q + self.qd * dt + 0.5 * self.qdd * dt * dt + j * dt ** 3 / 6.0+ self.qd = self.qd + self.qdd * dt + 0.5 * j * dt * dt+ self.qdd = self.qdd + j * dt+ return self.q, self.qd, self.qdd+++# ------------------------------------------------------------------------------------------------ planar base+@dataclass+class BaseLimits:+ """A planar base: speed / acceleration / jerk of the translation (per axis of the robot's own frame, `axes`, or+ on the norm, `norm`) and of the yaw. From body.toml [limits.base]."""++ speed: np.ndarray # (2,) or scalar for norm+ accel: np.ndarray+ jerk: np.ndarray+ yaw_rate: float+ yaw_accel: float+ yaw_jerk: float+ mode: str = "axes"++ @classmethod+ def of(cls, L: dict) -> "BaseLimits":+ mode = L.get("mode", "norm")+ f = (lambda k: np.asarray(L[k], float)) if mode == "axes" else (lambda k: float(np.max(L[k])))+ return cls(f("speed_m_s"), f("accel_m_s2"), f("jerk_m_s3"), float(L["yaw_rate_rad_s"]),+ float(L["yaw_accel_rad_s2"]), float(L["yaw_jerk_rad_s3"]), mode)++ def table(self) -> dict:+ r = lambda x: np.round(np.asarray(x, float), 4).tolist()+ return dict(mode=self.mode, speed_m_s=r(self.speed), accel_m_s2=r(self.accel), jerk_m_s3=r(self.jerk),+ yaw_rate_rad_s=self.yaw_rate, yaw_accel_rad_s2=self.yaw_accel, yaw_jerk_rad_s3=self.yaw_jerk)+++def _clipn(v, lim, norm):+ if not norm:+ return np.clip(v, -lim, lim)+ n = float(np.linalg.norm(v))+ return v if n <= lim or n == 0.0 else v * (lim / n)+++def _sqrtn(err, k, dlim, norm):+ """the sqrt law (limits._sqrt_ctrl) per component, or on the vector's length along its direction"""+ if not norm:+ return AL._sqrt_ctrl(err, k, dlim)+ n = float(np.linalg.norm(err))+ if n == 0.0:+ return np.zeros_like(err)+ return err / n * float(AL._sqrt_ctrl(np.array([n]), k, dlim)[0])+++class PlanarBase:+ """The jerk-limited setpoint generator of a planar base (x, y in the mount frame; yaw). The translation is limited+ in the robot's own frame (rotated by the setpoint's yaw), per axis ("axes": the vendors' chassis SDKs limit the+ commanded vx, vy, wz separately) or on the norm ("norm"); the yaw as one joint. The same cascade as+ limits.JerkLimiter (position -> velocity -> acceleration -> jerk, sqrt laws, the velocity guard)."""++ KP, KV, BRAKE = AL.JerkLimiter.KP, AL.JerkLimiter.KV, AL.JerkLimiter.BRAKE++ def __init__(self, lim: BaseLimits, dt: float):+ self.lim, self.dt = lim, float(dt)+ self.norm = lim.mode != "axes"+ self.reset(np.zeros(3))++ def reset(self, q, qd=None):+ """q: (x, y, yaw) in the mount frame; qd: their time derivatives (mount frame)."""+ q = np.asarray(q, float)+ qd = np.zeros(3) if qd is None else np.asarray(qd, float)+ self.p, self.yaw = q[:2].copy(), float(q[2])+ c, s = math.cos(self.yaw), math.sin(self.yaw)+ self.v = np.array([c * qd[0] + s * qd[1], -s * qd[0] + c * qd[1]]) # body frame+ self.a = np.zeros(2)+ self.w, self.wd = float(qd[2]), 0.0++ def state(self):+ """(q, qd, qdd) in the mount frame: x, y, yaw."""+ c, s = math.cos(self.yaw), math.sin(self.yaw)+ R = np.array([[c, -s], [s, c]])+ v, a = R @ self.v, R @ self.a+ return np.r_[self.p, self.yaw], np.r_[v, self.w], np.r_[a, self.wd]++ def _axis(self, e, rd, v, a, V, A, J, norm):+ dt = self.dt+ Vg = V - J * dt * dt - A * dt # one step of jerk and of acceleration (discrete overshoot)+ if norm: # the error left once the acceleration has ramped to zero+ na = float(np.linalg.norm(a)) # (relative to the reference moving at rd)+ if na > 0.0:+ t = na / J+ e = e - ((v - rd) * t + 0.5 * a * t * t - a / na * J * t ** 3 / 6.0)+ else:+ t = np.abs(a) / J+ e = e - ((v - rd) * t + 0.5 * a * t * t - np.sign(a) * J * t ** 3 / 6.0)+ if norm:+ n_e = float(np.linalg.norm(e))+ sp = min(self.KP * n_e, float(brake_speed(n_e, self.BRAKE * A, J)))+ v_pos = e / n_e * sp if n_e > 0 else np.zeros_like(e)+ else:+ v_pos = np.sign(e) * np.minimum(self.KP * np.abs(e), brake_speed(np.abs(e), self.BRAKE * A, J))+ v_cmd = _clipn(rd + v_pos, Vg, norm)+ a_cmd = _clipn(_sqrtn(v_cmd - v, self.KV, J, norm), A, norm)+ if norm: # the velocity guard along the motion+ sp = float(np.linalg.norm(v))+ if sp > 0.0:+ u = v / sp+ ap = float(a_cmd @ u)+ cap = math.sqrt(2.0 * J * max(0.0, Vg - sp))+ if ap > cap:+ a_cmd = a_cmd - (ap - cap) * u+ else:+ room_up, room_dn = np.maximum(0.0, Vg - v), np.maximum(0.0, Vg + v)+ a_cmd = np.clip(a_cmd, -np.sqrt(2.0 * J * room_dn), np.sqrt(2.0 * J * room_up))+ j = _clipn((a_cmd - a) / dt, J, norm)+ return j++ def step(self, r, rd=None):+ """advance one step towards the reference r = (x, y, yaw) moving at rd; returns (q, qd, qdd) (mount frame)"""+ L, dt = self.lim, self.dt+ r = np.asarray(r, float)+ rd = np.zeros(3) if rd is None else np.asarray(rd, float)+ jw = self._axis(np.array([r[2] - self.yaw]), np.array([rd[2]]), np.array([self.w]), np.array([self.wd]),+ L.yaw_rate, L.yaw_accel, L.yaw_jerk, False)[0]+ c, s = math.cos(self.yaw), math.sin(self.yaw)+ Rt = np.array([[c, s], [-s, c]]) # mount -> body frame+ e_b, rd_b = Rt @ (r[:2] - self.p), Rt @ rd[:2]+ j = self._axis(e_b, rd_b, self.v, self.a, L.speed, L.accel, L.jerk, self.norm)+ v_new = self.v + self.a * dt + 0.5 * j * dt * dt+ dp_b = self.v * dt + 0.5 * self.a * dt * dt + j * dt ** 3 / 6.0+ self.a = self.a + j * dt+ yaw_mid = self.yaw + 0.5 * self.w * dt+ cm, sm = math.cos(yaw_mid), math.sin(yaw_mid)+ self.p = self.p + np.array([cm * dp_b[0] - sm * dp_b[1], sm * dp_b[0] + cm * dp_b[1]])+ self.v = v_new+ self.yaw += self.w * dt + 0.5 * self.wd * dt * dt + jw * dt ** 3 / 6.0+ self.w += self.wd * dt + 0.5 * jw * dt * dt+ self.wd += jw * dt+ return self.state()+++# ------------------------------------------------------------------------------------------------ the servo+class Servo:+ """The servo of one robot's commanded coordinates x (a rig's controlled vector u, or the part of it that is+ positions) in a compiled model: joint targets q = M x + c.++ Every physics step (`track`): the reference (r, rd) passes the setpoint generator (SetpointGenerator on the joint+ coordinates `jix`, PlanarBase on the base coordinates `bix` = (x, y, yaw)); the joint setpoint (q_sp, qd_sp,+ qdd_sp) = M (x_sp, xd_sp, xdd_sp) + c; the torque tau = kp (q_sp - q) + kd (qd_sp - qd) + bias (gravity, Coriolis)+ + M(q) qdd_sp (inertia feed-forward); then the output stage (Actuators.write). Coordinates of x that map to no+ joint (all-zero columns of M, e.g. a legged robot's walking command) are not servoed here."""++ def __init__(self, model, qadr, vadr, act: Actuators, M, c, kp, kd, dt, joint_lim: AL.ArmLimits | None,+ jix=(), base: BaseLimits | None = None, bix=(), feedforward=True):+ self.m = model+ self.qadr, self.vadr = np.asarray(qadr, int), np.asarray(vadr, int)+ self.act = act+ self.M, self.c = np.asarray(M, float), np.asarray(c, float)+ self.kp, self.kd = np.asarray(kp, float), np.asarray(kd, float)+ self.dt = float(dt)+ self.jix, self.bix = np.asarray(jix, int), np.asarray(bix, int)+ self.n = self.M.shape[1]+ self.lim = joint_lim+ self.jl = SetpointGenerator(joint_lim, dt) if len(self.jix) else None+ self.base = PlanarBase(base, dt) if len(self.bix) else None+ self.ff = feedforward+ self.ready = False+ self._acc = np.zeros(model.nv)+ self._f = np.zeros(model.nv)+ self.x = np.zeros(self.n)+ self.xd = np.zeros(self.n)+ self.xdd = np.zeros(self.n)+ self.peak = dict(vel=np.zeros(self.n), acc=np.zeros(self.n)) # |setpoint| peaks (conformance)++ def reset(self, x, xd=None):+ """The setpoint generator at x (moving at xd), at rest in acceleration: after a teleport, at the start."""+ x = np.asarray(x, float)+ xd = np.zeros(self.n) if xd is None else np.asarray(xd, float)+ if self.jl is not None:+ self.jl.reset(x[self.jix], xd[self.jix])+ if self.base is not None:+ self.base.reset(x[self.bix], xd[self.bix])+ self.x, self.xd, self.xdd = x.copy(), xd.copy(), np.zeros(self.n)+ self.act.reset()+ self.ready = True++ def setpoint(self, r, rd):+ """one step of the setpoint generator towards (r, rd): (x_sp, xd_sp, xdd_sp)"""+ r, rd = np.asarray(r, float), np.asarray(rd, float)+ x, xd, xdd = r.copy(), rd.copy(), np.zeros(self.n)+ if self.jl is not None:+ q, qd, qdd = self.jl.step(r[self.jix], rd[self.jix])+ x[self.jix], xd[self.jix], xdd[self.jix] = q, qd, qdd+ if self.base is not None:+ q, qd, qdd = self.base.step(r[self.bix], rd[self.bix])+ x[self.bix], xd[self.bix], xdd[self.bix] = q, qd, qdd+ self.x, self.xd, self.xdd = x, xd, xdd+ np.maximum(self.peak["vel"], np.abs(xd), out=self.peak["vel"])+ np.maximum(self.peak["acc"], np.abs(xdd), out=self.peak["acc"])+ return x, xd, xdd++ def track(self, d, r, rd, extra_tau=None):+ """one physics step: setpoint, servo torque, output stage (writes d.ctrl of this servo's motors)"""+ if not self.ready:+ raise RuntimeError("servo not reset (rig.place / rig.sync first)")+ x, xd, xdd = self.setpoint(r, rd)+ q_sp, qd_sp, qdd_sp = self.M @ x + self.c, self.M @ xd, self.M @ xdd+ tau = self.kp * (q_sp - d.qpos[self.qadr]) + self.kd * (qd_sp - d.qvel[self.vadr]) + d.qfrc_bias[self.vadr]+ if self.ff:+ import mujoco as mj+ self._acc[:] = 0.0+ self._acc[self.vadr] = qdd_sp+ mj.mj_mulM(self.m, d, self._f, self._acc)+ tau = tau + self._f[self.vadr]+ if extra_tau is not None:+ tau = tau + extra_tau+ return self.act.write(d, tau)+++def check_row(u, u_prev, u_prev2, LO, HI, VEL, ACC, dt, base: BaseLimits | None = None, tol=1e-6):+ """A target row of a controlled vector against the limits: the ranges, the per-step speeds (|du| <= VEL dt) and,+ given u_prev2, the accelerations (|second difference| <= ACC dt^2). base: the limits of a planar base at u[0:3]+ (x, y, yaw): its translation checked on the norm, or per axis in the robot's frame (rotated by u_prev's yaw).+ Returns None or the reason."""+ u, up = np.asarray(u, float), np.asarray(u_prev, float)+ LO, HI, VEL = np.asarray(LO, float), np.asarray(HI, float), np.asarray(VEL, float)+ if u.shape != LO.shape or not np.all(np.isfinite(u)):+ return f"a target must be {len(LO)} finite numbers"+ bad = (u < LO - 1e-9) | (u > HI + 1e-9)+ if bad.any():+ return f"outside the range at {np.nonzero(bad)[0].tolist()}"+ du = u - up+ dd = None if u_prev2 is None else du - (up - np.asarray(u_prev2, float))+ over = np.abs(du) > VEL * dt * (1 + tol) + 1e-12+ if base is not None:+ over[0:2] = False+ why = _base_problem(du[0:2], up[2], base.speed, base.mode, dt, tol)+ if why:+ return "the base speed limit"+ if over.any():+ return f"a per-step speed limit at {np.nonzero(over)[0].tolist()}"+ if dd is not None and ACC is not None:+ over = np.abs(dd) > np.asarray(ACC, float) * dt * dt * (1 + tol) + 1e-12+ if base is not None:+ over[0:2] = False+ if _base_problem(dd[0:2], up[2], base.accel, base.mode, dt * dt, tol):+ return "the base acceleration limit"+ if over.any():+ return f"an acceleration limit at {np.nonzero(over)[0].tolist()}"+ return None+++def _base_problem(dxy, yaw, lim, mode, scale, tol):+ if mode != "axes":+ return math.hypot(*dxy) > float(np.max(lim)) * scale * (1 + tol) + 1e-12+ c, s = math.cos(yaw), math.sin(yaw)+ b = np.array([c * dxy[0] + s * dxy[1], -s * dxy[0] + c * dxy[1]])+ return bool(np.any(np.abs(b) > np.asarray(lim, float) * scale * (1 + tol) + 1e-12))+++# ------------------------------------------------------------------------------------------------ rig layouts+def wheeled_layout(model, rig, decl: dict, phys_dt: float):+ """The servo of a rig with the wheeled humanoid's controlled vector u = [base x, y, yaw, lift, waist, arm 0..6]+ (bodies/wheeled_humanoid, galaxea_r1pro, tianji_marvin_pro): the joint coordinates (lift, waist, arm: those that+ move a joint) through SetpointGenerator with [limits.lift / waist / arm]'s speed, acceleration and jerk, the base+ through PlanarBase ([limits.base]; none when its kind is "absent"). Returns (servo, ACC: the per-coordinate+ acceleration limits for check_row, the base limits or None)."""+ L = decl["limits"]+ moves = np.any(np.abs(rig.M) > 0, axis=0)+ jix = [k for k in range(3, 12) if moves[k]]+ has_base = L["base"].get("kind") != "absent" and moves[0:3].all()+ base = BaseLimits.of(L["base"]) if has_base else None+ group = {3: "lift", 4: "waist"}+ q = lambda k, key: (_arr(L[group.get(k, "arm")].get(key), 7) if group.get(k, "arm") == "arm"+ else _arr(L[group[k]].get(key)))+ acc = np.full(12, 0.0)+ jerk = np.full(12, 0.0)+ for k in range(3, 12):+ a, j = q(k, "accel_rad_s2"), q(k, "jerk_rad_s3")+ acc[k] = np.inf if a is None else (a[k - 5] if k >= 5 else a[0])+ jerk[k] = np.inf if j is None else (j[k - 5] if k >= 5 else j[0])+ if base is not None:+ acc[0:2] = base.accel if base.mode == "axes" else float(base.accel)+ acc[2] = base.yaw_accel+ ji = np.array(jix, int)+ fin = lambda x: None if not np.all(np.isfinite(x)) else x+ lim = AL.ArmLimits(decl["body"]["name"], decl["body"]["title"] + " [u]", rig.LO[ji], rig.HI[ji], rig.VEL[ji],+ fin(acc[ji]), fin(jerk[ji]), np.full(len(ji), np.inf), None, dict(decl.get("sources", {})))+ act = Actuators(model, rig.aid, rig.vadr, rig.tau_lim, phys_dt)+ servo = Servo(model, rig.qadr, rig.vadr, act, rig.M, rig.c, rig.kp, rig.kd, phys_dt, lim, jix=jix, base=base,+ bix=(0, 1, 2) if base is not None else ())+ return servo, acc, base+++def legged_layout(model, rig, decl: dict, phys_dt: float, upper_keys: list, leg_keys: list, planar: dict | None):+ """The servos of a legged rig (bodies/unitree_g1, unitree_h1): the upper body's commanded coordinates (u[3:]:+ waist and arm joints) through SetpointGenerator at the joints' speed limits (Unitree publishes no acceleration+ or jerk: none declared, the motor curves bound them), the planar copy's base (planar: the [walk.planning] model)+ through PlanarBase; the output stages with the motors' torque-speed curves ([motors]: upper_keys / leg_keys name+ each joint's [motors.assign] entry; None = no curve). Returns (upper servo, legs Actuators or None, ACC)."""+ moves = np.any(np.abs(rig.M) > 0, axis=0)+ jix = [k for k in range(3, 12) if moves[k]]+ ji = np.array(jix, int)+ lim = AL.ArmLimits(decl["body"]["name"], decl["body"]["title"] + " [u]", rig.LO[ji], rig.HI[ji], rig.VEL[ji],+ None, None, np.full(len(ji), np.inf), None, dict(decl.get("sources", {})))+ base = None+ if planar is not None:+ base = BaseLimits(float(planar["speed_m_s"]), float(planar["accel_m_s2"]), 25.0 * float(planar["accel_m_s2"]),+ float(planar["yaw_rate_rad_s"]), float(planar["yaw_accel_rad_s2"]),+ 25.0 * float(planar["yaw_accel_rad_s2"]), "norm")+ env = unitree_envelope(decl, upper_keys)+ act = Actuators(model, rig.aid, rig.vadr, rig.tau_lim, phys_dt, envelope=env)+ servo = Servo(model, rig.qadr, rig.vadr, act, rig.M, rig.c, rig.kp, rig.kd, phys_dt, lim, jix=jix, base=base,+ bix=(0, 1, 2) if base is not None else ())+ legs = None+ if leg_keys:+ legs = Actuators(model, rig.laid, rig.lvadr, rig.ltau, phys_dt, envelope=unitree_envelope(decl, leg_keys))+ acc = np.full(12, np.inf)+ if base is not None:+ acc[0:2], acc[2] = base.accel, base.yaw_accel+ return servo, legs, acc+++# ------------------------------------------------------------------------------------------------ walking command+class WalkCommand:+ """A legged robot's walking command (vx, vy, wz in the robot's frame): clipped to the range the real robot's+ deployment accepts ([limits.walk] command_max: Unitree's joystick limits) and changed by at most command_accel+ per second."""++ def __init__(self, L: dict, dt: float):+ self.max = np.asarray(L["command_max"], float)+ self.step_max = np.asarray(L["command_accel"], float) * float(dt)+ self.cmd = np.zeros(3)++ def reset(self):+ self.cmd = np.zeros(3)++ def __call__(self, req):+ req = np.clip(np.asarray(req, float), -self.max, self.max)+ self.cmd = self.cmd + np.clip(req - self.cmd, -self.step_max, self.step_max)+ return self.cmddiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/sources.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/sources.pynew file mode 100644index 0000000000..c759e432d4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/sources.py@@ -0,0 +1,66 @@+"""The robot library's declaration rules (bodies/README.md "准入"), stdlib only: what bodies/servo.py, the+conformance test (bodies/conformance.py) and the CI check (ci_checks/check-robot-limits.py) agree on.++Every limit a robot declares in body.toml [limits.<group>] has a source in [limits.<group>.source]: a reference to+[sources] ("S2", "S2 x 1.5 (S5)"), or "ESTIMATE: <method>" (an unpublished value we chose, labelled), "DERIVED:+<method>" (computed from published facts), or "NOT PUBLISHED: <why>" (the quantity is not limited because nobody+publishes it; then it must have no value). Each kind of group declares the quantities of REQUIRED (a value or a NOT+PUBLISHED source); a group with kind = "absent" is a part the robot does not have.+"""+from __future__ import annotations++import re++TRUSTED = ("Servo", "Actuators", "PlanarBase", "WalkCommand", "SetpointGenerator", "JerkLimiter",+ "TorqueRateLimiter")+SOURCE_RE = re.compile(r"^(S\d+\b|ESTIMATE\b|NOT PUBLISHED\b|DERIVED\b)")+QUANTITIES = { # body.toml key -> what it is (the conformance check's list)+ "speed_rad_s": "joint speed", "accel_rad_s2": "joint acceleration", "jerk_rad_s3": "joint jerk",+ "torque_nm": "joint torque", "torque_rate_nm_s": "joint torque rate",+ "speed_m_s": "base speed", "accel_m_s2": "base acceleration", "jerk_m_s3": "base jerk",+ "yaw_rate_rad_s": "base yaw rate", "yaw_accel_rad_s2": "base yaw acceleration", "yaw_jerk_rad_s3": "base yaw jerk",+ "command_max": "walking command range", "command_accel": "walking command rate",+}+REQUIRED = { # per kind of limit group: what must be declared (a value, or a source entry saying why there is none)+ "joints": ("speed_rad_s", "accel_rad_s2", "jerk_rad_s3", "torque_nm"),+ "base": ("speed_m_s", "accel_m_s2", "jerk_m_s3", "yaw_rate_rad_s", "yaw_accel_rad_s2", "yaw_jerk_rad_s3"),+ "walk": ("command_max", "command_accel"),+ "gantry": ("speed_m_s", "accel_m_s2", "jerk_m_s3"), # linear axes, each limited on its own (per axis)+}+++def source_problems(decl: dict) -> list[str]:+ """Every declared limit has a source: [limits.<group>.source] maps each quantity of the group to a reference of+ [sources] ("S2", "S2 x 1.5 (S5)") or to "ESTIMATE: <method>", "DERIVED: <method>" or "NOT PUBLISHED: <why>";+ each kind of group declares the quantities of REQUIRED (a value, or a NOT PUBLISHED source). Returns problems."""+ out, srcs = [], set((decl.get("sources") or {}).keys())+ if not srcs:+ out.append("no [sources]")+ for g, L in (decl.get("limits") or {}).items():+ if not isinstance(L, dict):+ continue+ if "kind" not in L and not any(q in QUANTITIES for q in L):+ continue # not a limit group of joints or a base (e.g. [limits.cartesian])+ kind = L.get("kind") or ("base" if g == "base" else "walk" if g == "walk" else "gantry" if g == "gantry"+ else "joints")+ if kind == "absent": # the robot has no such part (e.g. a fixed stand's base)+ continue+ src = L.get("source")+ if not isinstance(src, dict):+ out.append(f"[limits.{g}] has no source table [limits.{g}.source]")+ continue+ for q in REQUIRED.get(kind, ()):+ if q not in L and not str(src.get(q, "")).startswith("NOT PUBLISHED"):+ out.append(f"[limits.{g}] {q}: neither a value nor 'NOT PUBLISHED: <why>' in its source table")+ for q in L:+ if q in QUANTITIES:+ s = str(src.get(q, ""))+ if not SOURCE_RE.match(s):+ out.append(f"[limits.{g}] {q}: source {s!r} is not S<k>, ESTIMATE:, DERIVED: or NOT PUBLISHED:")+ for ref in re.findall(r"\bS\d+\b", s):+ if ref not in srcs:+ out.append(f"[limits.{g}] {q}: {ref} is not in [sources]")+ for q, s in src.items():+ if str(s).startswith("NOT PUBLISHED") and q in L:+ out.append(f"[limits.{g}] {q}: has a value but its source says NOT PUBLISHED")+ return outdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/LICENSE b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/LICENSEnew file mode 100644index 0000000000..62637c8d14--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/LICENSE@@ -0,0 +1,27 @@+Copyright (c) 2016-2023 HangZhou YuShu TECHNOLOGY CO.,LTD. ("Unitree Robotics")+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++* Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/agile.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/agile.pynew file mode 100644index 0000000000..db0a773025--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/agile.py@@ -0,0 +1,145 @@+"""NVIDIA WBC-AGILE's velocity-height walking policy for the G1 (optional; body.toml [walk.agile]): a legs-only walking+and balance policy, trained while the arms and the waist moved, that a sport may choose instead of Unitree's policy+(body.py WalkPolicy, the default) or FALCON (falcon.py):++ rig = B.rig(model, prefix, hand="paddle", walker="agile")++Source: nvidia-isaac/WBC-AGILE (Apache-2.0, Copyright (c) NVIDIA CORPORATION & AFFILIATES; policy/LICENSE.agile), the+released LEAPP bundle agile/data/policy/velocity_height_g1/leapp/Velocity-Height-G1-History-v0 (S9); H. Zhao et al.,+"AGILE: A Comprehensive Workflow for Humanoid Loco-Manipulation Learning", arXiv:2603.20147. Trained with PPO in Isaac+Lab on the 29-DOF G1 (physics 200 Hz, policy 50 Hz), legs only: the waist yaw (within +-15 degrees) and the arms+moved to random targets while it stood, the waist roll and pitch held at 0; while it walked, the arms and the waist+went to their default pose (all 0), so walking with the arms elsewhere (the library's rest pose too) or the waist+turned further is outside its training. policy/agile_g1_velocity_height.npz holds the ONNX graph's weights and+constants unchanged (float32, evaluated in float64; tools/export_agile.py), the joint order of the bundle, and a+parity fixture: graph inputs (with their histories) and the outputs onnxruntime gave for them (parity() checks this+port against them).++The graph builds its observation itself and keeps a 5-frame history of each term, fed back every tick (LEAPP feedback):+each tick the oldest frame is dropped and the new one appended, then the terms' histories (oldest frame first) are+concatenated, 5 x 80 = 400 numbers:+ velocity-height command (vx, vy, wz, height) 4 pelvis angular velocity (pelvis frame) 3+ gravity (0, 0, -1) in the pelvis frame 3 q - default (29 joints, Isaac Lab order) 29+ joint speeds x 0.1 29 last action, clipped to +-10 12+MLP 400 -> 512 -> 256 -> 128 (ELU) -> 12: the action (Isaac Lab's leg order); targets = default + scale x action,+clipped to +-6 rad. graph() is that computation; step() maps Unitree's motor order to the bundle's by joint name.++On the rig (body.py G1Rig) and under the arbiter (bodies/control/arbiter.py) the legs follow AGILE's 12 targets on its+PD gains (body.toml [walk.agile] kp, kd: the graph's gain outputs); the waist and the arms stay the sport's (the rig's+u, the arbiter's plans or holds). AGILE has no waist or arm output and no residual: it reads all 29 joints' measured+positions and speeds.++The command as in training: clipped to the training ranges (after [limits.walk]); a command (vx, vy, wz) of norm+below 0.1 is 0 (training zeroed such samples); height 0.72 m (training's walking height). The history starts as in+training (Isaac Lab's history buffer: the first frame fills it, the last action is 0) after place(), a kick and an+arbiter hand-back. NVIDIA's MuJoCo runner starts from the bundle's initial values instead: the export run's first frame+after a reset (9 degrees of tilt, randomised legs, a walking command (0.20, 0.16, 0.23) in all five frames). Measured on+this model: an in-place turn below about 0.7 rad/s barely turns (0.35 rad/s turns 0.03-0.05 rad/s after the first+second; walking at 0.2 m/s or faster it turns as commanded), and it stands with the pelvis at 0.67-0.70 m (FALCON+0.74 m). Deterministic: plain float64 numpy.+"""++from __future__ import annotations++import math+from pathlib import Path++import numpy as np++from .body import ARM, LEGS, TORSO+from .falcon import mlp++HERE = Path(__file__).resolve().parent+UNITREE = LEGS + TORSO + [f"{s}_{a}_joint" for s in ("left", "right") for a in ARM] # Unitree's motor order (29)+TERMS = ("velocity_height_commands", "base_ang_vel", "projected_gravity", "joint_pos", "joint_vel", "actions")+INPUTS = ("base_velocity", "robot_root_ang_vel_b", "robot_root_quat_w", "robot_joint_pos", "robot_joint_vel")+++class Agile:+ """AGILE for one robot: the six term histories and the last action; step() every 20 ms. For the rig like body.py+ WalkPolicy (default: the legs' stance, reset, state); its step() takes falcon.py's arguments."""++ def __init__(self, decl):+ A = decl["walk"]["agile"]+ z = np.load(HERE / A["weights"])+ self.layers = [(z[f"w{k}"].astype(float), z[f"b{k}"].astype(float)) for k in range(4)]+ self.q0, self.dq0 = z["joint_pos_default"].astype(float), z["joint_vel_default"].astype(float)+ self.s_vel, self.act_clip = float(z["joint_vel_scale"]), float(z["action_clip"])+ self.scale, self.offset = z["action_scale"].astype(float), z["action_offset"].astype(float)+ self.t_min, self.t_max = z["target_min"].astype(float), z["target_max"].astype(float)+ self.gravity = z["gravity"].astype(float)+ self.fixture = {k[len("parity_") :]: z[k] for k in z.files if k.startswith("parity_")}+ self.ix = np.array([UNITREE.index(n) for n in z["obs_joints"]]) # Unitree index of each graph joint (29)+ legs = list(z["action_joints"])+ self.out = np.array([legs.index(n) for n in LEGS]) # Unitree leg i <- graph output out[i]+ self.default = self.offset[self.out] # the legs' stance (as WalkPolicy.default)+ self.kp, self.kd = np.array(A["kp"], float), np.array(A["kd"], float) # the legs' PD (12)+ self.history_len = int(A["history"])+ self.height = float(A["base_height_m"])+ self.cmd_min, self.cmd_max = np.array(A["command_min"], float), np.array(A["command_max"], float)+ self.cmd_min_norm = float(A["command_min_norm"])+ self.sizes = [4, 3, 3, len(UNITREE), len(UNITREE), len(LEGS)] # one frame of each term+ self.reset()++ def reset(self):+ self.action = np.zeros(len(LEGS))+ self.hist = tuple(np.zeros((self.history_len, n)) for n in self.sizes)+ self.fresh = True # the next tick's frame fills the history (Isaac Lab's history buffer after a reset)+ self.targets = self.default.copy()++ def command(self, cmd):+ """The walking command as AGILE was trained on it: clipped to its ranges, a small command zeroed."""+ c = np.clip(np.asarray(cmd, float)[:3], self.cmd_min, self.cmd_max)+ return c if math.sqrt(c @ c) >= self.cmd_min_norm else np.zeros(3)++ def frame(self, cmd4, gyro, quat_xyzw, q, dq, last_action):+ """One frame of the six terms, as the graph computes it (graph's order: Isaac Lab joints, quaternion x, y, z,+ w); gravity by Isaac Lab's quat_apply_inverse: v - w t + xyz x t, t = 2 xyz x v."""+ xyz, w = np.asarray(quat_xyzw[:3], float), float(quat_xyzw[3])+ t = 2.0 * np.cross(xyz, self.gravity)+ grav = self.gravity - w * t + np.cross(xyz, t)+ return (+ np.asarray(cmd4, float),+ np.asarray(gyro, float),+ grav,+ np.asarray(q, float) - self.q0,+ (np.asarray(dq, float) - self.dq0) * self.s_vel,+ np.clip(last_action, -self.act_clip, self.act_clip),+ )++ def graph(self, cmd4, gyro, quat_xyzw, q, dq, last_action, hist):+ """The ONNX graph: the new frame appended to each term's history (the oldest dropped), the network on the+ histories. Returns (targets 12, action 12, histories), the legs in the graph's order."""+ hist = tuple(np.vstack([h[1:], f]) for h, f in zip(hist, self.frame(cmd4, gyro, quat_xyzw, q, dq, last_action)))+ action = mlp(self.layers, np.concatenate([h.ravel() for h in hist]))+ return np.clip(self.offset + self.scale * action, self.t_min, self.t_max), action, hist++ def step(self, quat, gyro, q, dq, cmd, arms=None, waist_yaw=None):+ """One policy tick. quat (w, x, y, z) and gyro (pelvis frame) of the pelvis; q, dq: the 29 joints in Unitree's+ motor order (measured); cmd: vx, vy, wz (robot frame). arms, waist_yaw: not used (falcon.py's arguments).+ Returns the 12 leg targets (Unitree's order)."""+ w, x, y, z = quat+ q, dq = np.asarray(q, float), np.asarray(dq, float)+ inputs = (np.r_[self.command(cmd), self.height], gyro, (x, y, z, w), q[self.ix], dq[self.ix], self.action)+ if self.fresh:+ self.hist = tuple(np.tile(f, (self.history_len, 1)) for f in self.frame(*inputs))+ self.fresh = False+ t, self.action, self.hist = self.graph(*inputs, self.hist)+ self.targets = t[self.out]+ return self.targets++ def state(self):+ """The policy's memory (last action, histories, fresh): for hashing and copying."""+ return np.r_[self.action, np.concatenate([h.ravel() for h in self.hist]), self.fresh]++ def parity(self):+ """max |this port - onnxruntime| over the fixture stored with the weights (tools/export_agile.py): all the+ graph's outputs (targets, action, the six histories)."""+ F = self.fixture+ err = 0.0+ for k in range(len(F["joint_pos"])):+ ins = [F[n][k] for n in INPUTS + ("last_action_in",)] + [tuple(F[f"h_policy_{n}_in"][k] for n in TERMS)]+ t, a, hist = self.graph(*ins)+ ref = [F["joint_pos"][k], F["last_action_out"][k]] + [F[f"h_policy_{n}_out"][k] for n in TERMS]+ err = max(err, max(float(np.max(np.abs(g - r))) for g, r in zip([t, a, *hist], ref)))+ return errdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/body.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/body.pynew file mode 100644index 0000000000..d5d5ac08d9--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/body.py@@ -0,0 +1,507 @@+"""The Unitree G1 body (body.toml): MJCF assembly, the walking policy, the waist/arm servo, the kick, the controlled+vector u.++ from bodies import load_body+ B = load_body("unitree_g1")+ B.mount(scene_root, prefix="A_", pos=(0, -1.6, -0.76), yaw=pi / 2, hand="paddle") # into a scene's XML tree+ rig = B.rig(model, prefix="A_", hand="paddle") # after compiling (walker="falcon" / "falcon_legs" / "agile":+ # optional policies)+ rig.begin_step(d, u) # every 10 ms control step (the policy runs every 20 ms)+ rig.apply(d, u_prev, u, j, u_prev2) # every physics substep+ rig.kick(d, foot="right", speed=3.0) # a kick (kick.py); the walking policy resumes after it++The controlled vector u (body.toml [dof]): [walk_vx, walk_vy, walk_wz, waist_pitch, waist_yaw, arm_0 .. arm_6].+walk_*: the walking policy's velocity command in the robot's body frame; the legs are the policy's (or the kick+controller's) and are not in u. Rig.qadr / vadr / M / joint_targets cover the upper body (waist yaw, roll, pitch,+the hand arm, the other arm), as the wheeled humanoid's Rig, so the whole-body planner works on both bodies; the+legs have their own addresses (lqadr, lvadr, laid).+The same Rig drives a fixed-base copy (robot_only_xml(fixed_base=True): the pelvis welded at the origin) and a planar+copy (fixed_base="planar": no legs, the pelvis on two slides and a hinge at the standing height; the whole-body+planner's model and twin): there u[0:3] are the pelvis position (x, y, yaw), as the wheeled humanoid's base, a+stand-in for where walking puts the pelvis; neither copy has legs or a policy.+"""+from __future__ import annotations++import copy+import math+import tomllib+import xml.etree.ElementTree as ET+from pathlib import Path++import numpy as np++from .. import selfcollision as SC+from .. import servo as SV++HERE = Path(__file__).resolve().parent+HANDS = HERE.parent / "hands"+NAME_ATTRS = ("name", "joint", "body", "body1", "body2", "geom", "geom1", "geom2", "site", "mesh", "material",+ "class", "childclass", "target", "texture", "tendon", "actuator")+LEGS = [f"{s}_{j}_joint" for s in ("left", "right") for j in ("hip_pitch", "hip_roll", "hip_yaw", "knee",+ "ankle_pitch", "ankle_roll")]+ARM = ["shoulder_pitch", "shoulder_roll", "shoulder_yaw", "elbow", "wrist_roll", "wrist_pitch", "wrist_yaw"]+TORSO = ["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"]+STAND_Z = 0.793 # the pelvis above the floor at the policy's default stance+PLAN_Z = 0.778 # ... where it settles standing or walking (the planar copy's height)+PLANAR = ["base_x", "base_y", "base_yaw"]+++def short(j):+ """'left_hip_pitch_joint' -> 'hip_pitch', 'waist_yaw_joint' -> 'waist_yaw' (body.toml [motors.assign] keys)."""+ s = j[:-len("_joint")] if j.endswith("_joint") else j+ for side in ("left_", "right_"):+ if s.startswith(side):+ return s[len(side):]+ return s+++def _toml(p):+ return tomllib.loads(Path(p).read_text())+++def _fmt(v):+ return " ".join(repr(float(x)) for x in v)+++def quat_z(yaw):+ return (math.cos(yaw / 2), 0.0, 0.0, math.sin(yaw / 2))+++class G1Body:+ kind = "legged"+ walkers = ("unitree", "falcon", "falcon_legs", "agile") # rig(..., walker=): Unitree's policy (the default),+ # FALCON (falcon.py; "falcon_legs": FALCON on the legs only)+ # or AGILE (agile.py)++ def __init__(self):+ self.decl = _toml(HERE / "body.toml")+ self.hands = _toml(HANDS / "hands.toml")+ self.name = self.decl["body"]["name"]+ self.revision = self.decl["body"]["revision"]+ self.dof = list(self.decl["dof"]["names"])+ W = self.decl["walk"]+ P = W["planning"] # the planner's base tracker (the planar copy): what+ self.base_speed, self.base_accel = float(P["speed_m_s"]), float(P["accel_m_s2"]) # walking really achieves+ self.yaw_rate, self.yaw_accel = float(P["yaw_rate_rad_s"]), float(P["yaw_accel_rad_s2"])+ self.plan_z = PLAN_Z+ C = self.decl["controller"]["step"]+ self.dt = C["control_dt_s"]+ self.substeps = int(round(self.dt / C["physics_dt_s"]))++ # ------------------------------------------------------------------ the template, renamed+ def _hand(self, hand, tag="hand"):+ h = self.hands[hand]+ body = copy.deepcopy(ET.parse(HANDS / h["file"]).getroot().find("worldbody").find("body"))+ contact = set(h.get("contact", []))+ for el in body.iter():+ if el.tag == "body" and el.get("name") == "hand":+ el.set("name", tag)+ elif el.get("name") is not None:+ if el.tag == "geom":+ c = el.get("name") in contact+ el.set("contype", "1" if c else "4")+ el.set("conaffinity", "1" if c else "0")+ el.set("name", f"{tag}_" + el.get("name"))+ elif el.tag == "geom":+ el.set("contype", "4"); el.set("conaffinity", "0")+ return body++ def _template(self, prefix, hand, arm, lod, accent, head_pitch, fixed_base=False):+ root = ET.parse(HERE / self.decl["body"]["model"]).getroot()+ meshdir = HERE / self.decl["body"]["meshes"][lod]+ if lod == "fine" and not meshdir.is_dir(): # the fine meshes are not in git (tools/make_model.py)+ meshdir, lod = HERE / self.decl["body"]["meshes"]["standard"], "standard"+ for m in root.find("asset").findall("mesh"):+ stem = Path(m.get("file")).stem+ m.set("file", str(meshdir / (stem + (".STL" if lod == "fine" else ".stl"))))+ if head_pitch is None:+ head_pitch = self.decl["mounts"]["head_pitch_rad"]+ for b in root.iter("body"):+ if b.get("name") == "head_cam":+ b.set("quat", _fmt((math.cos(head_pitch / 2), 0.0, math.sin(head_pitch / 2), 0.0)))+ if b.get("name") == "torso_link" and accent is not None:+ for g in b.findall("geom"):+ if g.get("mesh") == "g1_torso_link" and g.get("class") == "g1_visual":+ g.set("rgba", _fmt(accent))+ if hand:+ mount = next(b for b in root.iter("body") if b.get("name") == f"{arm}_mount")+ mount.append(self._hand(hand))+ if fixed_base:+ pelvis = root.find("worldbody").find("body")+ for j in pelvis.findall("freejoint"):+ pelvis.remove(j)+ for b in list(pelvis): # the legs go: the pelvis is welded (or planar)+ if b.tag == "body" and "hip" in (b.get("name") or ""):+ pelvis.remove(b)+ if fixed_base == "planar":+ for i, (n, typ, ax) in enumerate((("base_x", "slide", "1 0 0"), ("base_y", "slide", "0 1 0"),+ ("base_yaw", "hinge", "0 0 1"))):+ pelvis.insert(i, ET.Element("joint", name=n, type=typ, axis=ax, damping="0", armature="0.1"))+ for el in root.iter():+ for a in NAME_ATTRS:+ v = el.get(a)+ if v is not None:+ el.set(a, prefix + v)+ return root++ def joints(self, arm, fixed_base=False):+ other = "left" if arm == "right" else "right"+ upper = ["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"] + \+ [f"{arm}_{j}_joint" for j in ARM] + [f"{other}_{j}_joint" for j in ARM]+ return (PLANAR if fixed_base == "planar" else [] if fixed_base else LEGS) + upper++ def _effort(self, j):+ L = self.decl["limits"]+ if j in PLANAR: # the planar copy's stand-in for walking+ return 5000.0+ if j.startswith("waist"):+ return L["waist"]["torque_nm"][["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"].index(j)]+ for i, a in enumerate(ARM):+ if j.endswith(f"_{a}_joint"):+ return L["arm"]["torque_nm"][i]+ return L["leg"]["torque_nm"][LEGS.index(j) % 6]++ def mount(self, scene: ET.Element, prefix: str, pos, yaw: float, hand: str | None = "paddle", arm: str = "right",+ lod: str = "standard", accent=None, head_pitch=None, fixed_base: bool = False,+ self_collision: bool = True, **_) -> dict:+ """Add one G1 to a scene's XML tree. pos: the point on the floor under the pelvis; yaw: its facing (the robot's+ forward axis = world x rotated by yaw). The pelvis starts at the policy's stand height."""+ t = self._template(prefix, hand, arm, lod, accent, head_pitch, fixed_base)+ sc = SC.plan(t, self.decl["self_collision"], prefix=prefix) if self_collision else None # selfcollision.py+ for sec in ("default", "asset"):+ dst = scene.find(sec)+ if dst is None:+ dst = ET.SubElement(scene, sec)+ for el in t.find(sec):+ dst.append(el)+ pelvis = t.find("worldbody").find("body")+ z = PLAN_Z if fixed_base == "planar" else 0.0 if fixed_base else STAND_Z+ p = np.asarray(pos, float) + np.array([0.0, 0.0, z])+ pelvis.set("pos", _fmt(p))+ pelvis.set("quat", _fmt(quat_z(yaw)))+ scene.find("worldbody").append(pelvis)+ if sc is not None: # the robot's self-collision pairs (body.toml [self_collision])+ SC.add_pairs(scene, sc)+ act = scene.find("actuator")+ if act is None:+ act = ET.SubElement(scene, "actuator")+ for j in self.joints(arm, fixed_base):+ lim = self._effort(j)+ ET.SubElement(act, "motor", name=f"{prefix}m_{j}", joint=prefix + j, ctrlrange=f"{-lim!r} {lim!r}")+ return {**SC.info(sc), "prefix": prefix, "base": prefix + "pelvis", "hand": prefix + "hand" if hand else None,+ "tool_site": prefix + "hand_" + self.hands[hand]["site"] if hand else None,+ "contact_geoms": [prefix + "hand_" + g for g in self.hands[hand].get("contact", [])] if hand else [],+ "feet": [prefix + "left_foot_strike", prefix + "right_foot_strike"], "arm": arm,+ "cameras": [prefix + c for c in self.decl["mounts"]["cameras"]]}++ @staticmethod+ def guard_root(arm):+ """The forearm's link: the planner keeps it and everything below it out of a sport's keep-out boxes."""+ return f"{arm}_elbow_link"++ def robot_only_xml(self, hand="paddle", arm="right", lod="standard", meshdir: str | None = None,+ option: dict | None = None, header: str = "", fixed_base="planar",+ self_collision: bool = True) -> str:+ """The robot alone: by default the planar copy (the planner's model, a low-level player's model)."""+ root = ET.Element("mujoco", model=f"{self.name}_{hand}_robot_only")+ if header:+ root.append(ET.Comment(header))+ ET.SubElement(root, "compiler", angle="radian", autolimits="true", **({"meshdir": meshdir} if meshdir else {}))+ ET.SubElement(root, "option", **(option or {"timestep": "0.001", "integrator": "implicitfast"}))+ for sec in ("default", "asset", "worldbody"):+ ET.SubElement(root, sec)+ self.mount(root, "", (0.0, 0.0, 0.0), 0.0, hand=hand, arm=arm, lod=lod, fixed_base=fixed_base,+ self_collision=self_collision)+ if meshdir:+ for m in root.find("asset").findall("mesh"):+ m.set("file", Path(m.get("file")).name)+ ET.indent(root, space=" ")+ return ET.tostring(root, encoding="unicode") + "\n"++ def rig(self, model, prefix="", arm="right", hand="paddle", rest=None, walker="unitree"):+ return G1Rig(self, model, prefix, arm, hand, rest, walker)+++class WalkPolicy:+ """Unitree's walking policy (body.toml [walk]) for one robot: the observation, the LSTM memory, the leg targets. The+ network (LSTM 47 -> 64, Linear 64 -> 32, ELU, Linear 32 -> 12) runs in numpy (float64) from policy/motion.npz+ (tools/export_policy.py: the weights of Unitree's motion.pt, unchanged)."""++ def __init__(self, decl):+ W = decl["walk"]+ z = np.load(HERE / W["weights"])+ self.w_ih, self.w_hh = z["w_ih"].astype(float), z["w_hh"].astype(float)+ self.b = z["b_ih"].astype(float) + z["b_hh"].astype(float)+ self.w0, self.b0 = z["w0"].astype(float), z["b0"].astype(float)+ self.w2, self.b2 = z["w2"].astype(float), z["b2"].astype(float)+ self.nh = self.w_hh.shape[1]+ self.default = np.array(W["default_angles"], float)+ self.scale = float(W["action_scale"])+ S = W["obs_scales"]+ self.s_ang, self.s_pos, self.s_vel = S["ang_vel"], S["dof_pos"], S["dof_vel"]+ self.s_cmd = np.array(S["cmd"], float)+ self.period = float(W["gait_period_s"])+ self.reset()++ def reset(self):+ self.h = np.zeros(self.nh)+ self.c = np.zeros(self.nh)+ self.action = np.zeros(12)+ self.targets = self.default.copy()++ def net(self, x):+ g = self.w_ih @ x + self.w_hh @ self.h + self.b+ n = self.nh+ sig = lambda v: 1.0 / (1.0 + np.exp(-v))+ i, f, gg, o = sig(g[0:n]), sig(g[n:2 * n]), np.tanh(g[2 * n:3 * n]), sig(g[3 * n:4 * n])+ self.c = f * self.c + i * gg+ self.h = o * np.tanh(self.c)+ y = self.w0 @ self.h + self.b0+ y = np.where(y > 0, y, np.expm1(np.minimum(y, 0.0))) # ELU+ return self.w2 @ y + self.b2++ def step(self, quat, omega, q, qd, cmd, t):+ w, x, y, z = quat+ g = np.array([2 * (-z * x + w * y), -2 * (z * y + w * x), 1 - 2 * (w * w + z * z)])+ ph = (t % self.period) / self.period+ obs = np.concatenate([omega * self.s_ang, g, np.asarray(cmd) * self.s_cmd, (q - self.default) * self.s_pos,+ qd * self.s_vel, self.action, [math.sin(2 * math.pi * ph), math.cos(2 * math.pi * ph)]])+ self.action = self.net(obs)+ self.targets = self.action * self.scale + self.default+ return self.targets++ def state(self):+ """The policy's memory (LSTM state, last action): for hashing and copying."""+ return np.concatenate([self.h, self.c, self.action])+++class G1Rig:+ """One mounted G1 in a compiled model: upper-body addresses, limits and servo (as the wheeled humanoid's Rig), plus+ the legs: the walking policy, the kick, their PD."""++ def __init__(self, body: G1Body, model, prefix="", arm="right", hand="paddle", rest=None, walker="unitree"):+ import mujoco as mj+ if walker not in body.walkers:+ raise ValueError(f"unknown walker {walker!r}; one of {list(body.walkers)}")+ self.mj, self.B, self.m, self.prefix, self.arm, self.walker = mj, body, model, prefix, arm, walker+ D = body.decl+ jid = lambda n: mj.mj_name2id(model, mj.mjtObj.mjOBJ_JOINT, prefix + n)+ self.fixed_base = jid("left_hip_pitch_joint") < 0+ self.planar = jid("base_x") >= 0+ upper = (PLANAR if self.planar else []) + body.joints(arm, fixed_base=True)+ o = 3 if self.planar else 0 # the planar copy's base joints come first+ ids = [jid(j) for j in upper]+ if min(ids) < 0:+ raise ValueError(f"robot {prefix!r} not in the model")+ self.joints = upper+ self.qadr = np.array([model.jnt_qposadr[i] for i in ids])+ self.vadr = np.array([model.jnt_dofadr[i] for i in ids])+ self.aid = np.array([mj.mj_name2id(model, mj.mjtObj.mjOBJ_ACTUATOR, f"{prefix}m_{j}") for j in upper])+ self.tau_lim = model.actuator_ctrlrange[self.aid, 1].copy()+ # u -> upper-body joint targets: [waist yaw, roll, pitch, arm x 7, other arm x 7] = M @ u + c+ self.M = np.zeros((17 + o, 12))+ for k in range(o):+ self.M[k, k] = 1.0+ self.M[o + 0, 4] = 1.0 # waist yaw+ self.M[o + 2, 3] = 1.0 # waist pitch+ for i in range(7):+ self.M[o + 3 + i, 5 + i] = 1.0+ R = D["rest"]+ self.c = np.zeros(17 + o)+ self.c[o + 10:o + 17] = R["other_arm"]+ C, L = D["controller"], D["limits"]+ Pl = D["walk"]["planning"]+ base_kp, base_kd = (Pl["base_kp"], Pl["base_kd"]) if o else ([], [])+ self.kp = np.r_[base_kp, C["kp"]["waist"], C["kp"]["arm"], C["kp"]["arm"]]+ self.kd = np.r_[base_kd, C["kd"]["waist"], C["kd"]["arm"], C["kd"]["arm"]]+ self.o = o+ jr = model.jnt_range[ids[o:]]+ W = D["walk"]+ self.LO = np.r_[-np.array(L["walk"]["command_max"]), jr[2, 0], jr[0, 0], jr[3:10, 0]]+ self.HI = np.r_[np.array(L["walk"]["command_max"]), jr[2, 1], jr[0, 1], jr[3:10, 1]]+ self.VEL = np.r_[L["walk"]["command_accel"], L["waist"]["speed_rad_s"][2], L["waist"]["speed_rad_s"][0],+ L["arm"]["speed_rad_s"]]+ if self.planar: # the planar copy: u[0:3] = the pelvis position, as a mobile base+ self.LO[0:3], self.HI[0:3] = -np.inf, np.inf+ self.VEL[0:3] = body.base_speed, body.base_speed, body.yaw_rate+ self.STEP = self.VEL * body.dt # the walk command: its change per step; the joints: their speed+ self.rest = np.r_[0.0, 0.0, 0.0, R["waist"], R["arm"]]+ if rest is not None:+ self.rest[3:] = rest+ self.dt, self.substeps = body.dt, body.substeps+ self.tool_site = mj.mj_name2id(model, mj.mjtObj.mjOBJ_SITE, prefix + "hand_" + body.hands[hand]["site"]) \+ if hand else -1+ self.base_body = mj.mj_name2id(model, mj.mjtObj.mjOBJ_BODY, prefix + "pelvis")+ self.cmd = np.zeros(3)+ self.mode = "walk"+ self.kicker = None+ self.k = 0+ self.farms = None+ self.residual = False # FALCON's wrist residual (falcon.py); AGILE has none+ if not self.fixed_base:+ lids = [jid(j) for j in LEGS]+ self.lqadr = np.array([model.jnt_qposadr[i] for i in lids])+ self.lvadr = np.array([model.jnt_dofadr[i] for i in lids])+ self.laid = np.array([mj.mj_name2id(model, mj.mjtObj.mjOBJ_ACTUATOR, f"{prefix}m_{j}") for j in LEGS])+ self.ltau = model.actuator_ctrlrange[self.laid, 1].copy()+ fj = next(j for j in range(model.njnt) if model.jnt_bodyid[j] == self.base_body)+ self.fqadr, self.fvadr = int(model.jnt_qposadr[fj]), int(model.jnt_dofadr[fj])+ if walker != "unitree": # the optional FALCON / AGILE policy (falcon.py, agile.py; body.toml+ if walker in ("falcon", "falcon_legs"): # [walk.falcon], [walk.agile]): they read all 29 joints+ from .falcon import Falcon+ self.policy = Falcon(D, arm_actor=walker == "falcon")+ else:+ from .agile import Agile+ self.policy = Agile(D)+ self.lkp, self.lkd = self.policy.kp, self.policy.kd+ fids = [jid(j) for j in LEGS + TORSO + [f"{s}_{a}_joint" for s in ("left", "right") for a in ARM]]+ self.fq, self.fv = model.jnt_qposadr[fids], model.jnt_dofadr[fids]+ self.farms = [upper.index(f"{s}_{a}_joint") for s in ("left", "right") for a in ARM]+ self.residual = walker == "falcon"+ else:+ self.policy = WalkPolicy(D)+ self.lkp, self.lkd = np.array(W["kp"], float), np.array(W["kd"], float)+ self.leg_targets = self.policy.default.copy()+ # the servos (bodies/servo.py): the upper body's commanded joints (setpoints at the speed limits, the motor+ # curves at the output), the legs' output stage (the motor curves), the walking command (the real joystick+ # range, rate-limited)+ upper_keys = ([None] * 3 if self.planar else []) + [short(j) for j in body.joints(arm, fixed_base=True)]+ leg_keys = [] if self.fixed_base else [short(j) for j in LEGS]+ self.servo, self.legs_act, self.ACC = SV.legged_layout(model, self, D, body.dt / body.substeps, upper_keys,+ leg_keys, Pl if self.planar else None)+ self.walk = SV.WalkCommand(L["walk"], body.dt)+ self.selfcol = SC.Monitor(model, prefix + "selfcol", D["self_collision"].get("warn_force_n")) # recorded only++ # u <-> joints+ def joint_targets(self, u):+ return self.M @ np.asarray(u, float) + self.c++ def u_of(self, d):+ q, o = d.qpos[self.qadr], self.o+ return np.r_[q[0:3] if o else self.cmd, q[o + 2], q[o], q[o + 3:o + 10]]++ def ud_of(self, d):+ v, o = d.qvel[self.vadr], self.o+ return np.r_[v[0:3] if o else np.zeros(3), v[o + 2], v[o], v[o + 3:o + 10]]++ def base_pose(self, d):+ """The pelvis on the floor: (x, y, yaw) in the world (the yaw of its forward axis)."""+ R = d.xmat[self.base_body].reshape(3, 3)+ p = d.xpos[self.base_body]+ return np.array([p[0], p[1], math.atan2(R[1, 0], R[0, 0])])++ def pelvis(self, d):+ """(position, rotation matrix) of the pelvis in the world."""+ return d.xpos[self.base_body].copy(), d.xmat[self.base_body].reshape(3, 3).copy()++ def place(self, d, u, pos=None, yaw=None):+ """Teleport to standing at the mount (or at pos / yaw) with the upper body at u; the policy's memory reset."""+ d.qpos[self.qadr] = self.joint_targets(u)+ d.qvel[self.vadr] = 0.0+ if not self.fixed_base:+ m = self.m+ j = self.fqadr+ p0 = m.body_pos[self.base_body] if pos is None else np.asarray(pos, float)+ q0 = m.body_quat[self.base_body] if yaw is None else np.array(quat_z(yaw))+ d.qpos[j:j + 3] = p0+ d.qpos[j + 3:j + 7] = q0+ d.qvel[self.fvadr:self.fvadr + 6] = 0.0+ d.qpos[self.lqadr] = self.policy.default+ d.qvel[self.lvadr] = 0.0+ self.policy.reset()+ self.walk.reset()+ self.legs_act.reset()+ self.leg_targets = self.policy.default.copy()+ self.mode, self.kicker, self.cmd, self.k = "walk", None, np.zeros(3), 0+ self.sync(d)++ def sync(self, d):+ """The servo's setpoint generator to the upper body's measured state (after a teleport or a state copy)."""+ x, xd = self.u_of(d), self.ud_of(d)+ if not self.planar:+ x[0:3], xd[0:3] = 0.0, 0.0 # the walking command is not a position+ self.servo.reset(x, xd)++ # the control step+ def begin_step(self, d, u):+ """Once per 10 ms control step, before its substeps: the walking command from u, the policy every 20 ms+ (or the kick's leg targets)."""+ if self.fixed_base:+ return+ self.cmd = self.walk(u[0:3]).copy() # the real joystick range, rate-limited (bodies/servo.py)+ if self.mode == "kick":+ self.leg_targets = self.kicker.step(d)+ if self.kicker.done:+ self.mode, self.kicker = "walk", None+ self.policy.reset()+ self.k = 0+ if self.mode == "walk" and self.k % 2 == 0:+ j, v = self.fqadr, self.fvadr+ if self.walker != "unitree": # all 29 joints, u's arm targets and waist yaw (falcon.py; agile.py+ # reads the joints only)+ up = self.joint_targets(u)+ self.leg_targets = self.policy.step(d.qpos[j + 3:j + 7], d.qvel[v + 3:v + 6], d.qpos[self.fq],+ d.qvel[self.fv], self.cmd, up[self.farms], up[0])[:12]+ else:+ self.leg_targets = self.policy.step(d.qpos[j + 3:j + 7], d.qvel[v + 3:v + 6], d.qpos[self.lqadr],+ d.qvel[self.lvadr], self.cmd, self.k * self.dt)+ self.k += 1++ def apply(self, d, u_prev, u_next, j, u_prev2=None):+ """Physics substep j: the upper body through its servo (bodies/servo.py: setpoints within the limits, PD ++ bias + inertia feed-forward, the motor curves) and the legs' PD through their output stage (the motor+ curves). u_prev2 is accepted for the old signature."""+ self.selfcol.update(d) # self-collision contacts of the last physics step (recorded)+ if not self.servo.ready:+ self.sync(d)+ a, b = np.asarray(u_prev, float), np.asarray(u_next, float)+ extra = None # FALCON's balance residual of the wrists, as a target offset+ if self.residual and self.mode == "walk":+ extra = np.zeros(len(self.kp))+ extra[self.farms] = self.policy.wrist_torque(self.kp[self.farms])+ self.servo.track(d, a + (b - a) * (j / self.substeps), (b - a) / self.dt, extra)+ if not self.fixed_base:+ kp, kd = (self.kicker.kp, self.kicker.kd) if self.mode == "kick" else (self.lkp, self.lkd)+ lt = kp * (self.leg_targets - d.qpos[self.lqadr]) - kd * d.qvel[self.lvadr]+ if self.mode == "kick":+ lt = lt + self.kicker.ff+ self.legs_act.write(d, lt)++ def self_collisions(self) -> dict:+ """The self-collision record since the rig was built or reset (bodies/selfcollision.py Monitor.summary):+ events, warnings, time in contact, peak force, impulse, the worst pairs. For the match record."""+ return self.selfcol.summary()++ def check(self, u, u_prev, u_prev2=None):+ """A target row against the limits (bodies/servo.py check_row): ranges (the walking command within the real+ joystick range), per-step changes (joint speeds, the walking command's rate); with u_prev2 the planar copy's+ base acceleration. None or the reason."""+ return SV.check_row(u, u_prev, u_prev2, self.LO, self.HI, self.VEL, self.ACC, self.dt,+ self.servo.base.lim if self.servo.base is not None else None)++ def tool(self, d):+ return d.site_xpos[self.tool_site].copy(), d.site_xmat[self.tool_site].reshape(3, 3).copy()++ def kick(self, d, foot="right", speed=2.5, height=0.10, reach=0.22, target=None, direction=None):+ """Start a kick (kick.py): the legs leave the policy until it ends. target: the world point the foot's strike+ box passes through at `speed` (m/s; e.g. a little below and behind the ball's centre); direction: the swing's+ world direction (default the robot's forward axis); without a target the foot strikes `reach` beyond the+ support foot's toe line, `height` above the ground."""+ if self.fixed_base or self.mode == "kick":+ return False+ from .kick import Kick+ self.kicker = Kick(self, d, foot, speed, height, reach, target, direction)+ self.mode = "kick"+ return True++ def memory(self):+ return self.policy.state() if not self.fixed_base else np.zeros(0)+++_BODY: dict = {}+++def load() -> G1Body:+ if "g1" not in _BODY:+ _BODY["g1"] = G1Body()+ return _BODY["g1"]diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/body.toml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/body.tomlnew file mode 100644index 0000000000..3e93651a0a--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/body.toml@@ -0,0 +1,239 @@+# The RoboOlympics legged humanoid: Unitree G1 (29-DOF, rev 1.0) from MuJoCo Menagerie, walking with Unitree's own+# pretrained walking policy (unitree_rl_gym, BSD-3-Clause). For the sports where the feet matter (soccer, athletics);+# the upper-body sports use bodies/wheeled_humanoid. Data only: body.py reads it.++[body]+name = "unitree_g1"+title = "legged humanoid (Unitree G1, 29 DOF)"+revision = "g1-4" # bump on any change that alters play (model.xml, policy, limits, controllers;+ # g1-2: walking command at the real joystick limits, motor curves, bodies/servo.py)+ # g1-3: self-collision, [self_collision] (bodies/selfcollision.py, 2026-10-09)+ # g1-4: legs x legs, shin x foot (self-collision); the strike boxes out of it+model = "model.xml" # tools/make_model.py from the Menagerie model (provenance, changes)+meshes = { standard = "meshes", fine = "meshes_fine", "25k" = "meshes_25k" } # standard: 63 k faces; fine: the Menagerie meshes (419 k)+# "25k": the players' level of detail (31 k faces, in git; bodies/lod.py from meshes_fine/,+# user decision D1 2026-10-08): mount(..., lod="25k") draws the players' images with the real robot's appearance+license = "BSD-3-Clause (LICENSE: MuJoCo Menagerie unitree_g1, derived from Unitree's g1_description; policy/LICENSE.unitree_rl_gym: the walking policy); MIT (policy/LICENSE.falcon: the optional FALCON walking policy); Apache-2.0 (policy/LICENSE.agile: the optional AGILE walking policy)"+mass_kg = 33.3 # the model (datasheet "about 35 kg" with battery)+height_m = 1.32 # standing (datasheet 1,320 mm)+kind = "legged" # the base is not a joint: it moves by walking (the policy) or kicking++[dof] # the controlled vector u, in this order+names = ["walk_vx", "walk_vy", "walk_wz", "waist_pitch", "waist_yaw",+ "arm_0", "arm_1", "arm_2", "arm_3", "arm_4", "arm_5", "arm_6"]+# walk_*: the walking policy's velocity command in the robot's body frame (m/s, m/s, rad/s), held until changed;+# waist_pitch / waist_yaw: the waist (waist_roll holds 0); arm_i: the hand arm's joints (shoulder pitch, roll, yaw,+# elbow, wrist roll, pitch, yaw). The other arm holds [rest] other_arm. The legs belong to the walking policy (or the+# kick controller): they are not in u.++[walk] # the walking policy (policy/): Unitree unitree_rl_gym deploy/pre_train/g1/motion.pt+policy = "policy/motion.pt" # an LSTM actor (64 units) trained in Isaac Gym on g1_12dof, validated sim-to-sim in+ # MuJoCo by Unitree (deploy/deploy_mujoco); 50 Hz; observation 47 (angular+ # velocity, gravity, command, leg joints, velocities, last action, gait phase)+sha256 = "cf668f75b90d1abf73d2b87612a6e76bccc61ff7e083b63582d3f6aaa3c1759d"+weights = "policy/motion.npz" # its weights as arrays (tools/export_policy.py): the simulator runs it in numpy+rate_hz = 50+gait_period_s = 0.8+default_angles = [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0, -0.1, 0.0, 0.0, 0.3, -0.2, 0.0]+kp = [100, 100, 100, 150, 40, 40, 100, 100, 100, 150, 40, 40]+kd = [2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2]+action_scale = 0.25+obs_scales = { ang_vel = 0.25, dof_pos = 1.0, dof_vel = 0.05, cmd = [2.0, 2.0, 0.25] }+command_max = [1.0, 1.0, 1.0] # the policy's training range (lin_vel_x, lin_vel_y, ang_vel_yaw); measured in+ # MuJoCo: 0.49 m/s for 0.5, 0.91 m/s for 1.0, 0.30 m/s sideways for 0.4+command_accel = [2.0, 2.0, 4.0] # how fast a command may change (per second): our rule, not the policy's+[walk.planning] # a planner's model of walking (the planar copy's base): below the measured+speed_m_s = 0.6 # speeds, with the policy's lag of about 0.3 s in the acceleration; the copy's+accel_m_s2 = 1.5 # base servo is soft in yaw (base_kp / base_kd: x, y, yaw), like the standing+yaw_rate_rad_s = 0.8 # robot, whose pelvis turns against a fast waist or arm swing+yaw_accel_rad_s2 = 3.0+base_kp = [3000.0, 3000.0, 200.0]+base_kd = [150.0, 150.0, 25.0]+# FALCON (S8; MIT, policy/LICENSE.falcon): an optional walking policy, a sport opts in with rig(..., walker="falcon")+# (falcon.py), or walker="falcon_legs": FALCON on the legs only (its arm actor not applied and fed back as 0, no wrist+# residual; falcon.py). Trained in IsaacGym on the 29-DOF G1 with arm motions and forces on the hands. The weights of the+# released sim2real/models/falcon/g1_29dof.onnx (onnx_sha256), unchanged, with a parity fixture (tools/export_falcon.py).+[walk.falcon]+weights = "policy/falcon_g1_29dof.npz"+onnx_sha256 = "8ac8f51875b878a79d9b5782e702b66572697e204ed262e2002b55631f3105d0"+rate_hz = 50+history = 5 # frames of 115 numbers in the observation (falcon.py)+default_angles = [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0, -0.1, 0.0, 0.0, 0.3, -0.2, 0.0, 0.0, 0.0, 0.0,+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # 29 joints (S8 yaml)+kp = [100, 100, 100, 200, 20, 20, 100, 100, 100, 200, 20, 20] # the legs' PD (S8 yaml JOINT_KP, KD); the waist+kd = [2.5, 2.5, 2.5, 5.0, 0.2, 0.1, 2.5, 2.5, 2.5, 5.0, 0.2, 0.1] # and the arms stay on the [controller] servo+action_scale = 0.25+action_clip = 100.0+obs_scales = { ang_vel = 0.25, dof_vel = 0.05, base_height = 2.0 }+base_height_m = 0.75 # DESIRED_BASE_HEIGHT (S8 yaml)+command_max = [1.0, 1.0, 1.0] # the training range (S8 env config); [limits.walk] clips the command first+speed_min_m_s = 0.2 # training: a speed |(vx, vy)| below 0.2 is 0 (S8 env code)+turn_min_rad_s = 0.2 # ours: with no speed, a smaller yaw rate is 0 too (the robot stands)+heading_gain = 0.5 # training: yaw rate = 0.5 (heading target - heading), clipped (S8 env code)+heading_error_max_rad = 1.0 # ours: the heading target stays this close to the heading+wrist_residual_max_rad = 0.05 # ours: the arm actor's residual, added to the wrists' targets only, clipped+# AGILE (S9; Apache-2.0, policy/LICENSE.agile): another optional walking policy, a sport opts in with+# rig(..., walker="agile") (agile.py). NVIDIA's velocity-height policy, trained in Isaac Lab on the 29-DOF G1 (legs+# only; the arms and the waist yaw moved at random while it stood, held at 0 while it walked). The weights and+# constants of the released LEAPP bundle's ONNX graph (onnx_sha256), unchanged, with the bundle's joint order and a+# parity fixture (tools/export_agile.py).+[walk.agile]+weights = "policy/agile_g1_velocity_height.npz"+onnx_sha256 = "f9a8dfcb8cb8bb2816b92cf893650c53dea30bb041f4919a85f1cf73acbb29fc"+rate_hz = 50 # the bundle's pipeline frequency (S9)+history = 5 # frames of each observation term, kept by the graph (agile.py)+kp = [100, 100, 100, 200, 20, 20, 100, 100, 100, 200, 20, 20] # the legs' PD: the graph's gain outputs (S9; the+kd = [2.5, 2.5, 2.5, 5.0, 0.2, 0.1, 2.5, 2.5, 2.5, 5.0, 0.2, 0.1] # export checks them); waist, arms: [controller]+base_height_m = 0.72 # the height command: training's walking height (DEFAULT_PELVIS_HEIGHT, S9)+command_min = [-0.5, -0.5, -1.0] # the training range (vx, vy, wz; S9); [limits.walk] clips the command first+command_max = [1.5, 0.5, 1.0]+command_min_norm = 0.1 # training: a command (vx, vy, wz) of norm below 0.1 is 0 (S9 min_vel_norm)++[limits.walk] # the walking command u[0:3] (bodies/servo.py WalkCommand): vx, vy, wz+command_max = [0.8, 0.5, 1.57] # what Unitree's own deployment accepts from the joystick (audit G8, approved)+command_accel = [2.0, 2.0, 4.0] # how fast a command may change (per second)+[limits.walk.source]+command_max = "S5 (deploy/deploy_real/configs/g1.yaml:42 max_cmd [0.8, 0.5, 1.57]; the policy was trained on +-1, [walk] command_max)"+command_accel = "ESTIMATE: our rule (the joystick has no published rate limit; 0.4 s from 0 to the forward limit)"++[limits.arm] # joints 0..6 of either arm; Unitree g1_29dof_rev_1_0.urdf <limit> (S2)+speed_rad_s = [37.0, 37.0, 37.0, 37.0, 37.0, 22.0, 22.0]+torque_nm = [25.0, 25.0, 25.0, 25.0, 25.0, 5.0, 5.0]+reach_m = 0.45 # "arm span about 0.45 m" (S1)+payload_kg = 2.0+[limits.arm.source]+speed_rad_s = "S2 (URDF; reachable only near zero torque: the motor curves, S6, cut the torque from 30.9 / 15.3 rad/s)"+accel_rad_s2 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+jerk_rad_s3 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+torque_nm = "S2 (URDF effort; with the motor curves of [motors], S6)"++[limits.waist] # yaw, roll, pitch (S2)+speed_rad_s = [32.0, 37.0, 37.0]+torque_nm = [88.0, 50.0, 50.0]+range_rad = [[-2.618, 2.618], [-0.52, 0.52], [-0.52, 0.52]]+[limits.waist.source]+speed_rad_s = "S2"+accel_rad_s2 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+jerk_rad_s3 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+torque_nm = "S2 (with the motor curves, S6)"++[limits.leg] # hip pitch, roll, yaw, knee, ankle pitch, roll of either leg (S2; the datasheet+speed_rad_s = [32.0, 20.0, 32.0, 20.0, 37.0, 37.0] # gives the knee 90 N m for the 23-DOF base model, S1)+torque_nm = [88.0, 139.0, 88.0, 139.0, 50.0, 50.0]+[limits.leg.source]+speed_rad_s = "S2"+accel_rad_s2 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+jerk_rad_s3 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+torque_nm = "S2 (with the motor curves, S6)"++[controller] # waist and arms: as the wheeled humanoid's servo (M qdd_des + PD + bias,+[controller.kp] # clipped at the torques, every 1 ms); legs: the policy's PD (or the kick's)+waist = [400.0, 400.0, 400.0]+arm = [300.0, 300.0, 300.0, 300.0, 100.0, 60.0, 60.0]+[controller.kd]+waist = [10.0, 10.0, 10.0]+arm = [6.0, 6.0, 6.0, 6.0, 2.0, 1.0, 1.0]+[controller.step]+control_dt_s = 0.01+physics_dt_s = 0.001++[rest]+waist = [0.0, 0.0] # pitch, yaw+arm = [0.2, -0.2, 0.0, 1.28, 0.0, 0.0, 0.0] # the Menagerie stand keyframe's right arm+other_arm = [0.2, 0.2, 0.0, 1.28, 0.0, 0.0, 0.0]++[kick] # the kick controller (kick.py): stop, shift the weight onto the support foot, wind+gains_kp = [700, 700, 500, 900, 300, 300] # up, swing the foot through a target, recover, walk on;+gains_kd = [12, 12, 8, 15, 6, 6] # leg joints on PD at these gains (motor torques clipped)++[mounts]+wrist = "the body <side>_mount at the rubber hand of <side>_wrist_yaw_link, +z along the forearm"+cameras = ["head_left", "head_right"] # a stereo pair in front of the head, 5 cm apart, 58 degree vertical field of+ # view: the G1's head depth camera (Intel RealSense D435i: 50 mm baseline,+ # 87 x 58 degree depth field of view, S3); its tilt is a mount parameter+head_pitch_rad = 0.6++# ---------------------------------------------------------------------------------------------------------------------+# The motors (bodies/servo.py Actuators: every G1 joint's torque goes through its curve) and the low-level plan+# interface of the optional joint-group arbiter (bodies/control/arbiter.py, from the two-mode pilot of 2026-10-08).++[motors] # Unitree actuator torque-speed curves (S6): below X1 rad/s the peak torque is Y1+ # (torque along the motion) or Y2 (against it, braking); from X1 it falls+ # linearly to 0 at X2. The URDF effort (actuator ctrlrange) caps it as well.+N7520_14p3 = { X1 = 22.63, X2 = 35.52, Y1 = 71.0, Y2 = 83.3 }+N7520_22p5 = { X1 = 14.5, X2 = 22.7, Y1 = 111.0, Y2 = 131.0 }+N5020_16 = { X1 = 30.86, X2 = 40.13, Y1 = 24.8, Y2 = 31.9 }+N5020_16_x2 = { X1 = 30.86, X2 = 40.13, Y1 = 49.6, Y2 = 63.8 } # ankles, waist roll / pitch: two N5020-16 in a+W4010_25 = { X1 = 15.3, X2 = 24.76, Y1 = 4.8, Y2 = 8.6 } # parallel linkage (S6; URDF effort 50 N m)+[motors.assign] # per joint (unitree_rl_lab unitree.py UNITREE_G1_29DOF_CFG, S6)+hip_pitch = "N7520_14p3"+hip_roll = "N7520_22p5"+hip_yaw = "N7520_14p3"+knee = "N7520_22p5"+ankle_pitch = "N5020_16_x2"+ankle_roll = "N5020_16_x2"+waist_yaw = "N7520_14p3"+waist_roll = "N5020_16_x2"+waist_pitch = "N5020_16_x2"+shoulder_pitch = "N5020_16"+shoulder_roll = "N5020_16"+shoulder_yaw = "N5020_16"+elbow = "N5020_16"+wrist_roll = "N5020_16"+wrist_pitch = "W4010_25"+wrist_yaw = "W4010_25"++[lowlevel] # the low-level interface (bodies/control/arbiter.py): plan rows, servo gains+groups = ["legs", "waist", "arms"] # Unitree SDK joint order: left leg 6, right leg 6, waist yaw / roll / pitch,+ # left arm 7, right arm 7+row_dt_s = 0.01 # one plan row per control step; the PD interpolates between rows at 1 kHz+max_rows = 300 # a plan covers at most 3 s+min_plan_interval_steps = 2 # a new plan at most every 20 ms (50 Hz): the agent's loop runs outside the sim+kp_max = { legs = 1000.0, waist = 500.0, arms = 400.0 } # "estimate": the motor drivers accept any gain (LowCmd);+kd_max = { legs = 20.0, waist = 15.0, arms = 10.0 } # these caps keep the 1 kHz PD stable in simulation+[lowlevel.handover] # a group handed back to the walking policy (legs) or to the body's hold+blend_steps = 30 # legs: targets blended to the policy's stance (0.3 s), at the stand gains+blend_steps_after_skill = 0 # the kick ends in the stance itself: the policy takes over at once (as kick.py)+stand_kp = [700, 700, 500, 900, 300, 300]+stand_kd = [12, 12, 8, 15, 6, 6]+stable_tilt_rad = 0.10 # then the policy, re-initialised, takes the legs and holds a zero command until+stable_omega_rad_s = 2.0 # the robot is confirmed stable: over the last stable_window steps (half a gait+stable_com_speed_m_s = 0.20 # period) pelvis tilt, angular rate and CoM speed stayed under these (marching in+stable_window = 40 # place sways up to 0.07 rad, 1.4 rad/s, 0.13 m/s); the agent's command applies+timeout_steps = 200 # from then on; not confirmed in 2 s: logged (stable_timeout), let through+++# ---------------------------------------------------------------------------------------------------------------------+# Self-collision (real limits B0, 2026-10-09: the real arm cannot pass through its own body, so the simulated one+# cannot either). bodies/selfcollision.py turns this into MuJoCo <pair>s at mount(): parts by body name (without the+# prefix; a body matching nothing takes its parent's part, one below an arm is that arm's tool), the rules say which+# parts touch, the exclusions say which pairs do not and why. Automatic exclusions (not listed): geoms of one rigid+# group (a link, its mount, its tool) and of two rigid groups joined by one joint (the joint's housing).+# Recorded during play (rig.self_collisions()): events, time in contact, peak force; above warn_force_n a warning.+# No penalty yet (the sports decide). Check: python -m bodies.selfcollision check <robot> (CI: check-robot-limits).+[self_collision]+parts.left_arm = "left_(shoulder_(pitch|roll|yaw)|elbow|wrist_(roll|pitch|yaw))_link"+parts.right_arm = "right_(shoulder_(pitch|roll|yaw)|elbow|wrist_(roll|pitch|yaw))_link"+parts.body = "pelvis|waist_(yaw|roll)_link|torso_link"+parts.left_leg = "left_(hip_(pitch|roll|yaw)|knee|ankle_(pitch|roll))_link"+parts.right_leg = "right_(hip_(pitch|roll|yaw)|knee|ankle_(pitch|roll))_link"+rules = { arm_body = true, arm_arm = true, tool_own_arm = true, same_arm = false, leg_leg = true, same_leg = true }+ # leg_leg / same_leg (audit, Changhe 2026-10-10): the walking policy's sidesteps+ # crossed the legs by up to 52 mm; shin x foot of one leg (the ankle between)+ignore_geoms = "(left|right)_foot_strike" # the kick's strike boxes (contype 8): sensing volumes, not the shell+warn_force_n = 20.0 # a self-collision event above this peak normal force is a warning+exclude = [] # none beyond the automatic ones: the Menagerie collision meshes clear each other+ # at the stand pose and in every random legal pose class (check: 0 structural)+[self_collision.source]+warn_force_n = "ESTIMATE: no vendor publishes a self-contact threshold for this robot; the Franka's collision threshold (20 N, bodies/franka_panda S4) for every body, so one rule reads the same everywhere"++[sources]+S1 = "Unitree Robotics, G1 product page, specifications: https://www.unitree.com/g1/ (1,320 mm, about 35 kg, 23 DOF base model / 29-43 DOF EDU, knee 90 N m, arm load about 2 kg, arm span about 0.45 m, depth camera + 3D LiDAR)"+S2 = "Unitree Robotics, g1_description g1_29dof_rev_1_0.urdf joint <limit> (effort, velocity, lower, upper), as shipped in unitree_rl_gym resources/robots/g1_description (commit 276801e46c5d433564f24658bac64f254b7d2d4b): https://github.com/unitreerobotics/unitree_rl_gym"+S3 = "Intel RealSense D435i datasheet (stereo baseline 50 mm, depth field of view 87 x 58 degrees): https://www.intelrealsense.com/depth-camera-d435i/"+S4 = "MuJoCo Menagerie unitree_g1 (BSD-3-Clause), commit f054586a8e90465d49ee5be15335c4a0c7f57caf: https://github.com/google-deepmind/mujoco_menagerie/tree/main/unitree_g1"+S5 = "Unitree unitree_rl_gym (BSD-3-Clause), deploy/pre_train/g1/motion.pt, deploy/deploy_mujoco/configs/g1.yaml, deploy/deploy_real/configs/g1.yaml, legged_gym/envs/g1/g1_config.py, commit 276801e46c5d433564f24658bac64f254b7d2d4b"+S6 = "Unitree unitree_rl_lab, source/unitree_rl_lab/unitree_rl_lab/assets/robots/unitree_actuators.py (UnitreeActuator torque-speed curves) and unitree.py (UNITREE_G1_29DOF_CFG joint-to-motor assignment), commit 4960b84732b0c2ec593dccbfe963fda1bcd7b1e3"+S7 = "Unitree unitree_sdk2 (BSD-3-Clause), commit 63096d0: LowCmd (q, dq, kp, kd, tau per motor) is sent to the motors unchanged: no joint position, velocity or acceleration limiting in the SDK, https://github.com/unitreerobotics/unitree_sdk2"+S8 = "LeCAR-Lab FALCON (MIT, Copyright (c) 2025 Yuanhang Zhang), commit a967a6d8494f57777cf8d266a644ac8e45833301: sim2real/models/falcon/g1_29dof.onnx (the policy), sim2real/config/g1/g1_29dof_falcon.yaml (gains, default angles, scales, base height), humanoidverse/config/env/decoupled_locomotion_stand_height_waist_wbc_ma_diff_force.yaml and humanoidverse/envs/decoupled_locomotion/decoupled_locomotion_stand_height_waist_wbc_ma.py (command ranges, the 0.2 m/s speed threshold, the heading controller); Y. Zhang et al., FALCON: Learning Force-Adaptive Humanoid Loco-Manipulation, arXiv:2505.06776: https://github.com/LeCAR-Lab/FALCON"+S9 = "NVIDIA WBC-AGILE (Apache-2.0, Copyright (c) NVIDIA CORPORATION & AFFILIATES), commit 6830cf995714e81c91ce63247e8e016d36e28f14: agile/data/policy/velocity_height_g1/leapp/Velocity-Height-G1-History-v0/ (Velocity-Height-G1-History-v0.onnx: the policy with its observation, history and gains in the graph; .yaml: joint order, quaternion order, 50 Hz, feedback), agile/rl_env/tasks/locomotion_height/g1/velocity_height_env_cfg.py (observation terms, command ranges, 200 Hz physics, random upper-body motion while standing), agile/rl_env/mdp/actions/random_actions.py (the upper body at its default pose while walking), agile/rl_env/mdp/commands/commands_cfg.py (min_vel_norm 0.1), agile/rl_env/assets/robots/unitree_g1.py (DEFAULT_PELVIS_HEIGHT 0.72); H. Zhao et al., AGILE: A Comprehensive Workflow for Humanoid Loco-Manipulation Learning, arXiv:2603.20147: https://github.com/nvidia-isaac/WBC-AGILE"diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/falcon.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/falcon.pynew file mode 100644index 0000000000..2c51fd9717--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/falcon.py@@ -0,0 +1,192 @@+"""FALCON's walking policy for the G1 (optional; body.toml [walk.falcon]): a whole-body-trained walking and balance+policy that a sport may choose instead of Unitree's legs-only policy (body.py WalkPolicy, the default):++ rig = B.rig(model, prefix, hand="paddle", walker="falcon") # the arm actor's wrist residual on (below)+ rig = B.rig(model, prefix, hand="paddle", walker="falcon_legs") # FALCON drives the legs only (below)++Source: LeCAR-Lab/FALCON (MIT, Copyright (c) 2025 Yuanhang Zhang; policy/LICENSE.falcon), the released policy+sim2real/models/falcon/g1_29dof.onnx; Y. Zhang et al., "FALCON: Learning Force-Adaptive Humanoid Loco-Manipulation",+arXiv:2505.06776. Trained in IsaacGym on the 29-DOF G1 (PD at 200 Hz, policy at 50 Hz) with upper-body motions+replayed on the arms and external forces on the hands (x, y within +-40 N, z within -50..5 N). policy/falcon_g1_29dof.npz holds the ONNX graph's weights+unchanged (float32, evaluated in float64; tools/export_falcon.py) and a parity fixture: observations with the outputs+onnxruntime gave for them (parity() checks this port against them).++The network: two MLPs on the same input, 575 -> 512 -> 256 -> 128 (ELU) -> 15 (legs + waist) and -> 14 (arms). The+observation is the last 5 frames (oldest first) of 115 numbers, its terms sorted by name as FALCON's deployment code+(sim2real/rl_policy, config/g1/g1_29dof_falcon.yaml) builds them:+ [0:29] last action (clipped to +-100) [29:32] pelvis angular velocity (pelvis frame) x 0.25+ [32] yaw-rate command [33] base height command (m) x 2+ [34:36] vx, vy command (m/s, robot frame) [36] stepping flag (1 stepping, 0 standing)+ [37:40] waist yaw, roll, pitch command (rad) [40:69] q - default (29 joints, Unitree's motor order)+ [69:98] joint speeds x 0.05 [98:101] gravity (0, 0, -1) in the pelvis frame+ [101:115] arm joint targets (rad; left arm 7, right arm 7)+Targets: default + 0.25 x action. On the rig (body.py G1Rig) and under the arbiter (bodies/control/arbiter.py) the+legs follow FALCON's 12 leg targets on its PD gains (body.toml [walk.falcon] kp, kd); the waist and the arms stay the+sport's (the rig's u, the arbiter's plans or holds): FALCON gets the arm targets and the waist's yaw as its commands+(roll and pitch go in as 0: training never commanded them, their input weights are untrained), its waist targets are+not used, and of its arm actor's output (a residual that FALCON adds to the arm targets) only the wrists' part is+kept, clipped to wrist_residual_max_rad (without it that output runs away within seconds and the standing robot slides+off; measured on this model).++walker="falcon_legs" (Falcon(decl, arm_actor=False)): the arm actor's output is not applied at all and its part of the+last action in the observation is 0 (as if the arms tracked their targets perfectly), no wrist residual: the arms+are wholly the sport's (the rig's servo, the arbiter's plans and holds). This is how basketball's low level (PR #58,+sports/basketball3x3/falcon.py) and the fencing study (docs/screening/fencing) use FALCON. Without the residual but+with the unapplied arm output fed back the standing robot shuffles away (2.5 m in 5 s, PR #58); with it zeroed it+stands and walks (conformance 3b: 10 s at rest with the paddle 7.3 cm, "falcon" 1.4 cm; on guard with an epee 0.08 m+and 2 deg, "falcon" 0.03 m and 10 deg; footwork at the joystick cap 0.77 m/s forward, 0.86 back, no fall in 34+footwork and disturbance runs), and the arms follow their plans undisturbed: on the same 7 reachable targets a re-planned arm+thrust comes within 0.4-0.8 cm (median), 1.0-2.2 cm with "falcon", though "falcon" is closer at the planned end+time (4.4 against 5.7-6.6 cm; fencing F0, docs/screening/fencing.md). Its waist output is not used either way (the+waist is the sport's).++As in its training: a walking speed |(vx, vy)| below 0.2 m/s is 0; here a yaw rate below 0.2 rad/s with no speed is 0+too, then the robot stands (stepping flag 0). Its yaw-rate input was a heading controller there, 0.5 (heading target -+heading) clipped to +-1, so here the yaw-rate command turns a heading target and the input is the command plus that+feedback (the robot keeps its heading when walking straight), clipped to the training range; base height 0.75 m.+FALCON saw a waist command (yaw within +-1 rad) only when standing: a sport that turns the waist while walking is+outside its training. Deterministic: plain float64 numpy.+"""++from __future__ import annotations++import math+from pathlib import Path++import numpy as np++HERE = Path(__file__).resolve().parent+N_LOWER, N_ARM, N_FRAME = 15, 14, 115+++def mlp(layers, x):+ """An actor: Gemm + ELU per hidden layer, a linear output."""+ for k, (w, b) in enumerate(layers):+ x = w @ x + b+ if k < len(layers) - 1:+ x = np.where(x > 0, x, np.expm1(np.minimum(x, 0.0)))+ return x+++def gravity_in(quat):+ """(0, 0, -1) in the frame of the quaternion (w, x, y, z)."""+ w, x, y, z = quat+ return np.array([2 * (-z * x + w * y), -2 * (z * y + w * x), 1 - 2 * (w * w + z * z)])+++def heading_of(quat):+ """The yaw (rad) of the quaternion (w, x, y, z)."""+ w, x, y, z = quat+ return math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))+++class Falcon:+ """FALCON for one robot: the observation history, the last action, the heading target; step() every 20 ms.+ For the rig like body.py WalkPolicy (default: the legs' stance, reset, state); its step() sees more."""++ WRISTS = [4, 5, 6, 11, 12, 13] # of the 14 arm joints (left, right): the wrists' roll, pitch, yaw++ def __init__(self, decl, arm_actor=True):+ F = decl["walk"]["falcon"]+ self.arm_actor = bool(arm_actor) # False: walker "falcon_legs" (no residual, its arm output fed back as 0)+ z = np.load(HERE / F["weights"])+ self.lower, self.upper = (+ [(z[f"{a}_w{k}"].astype(float), z[f"{a}_b{k}"].astype(float)) for k in range(4)] for a in ("lower", "upper")+ )+ self.fixture = z["parity_obs"], z["parity_action"]+ self.default_all = np.array(F["default_angles"], float) # 29 joints, Unitree's motor order+ self.default = self.default_all[:12] # the legs' stance (as WalkPolicy.default)+ self.kp, self.kd = np.array(F["kp"], float), np.array(F["kd"], float) # the legs' PD (12)+ self.scale, self.clip = float(F["action_scale"]), float(F["action_clip"])+ self.history_len = int(F["history"])+ S = F["obs_scales"]+ self.s_ang, self.s_vel, self.s_height = S["ang_vel"], S["dof_vel"], S["base_height"]+ self.height = float(F["base_height_m"])+ self.cmd_max = np.array(F["command_max"], float)+ self.speed_min, self.turn_min = float(F["speed_min_m_s"]), float(F["turn_min_rad_s"])+ self.k_heading, self.heading_err_max = float(F["heading_gain"]), float(F["heading_error_max_rad"])+ self.dt = 1.0 / float(F["rate_hz"])+ self.wrist_max = float(F["wrist_residual_max_rad"])+ self.reset()++ def reset(self):+ self.action = np.zeros(N_LOWER + N_ARM)+ self.history = np.zeros(self.history_len * N_FRAME)+ self.heading = None # the heading target: taken from the robot when it starts stepping+ self.targets = self.default_all[:N_LOWER].copy()++ def command(self, cmd):+ """The walking command as FALCON was trained on it: clipped to its range, small speeds and turns zeroed."""+ c = np.clip(np.asarray(cmd, float), -self.cmd_max, self.cmd_max)+ if math.hypot(c[0], c[1]) < self.speed_min:+ c[0:2] = 0.0+ if abs(c[2]) < self.turn_min:+ c[2] = 0.0+ return c++ def frame(self, quat, gyro, q, dq, cmd, arms, waist_yaw):+ """One observation frame (115) and the next heading target."""+ c = self.command(cmd)+ stepping = bool(np.any(c != 0.0))+ yaw = heading_of(quat)+ wz = 0.0+ if stepping:+ ref = yaw if self.heading is None else self.heading + c[2] * self.dt+ err = (ref - yaw + math.pi) % (2 * math.pi) - math.pi+ err = min(max(err, -self.heading_err_max), self.heading_err_max)+ wz = min(max(c[2] + self.k_heading * err, -self.cmd_max[2]), self.cmd_max[2])+ heading = yaw + err+ else:+ heading = None+ f = np.empty(N_FRAME)+ f[0:29] = self.action+ f[29:32] = np.asarray(gyro, float) * self.s_ang+ f[32] = wz+ f[33] = self.height * self.s_height+ f[34:36] = c[0:2]+ f[36] = float(stepping)+ f[37:40] = (waist_yaw, 0.0, 0.0) # yaw, roll, pitch+ f[40:69] = np.asarray(q, float) - self.default_all+ f[69:98] = np.asarray(dq, float) * self.s_vel+ f[98:101] = gravity_in(quat)+ f[101:115] = arms+ return f, heading++ def forward(self, obs):+ """The two actors on an observation (575): the action (29: legs + waist, arms), clipped as in deployment."""+ return np.clip(np.r_[mlp(self.lower, obs), mlp(self.upper, obs)], -self.clip, self.clip)++ def step(self, quat, gyro, q, dq, cmd, arms, waist_yaw):+ """One policy tick. quat (w, x, y, z) and gyro (pelvis frame) of the pelvis; q, dq: the 29 joints in Unitree's+ motor order (legs, waist yaw / roll / pitch, left arm, right arm); cmd: vx, vy, wz (robot frame); arms: the 14+ arm targets (left, right); waist_yaw: the waist's yaw command. Returns the 15 leg + waist targets."""+ f, self.heading = self.frame(quat, gyro, q, dq, cmd, arms, waist_yaw)+ self.history = np.r_[self.history[N_FRAME:], f]+ self.action = self.forward(self.history)+ if not self.arm_actor: # falcon_legs: the arm actor's output is never applied, so it is not fed back+ self.action[N_LOWER:] = 0.0+ self.targets = self.default_all[:N_LOWER] + self.scale * self.action[:N_LOWER]+ return self.targets++ def wrist_offsets(self):+ """The arm actor's residual on the six wrist joints (rad), clipped: added to their targets (0 for falcon_legs)."""+ if not self.arm_actor:+ return np.zeros(len(self.WRISTS))+ return np.clip(self.scale * self.action[N_LOWER:][self.WRISTS], -self.wrist_max, self.wrist_max)++ def wrist_torque(self, kp):+ """The residual as extra PD torque on the 14 arm joints (left, right) at their gains kp: kp x wrist_offsets()+ on the wrists, 0 elsewhere (= the wrists' targets moved by the offsets). The rig and the arbiter add it while+ FALCON has the legs."""+ t = np.zeros(N_ARM)+ t[self.WRISTS] = np.asarray(kp, float)[self.WRISTS] * self.wrist_offsets()+ return t++ def state(self):+ """The policy's memory (last action, history, heading target): for hashing and copying."""+ return np.r_[self.action, self.history, self.heading is not None, self.heading or 0.0]++ def parity(self):+ """max |this port - onnxruntime| over the fixture stored with the weights (tools/export_falcon.py)."""+ obs, ref = self.fixture+ return float(max(np.max(np.abs(self.forward(o.astype(float)) - r)) for o, r in zip(obs, ref)))diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/kick.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/kick.pynew file mode 100644index 0000000000..ecfba744b8--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/kick.py@@ -0,0 +1,313 @@+"""The G1's kick: a model-based whole-leg motion (the walking policy cannot kick), run on the legs' PD at the kick+gains (body.toml [kick]) with the motors' torque limits.++ stand the leg targets go from where the policy left them to the stance (0.25 s), feet down+ shift the pelvis moves over the support foot (0.55 s); a centre-of-mass loop keeps the CoM over the support+ foot's centre during the whole kick (the support foot stays where it is in the world)+ lift the kicking foot rises by `height` and winds back 0.15 m (0.25 s)+ swing the foot travels `reach` beyond the support foot's toe line along the robot's forward axis at `speed`+ (a minimum-jerk profile: its peak speed is about 1.9 x the mean), the instep at ball height+ recover follow-through, the foot back under the hip and down, the pelvis back between the feet, stand; then the+ walking policy takes the legs again (its memory reset)+Each control step the leg targets come from inverse kinematics of the two feet (position and a level orientation,+the support foot fixed in the world, the kicking foot on its path) relative to the desired pelvis pose. The kick+does not aim: the robot aims by walking and turning before it (the foot moves along its forward axis)."""+from __future__ import annotations++import math++import numpy as np++FOOT_STRIKE_FORWARD = 0.035 # the strike box's centre ahead of the ankle (model.xml)+BACK = -0.10 # the wind-up: the foot 10 cm behind where it stood+FOLLOW = 0.10 # with a target: the swing ends this far beyond it+STRIKE_IN_SITE = np.array([0.035, 0.0, -0.02]) # the strike box's centre in the foot site's frame (model.xml)+OUTSIDE = 0.012 # the balance target this much outside the support foot's centre line (the+ # swinging leg pulls the body toward the kicking side)+STAND_MAX = 60 # the stand waits until both feet are down and still (or this)+LOWER_MAX = 40 # the lowering goes on until the kicking foot is down (or this)+HOLD_MAX = 60 # the hold lasts until the capture point is within 1 cm of the target (or this)+CROUCH = 0.05 # the pelvis goes down this much for the kick (the support knee bent more)+OMEGA = math.sqrt(9.81 / 0.68) # the linear inverted pendulum's natural frequency at the G1's CoM height+++def minjerk(s):+ s = min(max(s, 0.0), 1.0)+ return 10 * s ** 3 - 15 * s ** 4 + 6 * s ** 5+++def yaw_of(R):+ return math.atan2(R[1, 0], R[0, 0])+++def rot_z(a):+ c, s = math.cos(a), math.sin(a)+ return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])+++class Kick:+ def __init__(self, rig, d, foot="right", speed=3.0, height=0.07, reach=0.22, target=None, direction=None):+ import mujoco as mj+ self.mj, self.rig, self.m = mj, rig, rig.m+ K = rig.B.decl["kick"]+ self.kp, self.kd = np.array(K["gains_kp"] * 2, float), np.array(K["gains_kd"] * 2, float)+ self.kin = mj.MjData(self.m)+ self.foot = foot+ self.sup = "left" if foot == "right" else "right"+ site = lambda n: mj.mj_name2id(self.m, mj.mjtObj.mjOBJ_SITE, rig.prefix + n)+ self.site = {"left": site("left_foot"), "right": site("right_foot")}+ self.legcols = {"left": np.arange(0, 6), "right": np.arange(6, 12)}+ p_pel, R_pel = rig.pelvis(d)+ self.yaw0 = yaw_of(R_pel)+ self.Rlevel = rot_z(self.yaw0)+ self.fw = self.Rlevel[:, 0]+ self.left_ax = self.Rlevel[:, 1]+ self.p0 = p_pel.copy()+ self.feet0 = {s: d.site_xpos[self.site[s]].copy() for s in ("left", "right")}+ self.q_start = d.qpos[rig.lqadr].copy()+ self.q = self.q_start.copy()+ self.com_off = np.zeros(2)+ self.com_fast = np.zeros(2)+ self.hold_extra = 0+ self.stand_extra = 0+ self.lower_extra = 0+ self.speed, self.height, self.reach = float(speed), float(height), float(reach)+ self.target = None if target is None else np.asarray(target, float).copy()+ if direction is not None: # the swing's direction (world, horizontal); default: forward+ a = np.array([direction[0], direction[1], 0.0], float)+ self.aim = a / max(np.linalg.norm(a), 1e-9)+ else:+ self.aim = self.fw.copy()+ dist = 0.15 + reach + 0.10 # the swing's nominal length: its duration (`speed` is the nominal+ n_sw = max(6, int(round(1.875 * dist / max(speed, 0.5) / rig.dt))) # peak; the real one is about 0.7 x)+ self.phases = [("stand", 40), ("shift", 140), ("hold", 30), ("lift", 30), ("swing", n_sw), ("follow", 10),+ ("retract", 50), ("lower", 40), ("unshift", 1), ("settle", 1)]+ self.delta = np.zeros(3)+ self.i, self.pi, self.done = 0, 0, False+ self.log = []+ self.ff = np.zeros(12)+ self.ik_err = {"left": 0.0, "right": 0.0}+ idx = [self.m.jnt_qposadr.tolist().index(a) for a in rig.lqadr]+ self.qlo, self.qhi = self.m.jnt_range[idx, 0].copy(), self.m.jnt_range[idx, 1].copy()+ self.qlo[[3, 9]] = 0.15 # the knees stay bent (no straight-leg singularity)+ self.qpel0 = np.array([math.cos(self.yaw0 / 2), 0.0, 0.0, math.sin(self.yaw0 / 2)])++ # ------------------------------------------------------------------ targets+ def _phase(self):+ name, n = self.phases[self.pi]+ return name, n, self.i / n++ def _pelvis_target(self, name, s):+ """The pelvis moves by `delta` (the vector that puts the centre of mass over the support foot's centre,+ measured when the shift starts), plus the balance correction while on one foot."""+ if name in ("stand", "settle"):+ k = 0.0+ elif name == "shift":+ k = minjerk(s)+ elif name == "unshift":+ k = 1.0 - minjerk(s)+ else:+ k = 1.0+ off = self.com_off + self.com_fast+ corr = self.fw * off[0] + self.left_ax * off[1]+ return self.p0 + self.delta * k + corr++ def _path(self):+ """The kicking foot's path (foot site, world), set when the stance is reached, along `aim` from where the foot+ stood: wound back 10 cm and lifted to the strike height, then swung forward to its end point, back above+ where it stood and down. Without a target the end point is `reach` beyond the support foot's toe line at+ `height`; with one (where the strike box's centre should meet the ball) the end is 10 cm beyond it, the+ height is the target's and the path is shifted sideways onto it (each within the leg's reach: at most 8 cm+ sideways, 3-12 cm up, 5-32 cm beyond the toe line)."""+ f0, sup = self.feet0[self.foot], self.feet0[self.sup]+ aim = self.aim+ lat = np.array([-aim[1], aim[0], 0.0])+ toe = float((sup - f0) @ aim)+ if self.target is None:+ x_end, side, h = toe + self.reach, 0.0, self.height+ else:+ rel = self.target - self.Rlevel @ STRIKE_IN_SITE - f0+ x_end, side, h = float(rel @ aim) + FOLLOW, float(rel @ lat), float(rel[2])+ x_end = float(np.clip(x_end, toe + 0.05, toe + 0.32))+ side = float(np.clip(side, -0.08, 0.08))+ h = float(np.clip(h, 0.03, 0.12))+ self.x_back, self.x_end, self.side, self.h = BACK, x_end, side, h++ def _at(self, x, z, side_k=1.0):+ f0 = self.feet0[self.foot]+ lat = np.array([-self.aim[1], self.aim[0], 0.0])+ return f0 + self.aim * x + lat * (self.side * side_k) + np.array([0.0, 0.0, z])++ def _kick_foot_target(self, name, s):+ f0 = self.feet0[self.foot]+ if name in ("stand", "shift", "settle", "unshift"):+ return f0.copy()+ if not hasattr(self, "x_end"):+ self._path()+ k = minjerk(s)+ if name == "lift": # wound back and up (and over onto the strike line)+ return self._at(self.x_back * k, self.h * k, k)+ if name == "swing": # forward through the strike point+ return self._at(self.x_back + (self.x_end - self.x_back) * k, self.h)+ if name == "follow":+ return self._at(self.x_end + 0.02, self.h)+ if name == "retract": # back above where it stood, at the strike height (clear of a ball)+ return self._at((self.x_end + 0.02) * (1 - k), self.h + 0.02 * math.sin(math.pi * k), 1 - k)+ if name == "lower": # down to 1 cm below where it stood (a firm landing)+ return f0 + np.array([0, 0, self.h - (self.h + 0.01) * k])+ return f0.copy()++ # ------------------------------------------------------------------ inverse kinematics of the feet+ def _ik(self, d, p_pel, foot_targets, iters=10):+ mj, m, kd, rig = self.mj, self.m, self.kin, self.rig+ kd.qpos[:] = d.qpos+ j = rig.fqadr+ kd.qpos[j:j + 3] = p_pel+ kd.qpos[j + 3:j + 7] = self.qpel0+ q = self.q.copy()+ jp = np.zeros((3, m.nv)); jr = np.zeros((3, m.nv))+ for _ in range(iters):+ kd.qpos[rig.lqadr] = q+ mj.mj_kinematics(m, kd)+ mj.mj_comPos(m, kd)+ for side in ("left", "right"):+ sid = self.site[side]+ p = kd.site_xpos[sid]+ R = kd.site_xmat[sid].reshape(3, 3)+ e = np.r_[foot_targets[side] - p, 0.5 * (np.cross(R[:, 0], self.Rlevel[:, 0]) ++ np.cross(R[:, 1], self.Rlevel[:, 1]) ++ np.cross(R[:, 2], self.Rlevel[:, 2]))]+ mj.mj_jacSite(m, kd, jp, jr, sid)+ cols = rig.lvadr[self.legcols[side]]+ J = np.vstack([jp[:, cols], jr[:, cols]])+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-3 * np.eye(6), e)+ n = np.abs(dq).max()+ if n > 0.15: # small steps: stay on the bent-knee branch+ dq *= 0.15 / n+ c = self.legcols[side]+ q[c] = np.clip(q[c] + dq, self.qlo[c], self.qhi[c])+ self.ik_err[side] = float(np.linalg.norm(e[:3]))+ return q++ def _nominal_pelvis(self, d, q_legs):+ """The level pelvis position that the leg angles q_legs put above the feet where they stand."""+ mj, m, kd, rig = self.mj, self.m, self.kin, self.rig+ kd.qpos[:] = d.qpos+ j = rig.fqadr+ kd.qpos[j:j + 3] = 0.0+ kd.qpos[j + 3:j + 7] = (math.cos(self.yaw0 / 2), 0.0, 0.0, math.sin(self.yaw0 / 2))+ kd.qpos[rig.lqadr] = q_legs+ mj.mj_kinematics(m, kd)+ off = [self.feet0[sd] - kd.site_xpos[self.site[sd]] for sd in ("left", "right")]+ return 0.5 * (off[0] + off[1])++ def _balance_target(self, d=None):+ """The support foot's centre (where it is now: it may slip or turn under a hard swing), a little outside."""+ out = self.left_ax * (OUTSIDE if self.sup == "left" else -OUTSIDE)+ p = self.feet0[self.sup] if d is None else d.site_xpos[self.site[self.sup]]+ return p + self.fw * FOOT_STRIKE_FORWARD + out++ def _site_vel(self, d, side):+ v = np.zeros(6)+ self.mj.mj_objectVelocity(self.m, d, self.mj.mjtObj.mjOBJ_SITE, self.site[side], v, 0)+ return v[3:]++ def _com_vel(self, d, com):+ prev = getattr(self, "_com_prev", None)+ self._com_prev = com.copy()+ return np.zeros(3) if prev is None else (com - prev) / self.rig.dt++ def _support_ff(self, d, name):+ """Leg torques that carry the robot's weight (static equilibrium with the feet's contact forces): tau =+ bias - J_c^T F, the weight split between the feet by where the centre of mass is (all of it on the support+ foot while the other is off the ground). Without it the stance legs sag under the PD and the kick drifts."""+ mj, m, rig = self.mj, self.m, self.rig+ com = d.subtree_com[rig.base_body].copy()+ W = float(m.body_subtreemass[rig.base_body]) * 9.81+ one_foot = name in ("lift", "swing", "follow", "retract")+ if one_foot:+ share = {self.sup: 1.0, self.foot: 0.0}+ else:+ pl, pr = d.site_xpos[self.site["left"]], d.site_xpos[self.site["right"]]+ ax = pl[:2] - pr[:2]+ t = float(np.clip((com[:2] - pr[:2]) @ ax / max(ax @ ax, 1e-9), 0.0, 1.0))+ share = {"left": t, "right": 1.0 - t}+ gen = np.zeros(m.nv)+ jp = np.zeros((3, m.nv)); jr = np.zeros((3, m.nv))+ for side, w in share.items():+ if w <= 0:+ continue+ p = d.site_xpos[self.site[side]]+ F = np.array([0.0, 0.0, w * W])+ r = np.array([com[0] - p[0], com[1] - p[1], 0.0])+ mj.mj_jacSite(m, d, jp, jr, self.site[side])+ gen += jp.T @ F + jr.T @ np.cross(r, F)+ return d.qfrc_bias[rig.lvadr] - gen[rig.lvadr]++ # ------------------------------------------------------------------ one control step+ def step(self, d):+ name, n, s = self._phase()+ rig = self.rig+ if name == "stand":+ k = minjerk(s)+ stand = rig.policy.default+ self.q = self.q_start + (stand - self.q_start) * k+ q = self.q+ if self.i == n - 1 and self.stand_extra < STAND_MAX:+ z = [d.site_xpos[self.site[sd]][2] for sd in ("left", "right")]+ vz = [np.linalg.norm(self._site_vel(d, sd)) for sd in ("left", "right")]+ if abs(z[0] - z[1]) > 0.006 or max(vz) > 0.05: # a foot still in the air or moving: wait+ self.stand_extra += 1+ self.ff = self._support_ff(d, name)+ return q.copy() # (the step counter stays)+ if self.i == n - 1: # the stance reached: the feet as they are now, the pelvis+ self.feet0 = {sd: d.site_xpos[self.site[sd]].copy() for sd in ("left", "right")}+ p_now, R_now = rig.pelvis(d) # the pelvis as it stands (the support torques hold it+ self.p0 = p_now.copy() # there: no sag, no creeping); its tilt is kept+ self.qpel0 = np.zeros(4)+ self.mj.mju_mat2Quat(self.qpel0, R_now.reshape(-1))+ c = self._balance_target()+ dl = c - d.subtree_com[rig.base_body]+ self.delta = np.array([dl[0], dl[1], -CROUCH]) # and a little lower: room for the support leg+ mid = 0.5 * (self.feet0["left"] + self.feet0["right"]) + self.fw * FOOT_STRIKE_FORWARD+ self.com_start = np.r_[mid[:2], 0.0] # the shift starts from the middle of the feet+ else:+ if name == "unshift" and self.i == 0: # both feet down again: where the kicking foot landed+ self.feet0[self.foot] = d.site_xpos[self.site[self.foot]].copy()+ self.mid_end = 0.5 * (self.feet0["left"] + self.feet0["right"]) + self.fw * FOOT_STRIKE_FORWARD+ if True: # balance: the capture point (CoM + v / omega) onto its+ com = d.subtree_com[rig.base_body] # target (the support foot's centre; on the way there during+ v = self._com_vel(d, com) # the shifts), the pelvis moved by the error+ bt = self._balance_target(d)+ if name == "shift":+ c = self.com_start + (bt - self.com_start) * minjerk(s)+ elif name == "unshift":+ c = bt + (self.mid_end - bt) * minjerk(s)+ elif name == "settle":+ c = self.mid_end+ else:+ c = bt+ xi = com[:2] + v[:2] / OMEGA+ err = c[:2] - xi+ e_loc = np.array([err @ self.fw[:2], err @ self.left_ax[:2]])+ self.com_off = np.clip(self.com_off + 0.05 * e_loc, -0.08, 0.08) # slow integral of the error+ self.com_fast = np.clip(1.3 * e_loc, -0.06, 0.06) # plus a direct term+ if name == "lower" and self.i == n - 1 and self.lower_extra < LOWER_MAX and \+ d.site_xpos[self.site[self.foot]][2] > self.feet0[self.foot][2] + 0.01:+ self.lower_extra += 1 # the foot not down yet: keep lowering+ self.i -= 1+ if name == "hold" and self.i == n - 1 and np.linalg.norm(e_loc) > 0.01 and self.hold_extra < HOLD_MAX:+ self.hold_extra += 1 # not settled yet: hold on+ self.i -= 1+ p_pel = self._pelvis_target(name, s)+ feet = {self.sup: self.feet0[self.sup], self.foot: self._kick_foot_target(name, s)}+ self.q = self._ik(d, p_pel, feet)+ q = self.q+ self.ff = self._support_ff(d, name)+ self.i += 1+ if self.i >= n:+ self.i = 0+ self.pi += 1+ if self.pi >= len(self.phases):+ self.done = True+ return q.copy()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/head_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/head_link.stlnew file mode 100644index 0000000000..9a687b6f68Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/head_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_pitch_link.stlnew file mode 100644index 0000000000..26fd113d1cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_roll_link.stlnew file mode 100644index 0000000000..64c8440b1cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_elbow_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_elbow_link.stlnew file mode 100644index 0000000000..2e3bcc0359Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_pitch_link.stlnew file mode 100644index 0000000000..fa2be04d4fBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_roll_link.stlnew file mode 100644index 0000000000..80f5c636f0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_yaw_link.stlnew file mode 100644index 0000000000..87acd9d78cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_knee_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_knee_link.stlnew file mode 100644index 0000000000..6e301535efBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_rubber_hand.stlnew file mode 100644index 0000000000..efcd64fe67Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_pitch_link.stlnew file mode 100644index 0000000000..9946d36c7bBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_roll_link.stlnew file mode 100644index 0000000000..47c8a6fc62Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_yaw_link.stlnew file mode 100644index 0000000000..ed007fd15eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_pitch_link.stlnew file mode 100644index 0000000000..7622aeda73Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_roll_link.stlnew file mode 100644index 0000000000..760a95030eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_yaw_link.stlnew file mode 100644index 0000000000..5d2dbbea9cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/logo_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/logo_link.stlnew file mode 100644index 0000000000..b3ef6197ffBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/logo_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/pelvis.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/pelvis.stlnew file mode 100644index 0000000000..bdec5cca41Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/pelvis.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/pelvis_contour_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/pelvis_contour_link.stlnew file mode 100644index 0000000000..dd144151eeBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/pelvis_contour_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_pitch_link.stlnew file mode 100644index 0000000000..302f4e98c0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_roll_link.stlnew file mode 100644index 0000000000..9b992e55e1Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_elbow_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_elbow_link.stlnew file mode 100644index 0000000000..161d89568aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_pitch_link.stlnew file mode 100644index 0000000000..ed34062feeBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_roll_link.stlnew file mode 100644index 0000000000..f544e5bb8eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_yaw_link.stlnew file mode 100644index 0000000000..66d519e64eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_knee_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_knee_link.stlnew file mode 100644index 0000000000..238d291e68Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_rubber_hand.stlnew file mode 100644index 0000000000..abcdfd3850Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_pitch_link.stlnew file mode 100644index 0000000000..8ed9408ffcBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_roll_link.stlnew file mode 100644index 0000000000..73642e511fBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_yaw_link.stlnew file mode 100644index 0000000000..9dd2c5aa83Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_pitch_link.stlnew file mode 100644index 0000000000..7aef0edb06Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_roll_link.stlnew file mode 100644index 0000000000..8ff67c7477Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_yaw_link.stlnew file mode 100644index 0000000000..163e832bfeBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/torso_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/torso_link_rev_1_0.stlnew file mode 100644index 0000000000..8bcdb1229dBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/torso_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/waist_roll_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/waist_roll_link_rev_1_0.stlnew file mode 100644index 0000000000..a0c249370eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/waist_roll_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/waist_yaw_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/waist_yaw_link_rev_1_0.stlnew file mode 100644index 0000000000..291dbe7c71Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes/waist_yaw_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/head_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/head_link.stlnew file mode 100644index 0000000000..b39d344584Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/head_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_pitch_link.stlnew file mode 100644index 0000000000..08c38c32ceBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_roll_link.stlnew file mode 100644index 0000000000..41025f4050Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_elbow_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_elbow_link.stlnew file mode 100644index 0000000000..6fbc2a6fcbBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_pitch_link.stlnew file mode 100644index 0000000000..a9fcc7e61fBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_roll_link.stlnew file mode 100644index 0000000000..907db4c599Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_yaw_link.stlnew file mode 100644index 0000000000..9d2bcf3a84Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_knee_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_knee_link.stlnew file mode 100644index 0000000000..c9026a83d4Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_rubber_hand.stlnew file mode 100644index 0000000000..d7f9fce032Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_pitch_link.stlnew file mode 100644index 0000000000..5e3b5e0d0bBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_roll_link.stlnew file mode 100644index 0000000000..51635e335aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_yaw_link.stlnew file mode 100644index 0000000000..ccea58c6b9Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_pitch_link.stlnew file mode 100644index 0000000000..72db7ab8ffBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_roll_link.stlnew file mode 100644index 0000000000..2f3dad2903Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_yaw_link.stlnew file mode 100644index 0000000000..7a6f6c777dBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/lod.json b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/lod.jsonnew file mode 100644index 0000000000..fbf46adbbe--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/lod.json@@ -0,0 +1,224 @@+{+ "files": {+ "head_link.stl": {+ "sha256": "b0b7459e77a9b361cbd3b42d75cdf8f54280e5771ae6655890920a15048d31e0",+ "source": "head_link.STL",+ "source_sha256": "005fb67fbd3eff94aa8bf4a6e83238174e9f91b6721f7111594322f223724411",+ "triangles": 1184+ },+ "left_ankle_pitch_link.stl": {+ "sha256": "d61e414cbeb7f87800c8216959a5d4f34dea746fcdf390f6920f7abe7f473d82",+ "source": "left_ankle_pitch_link.STL",+ "source_sha256": "d49e3abc6f5b12e532062cd575b87b5ef40cd2a3fc18f54a1ca5bba4f773d51d",+ "triangles": 90+ },+ "left_ankle_roll_link.stl": {+ "sha256": "ac56add2f6f6c4cd2b3b33274d8b8a10b49acceed658cffc6b36cb4a317923ea",+ "source": "left_ankle_roll_link.STL",+ "source_sha256": "c4092af943141d4d9f74232f3cfa345afc6565f46a077793b8ae0e68b39dc33f",+ "triangles": 830+ },+ "left_elbow_link.stl": {+ "sha256": "6043e71584dec9e8832f1e1e0e061074ad868ed4cf83c63a2684a47650547b32",+ "source": "left_elbow_link.STL",+ "source_sha256": "fa752198accd104d5c4c3a01382e45165b944fbbc5acce085059223324e5bed3",+ "triangles": 111+ },+ "left_hip_pitch_link.stl": {+ "sha256": "7c5fe35b1d28fad41dbe2865dd6a395255ab54911e5702ea11553635b808261e",+ "source": "left_hip_pitch_link.STL",+ "source_sha256": "4725168105ee768ee31638ef22b53f6be2d7641bfd7cfefe803488d884776fa4",+ "triangles": 230+ },+ "left_hip_roll_link.stl": {+ "sha256": "7e0f0ff6a935a6bdf79dd79b7cd206b6225ef1d813aa81bad3b1e8627fae4f24",+ "source": "left_hip_roll_link.STL",+ "source_sha256": "91f25922ee8a7c3152790051bebad17b4d9cd243569c38fe340285ff93a97acf",+ "triangles": 244+ },+ "left_hip_yaw_link.stl": {+ "sha256": "cf13b4e40a0f06ee8f3cf89e5e2a962223912251dd8707a5f8474e66b3df7e5c",+ "source": "left_hip_yaw_link.STL",+ "source_sha256": "a16d88aa6ddac8083aa7ad55ed317bea44b1fa003d314fba88965b7ed0f3b55b",+ "triangles": 377+ },+ "left_knee_link.stl": {+ "sha256": "78fa5f7cfea0b075e32de93ee5303cfcb3fe30b21cbb9422d9d3e307ef513530",+ "source": "left_knee_link.STL",+ "source_sha256": "8d92b9e3d3a636761150bb8025e32514c4602b91c7028d523ee42b3e632de477",+ "triangles": 1226+ },+ "left_rubber_hand.stl": {+ "sha256": "03a87a3e22dddf9d77fb7ce8189ead6629e90cde3ad8479acf4480afd15f3926",+ "source": "left_rubber_hand.STL",+ "source_sha256": "cff2221a690fa69303f61fce68f2d155c1517b52efb6ca9262dd56e0bc6e70fe",+ "triangles": 2906+ },+ "left_shoulder_pitch_link.stl": {+ "sha256": "3163bd3e1e473e4fa48900a74c844a5647b46f6c6ae30e94a1d51183d026cc75",+ "source": "left_shoulder_pitch_link.STL",+ "source_sha256": "f0d1cfd02fcf0d42f95e678eeca33da3afbcc366ffba5c052847773ec4f31d52",+ "triangles": 224+ },+ "left_shoulder_roll_link.stl": {+ "sha256": "8fe40e7a3c4c62735346e16900e1bf3de7e9373273bb881f232c4a0be7ca470d",+ "source": "left_shoulder_roll_link.STL",+ "source_sha256": "fb9df21687773522598dc384f1a2945c7519f11cbc8bd372a49170316d6eee88",+ "triangles": 508+ },+ "left_shoulder_yaw_link.stl": {+ "sha256": "2ef7a79abb015d2fefed54ced7c46b7949c3c6dcb774b6500b2f59522a7ebd52",+ "source": "left_shoulder_yaw_link.STL",+ "source_sha256": "1aa97e9748e924336567992181f78c7cd0652fd52a4afcca3df6b2ef6f9e712e",+ "triangles": 316+ },+ "left_wrist_pitch_link.stl": {+ "sha256": "50baada401939b9ee9e8cd03988f1ad800727394491eef6f4dd88a136f8f1f12",+ "source": "left_wrist_pitch_link.STL",+ "source_sha256": "b251d8e05047f695d0f536cd78c11973cfa4e78d08cfe82759336cc3471de3a9",+ "triangles": 108+ },+ "left_wrist_roll_link.stl": {+ "sha256": "233ba263c0ad165460af24c49172d112c476333c64c23cc65f4eec130f75defc",+ "source": "left_wrist_roll_link.STL",+ "source_sha256": "edc387c9a0ba8c2237e9b296d32531426fabeb6f53e58df45c76106bca74148c",+ "triangles": 452+ },+ "left_wrist_yaw_link.stl": {+ "sha256": "354af14f646a5a29a41142ed1436e9dbda1903755ebe96030d4b518cde989445",+ "source": "left_wrist_yaw_link.STL",+ "source_sha256": "83f8fb3a726bf9613d65dd14f0f447cb918c3c95b3938042a0c9c09749267d3b",+ "triangles": 404+ },+ "logo_link.stl": {+ "sha256": "555ec8563662a7d9dc8c02d731a9657fa77194858a3a252f444aa946aa5f339e",+ "source": "logo_link.STL",+ "source_sha256": "8571a0a19bc4916fa55f91449f51d5fdefd751000054865a842449429d5f155b",+ "triangles": 306+ },+ "pelvis.stl": {+ "sha256": "a5e7b076649f4899a0fbfcf7e1ee0368cf84fbb2e68bab695398ab6c1ca77d99",+ "source": "pelvis.STL",+ "source_sha256": "5ba6bbc888e630550140d3c26763f10206da8c8bd30ed886b8ede41c61f57a31",+ "triangles": 1349+ },+ "pelvis_contour_link.stl": {+ "sha256": "d016ed38115363429e2740aaa047dbd1d4e49fe796f24232099ade2295adcaa0",+ "source": "pelvis_contour_link.STL",+ "source_sha256": "5cc5c2c7a312329e3feeb2b03d3fc09fc29705bd01864f6767e51be959662420",+ "triangles": 8692+ },+ "right_ankle_pitch_link.stl": {+ "sha256": "0c5c9eca53d7370207426be70e45032afcb9f41be13dce246f259e5252e0c6b7",+ "source": "right_ankle_pitch_link.STL",+ "source_sha256": "15be426539ec1be70246d4d82a168806db64a41301af8b35c197a33348c787a9",+ "triangles": 90+ },+ "right_ankle_roll_link.stl": {+ "sha256": "e3ac204d29d5f91e97e1cef60691d5edb1fdda026b954e2169c914ab541cffd3",+ "source": "right_ankle_roll_link.STL",+ "source_sha256": "4b66222ea56653e627711b56d0a8949b4920da5df091da0ceb343f54e884e3a5",+ "triangles": 830+ },+ "right_elbow_link.stl": {+ "sha256": "233ae8c8f2f55588be7cc6d17cfaa66f9b5c37d0eaf32dbdee3807542478244d",+ "source": "right_elbow_link.STL",+ "source_sha256": "1be925d7aa268bb8fddf5362b9173066890c7d32092c05638608126e59d1e2ab",+ "triangles": 112+ },+ "right_hip_pitch_link.stl": {+ "sha256": "9b744118b6b7ffe69d7982ce4579eb20b35a9496b8a13d6aa6ab3145f1163e34",+ "source": "right_hip_pitch_link.STL",+ "source_sha256": "e4f3c99d7f4a7d34eadbef9461fc66e3486cb5442db1ec50c86317d459f1a9c6",+ "triangles": 230+ },+ "right_hip_roll_link.stl": {+ "sha256": "4c9c886c2977ba0881e87a3ed9712a90a149e5e996cb7a47b7c263926fa99856",+ "source": "right_hip_roll_link.STL",+ "source_sha256": "4c254ef66a356f492947f360dd931965477b631e3fcc841f91ccc46d945d54f6",+ "triangles": 244+ },+ "right_hip_yaw_link.stl": {+ "sha256": "79954979142fddcf9f234c3cf8b946529ac2b87bc18295b762bf305885e80051",+ "source": "right_hip_yaw_link.STL",+ "source_sha256": "e479c2936ca2057e9eb2f7dff6c189b7419d7b8484dea0b298cbb36a2a6aa668",+ "triangles": 376+ },+ "right_knee_link.stl": {+ "sha256": "807714c0d515988cbc17ee929e91e4538e3ce16d867d11fd0b07b2153d5dc210",+ "source": "right_knee_link.STL",+ "source_sha256": "63c4008449c9bbe701a6e2b557b7a252e90cf3a5abcf54cee46862b9a69f8ec8",+ "triangles": 1098+ },+ "right_rubber_hand.stl": {+ "sha256": "6ba8ebbdf198df47a175a0fc8c7c14597ebb7e2b6bfeae81f538baf6452aa03f",+ "source": "right_rubber_hand.STL",+ "source_sha256": "99533b778bca6246144fa511bb9d4e555e075c641f2a0251e04372869cd99d67",+ "triangles": 2786+ },+ "right_shoulder_pitch_link.stl": {+ "sha256": "c0ccf9540f9cbde63165983e7b62d9aa58ef38e8c552d0e3fcff75f7fec5d715",+ "source": "right_shoulder_pitch_link.STL",+ "source_sha256": "24cdb387e0128dfe602770a81c56cdce3a0181d34d039a11d1aaf8819b7b8c02",+ "triangles": 224+ },+ "right_shoulder_roll_link.stl": {+ "sha256": "e5787ae15464c086f4542b29c2dab43f5bd528c5f3ee56f2812545fe5e519bdf",+ "source": "right_shoulder_roll_link.STL",+ "source_sha256": "962b97c48f9ce9e8399f45dd9522e0865d19aa9fd299406b2d475a8fc4a53e81",+ "triangles": 510+ },+ "right_shoulder_yaw_link.stl": {+ "sha256": "f4a044687ef796f79e286a3bad4dc2c80be65b212132f938e3582a3ca268e399",+ "source": "right_shoulder_yaw_link.STL",+ "source_sha256": "a0b76489271da0c72461a344c9ffb0f0c6e64f019ea5014c1624886c442a2fe5",+ "triangles": 318+ },+ "right_wrist_pitch_link.stl": {+ "sha256": "226f48f17024005dccaa4f3d3ad5f7e8e16bc357a1aba87de173b20cc6ce6d82",+ "source": "right_wrist_pitch_link.STL",+ "source_sha256": "d22f8f3b3127f15a63e5be1ee273cd5075786c3142f1c3d9f76cbf43d2a26477",+ "triangles": 100+ },+ "right_wrist_roll_link.stl": {+ "sha256": "fec3af45b3b66aa16bf046cb320f72d0c9933dfed6266e253d78f9223ae925c9",+ "source": "right_wrist_roll_link.STL",+ "source_sha256": "a7ee9212ff5b94d6cb7f52bb1bbf3f352194d5b598acff74f4c77d340c5b344f",+ "triangles": 452+ },+ "right_wrist_yaw_link.stl": {+ "sha256": "b1f689265c15a16c51cd48cbcae54485486a95596de623b8d13b003456295200",+ "source": "right_wrist_yaw_link.STL",+ "source_sha256": "bc9dece2d12509707e0057ba2e48df8f3d56db0c79410212963a25e8a50f61a6",+ "triangles": 434+ },+ "torso_link_rev_1_0.stl": {+ "sha256": "3edf21bb662f94969e70da9a8688851c11cc7a5539ffd7548a2fe0caf16040f7",+ "source": "torso_link_rev_1_0.STL",+ "source_sha256": "11ddb46f2098efbbd8816b1d65893632d8e78be936376c7cdcd6771899ccc723",+ "triangles": 3267+ },+ "waist_roll_link_rev_1_0.stl": {+ "sha256": "8d994abdb0d933c51fa1e70f3f409b68cb505f4b4fe230f9e52267e96102ef51",+ "source": "waist_roll_link_rev_1_0.STL",+ "source_sha256": "b67c347a05abc3e8ddae600d98a082bee273bb39f8e651647708b0a7140a8a97",+ "triangles": 108+ },+ "waist_yaw_link_rev_1_0.stl": {+ "sha256": "8cc0d812b24b8ce39eb563e74e90570415c4016242a290a557276a5afe2c3284",+ "source": "waist_yaw_link_rev_1_0.STL",+ "source_sha256": "ec6db442b11f25eed898b5add07940c85d804f300de24dcbd264ccd8be7d554c",+ "triangles": 786+ }+ },+ "level": "25k",+ "note": "Levels of detail of the library's robots (the players' images, renderer rule 6; user decision D1, 2026-10-08): a robot's fine meshes (meshes_fine/, the unchanged upstream meshes, not in git) decimated to a triangle budget and committed as meshes_<level>/ (e.g. meshes_25k/), so that a sport draws its players' images of the robot with the appearance of the real robot at a small cost (a body's mount(..., lod=\"25k\")).",+ "robot": "unitree_g1",+ "source_triangles": 393270,+ "target_triangles": 25000,+ "tools": {+ "fast-simplification": "0.2.0",+ "trimesh": "5.1.1"+ },+ "triangles": 31522+}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/logo_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/logo_link.stlnew file mode 100644index 0000000000..26947d877cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/logo_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis.stlnew file mode 100644index 0000000000..4d4e3d8296Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis_contour_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis_contour_link.stlnew file mode 100644index 0000000000..b9747ed8c7Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis_contour_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_pitch_link.stlnew file mode 100644index 0000000000..b1712477dcBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_roll_link.stlnew file mode 100644index 0000000000..7671142be0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_elbow_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_elbow_link.stlnew file mode 100644index 0000000000..501a46b885Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_pitch_link.stlnew file mode 100644index 0000000000..84be1f9232Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_roll_link.stlnew file mode 100644index 0000000000..eeaac37289Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_yaw_link.stlnew file mode 100644index 0000000000..d91378c241Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_knee_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_knee_link.stlnew file mode 100644index 0000000000..94b2f41031Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_rubber_hand.stlnew file mode 100644index 0000000000..2e40f4a68aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_pitch_link.stlnew file mode 100644index 0000000000..633ab8a7daBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_roll_link.stlnew file mode 100644index 0000000000..97cc10dd87Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_yaw_link.stlnew file mode 100644index 0000000000..bbef2ead35Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_pitch_link.stlnew file mode 100644index 0000000000..0dee469ca5Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_roll_link.stlnew file mode 100644index 0000000000..8069b6ae41Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_yaw_link.stlnew file mode 100644index 0000000000..db62034ff0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/torso_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/torso_link_rev_1_0.stlnew file mode 100644index 0000000000..25f5e97ab9Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/torso_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stlnew file mode 100644index 0000000000..a7d09b7bfdBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stlnew file mode 100644index 0000000000..5f750aad7aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/model.xml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/model.xmlnew file mode 100644index 0000000000..e089140a20--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/model.xml@@ -0,0 +1,265 @@+<mujoco model="unitree_g1">+ <!-- Generated by bodies/unitree_g1/tools/make_model.py from MuJoCo Menagerie unitree_g1/g1.xml (commit f054586a8e90465d49ee5be15335c4a0c7f57caf, BSD-3-Clause, LICENSE; derived from Unitree's g1_description g1_29dof_rev_1_0). Template of the RoboOlympics Unitree G1 body: read by body.py, which prefixes every name, picks the mesh level and mounts the hand and the motors. Do not edit. -->+ <compiler angle="radian" meshdir="meshes" autolimits="true" />+ <default>+ <default class="g1_g1">+ <site rgba="1 0 0 1" size="0.01" group="5" />+ <joint armature="0.01" frictionloss="0.3" />+ <position kp="500" dampratio="1" inheritrange="1" />+ <default class="g1_visual">+ <geom group="2" type="mesh" contype="0" conaffinity="0" density="0" material="g1_m_metal" />+ </default>+ <default class="g1_collision">+ <geom group="3" type="mesh" contype="4" conaffinity="0" />+ <default class="g1_foot">+ <geom type="sphere" size="0.005" priority="1" friction="0.6" condim="3" contype="1" conaffinity="1" />+ </default>+ </default>+ </default>+ </default>+ <asset>+ <material name="g1_m_black" rgba="0.2 0.2 0.2 1" />+ <material name="g1_m_metal" rgba="0.7 0.7 0.7 1" />+ <mesh file="pelvis.stl" name="g1_pelvis" />+ <mesh file="pelvis_contour_link.stl" name="g1_pelvis_contour_link" />+ <mesh file="left_hip_pitch_link.stl" name="g1_left_hip_pitch_link" />+ <mesh file="left_hip_roll_link.stl" name="g1_left_hip_roll_link" />+ <mesh file="left_hip_yaw_link.stl" name="g1_left_hip_yaw_link" />+ <mesh file="left_knee_link.stl" name="g1_left_knee_link" />+ <mesh file="left_ankle_pitch_link.stl" name="g1_left_ankle_pitch_link" />+ <mesh file="left_ankle_roll_link.stl" name="g1_left_ankle_roll_link" />+ <mesh file="right_hip_pitch_link.stl" name="g1_right_hip_pitch_link" />+ <mesh file="right_hip_roll_link.stl" name="g1_right_hip_roll_link" />+ <mesh file="right_hip_yaw_link.stl" name="g1_right_hip_yaw_link" />+ <mesh file="right_knee_link.stl" name="g1_right_knee_link" />+ <mesh file="right_ankle_pitch_link.stl" name="g1_right_ankle_pitch_link" />+ <mesh file="right_ankle_roll_link.stl" name="g1_right_ankle_roll_link" />+ <mesh name="g1_waist_yaw_link" file="waist_yaw_link_rev_1_0.stl" />+ <mesh name="g1_waist_roll_link" file="waist_roll_link_rev_1_0.stl" />+ <mesh name="g1_torso_link" file="torso_link_rev_1_0.stl" />+ <mesh file="logo_link.stl" name="g1_logo_link" />+ <mesh file="head_link.stl" name="g1_head_link" />+ <mesh file="left_shoulder_pitch_link.stl" name="g1_left_shoulder_pitch_link" />+ <mesh file="left_shoulder_roll_link.stl" name="g1_left_shoulder_roll_link" />+ <mesh file="left_shoulder_yaw_link.stl" name="g1_left_shoulder_yaw_link" />+ <mesh file="left_elbow_link.stl" name="g1_left_elbow_link" />+ <mesh file="left_wrist_roll_link.stl" name="g1_left_wrist_roll_link" />+ <mesh file="left_wrist_pitch_link.stl" name="g1_left_wrist_pitch_link" />+ <mesh file="left_wrist_yaw_link.stl" name="g1_left_wrist_yaw_link" />+ <mesh file="left_rubber_hand.stl" name="g1_left_rubber_hand" />+ <mesh file="right_shoulder_pitch_link.stl" name="g1_right_shoulder_pitch_link" />+ <mesh file="right_shoulder_roll_link.stl" name="g1_right_shoulder_roll_link" />+ <mesh file="right_shoulder_yaw_link.stl" name="g1_right_shoulder_yaw_link" />+ <mesh file="right_elbow_link.stl" name="g1_right_elbow_link" />+ <mesh file="right_wrist_roll_link.stl" name="g1_right_wrist_roll_link" />+ <mesh file="right_wrist_pitch_link.stl" name="g1_right_wrist_pitch_link" />+ <mesh file="right_wrist_yaw_link.stl" name="g1_right_wrist_yaw_link" />+ <mesh file="right_rubber_hand.stl" name="g1_right_rubber_hand" />+ </asset>+ <worldbody>+ <body name="pelvis" pos="0 0 0.793" childclass="g1_g1">+ <inertial pos="0 0 -0.07605" quat="1 0 -0.000399148 0" mass="3.813" diaginertia="0.010549 0.0093089 0.0079184" />+ <freejoint name="floating_base_joint" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_pelvis" />+ <geom class="g1_visual" mesh="g1_pelvis_contour_link" />+ <geom class="g1_collision" mesh="g1_pelvis_contour_link" />+ <site name="imu_in_pelvis" pos="0.04525 0 -0.08339" size="0.01" />+ <body name="left_hip_pitch_link" pos="0 0.064452 -0.1027">+ <inertial pos="0.002741 0.047791 -0.02606" quat="0.954862 0.293964 0.0302556 0.030122" mass="1.35" diaginertia="0.00181517 0.00153422 0.00116212" />+ <joint name="left_hip_pitch_joint" axis="0 1 0" range="-2.5307 2.8798" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_left_hip_pitch_link" />+ <geom class="g1_collision" material="g1_m_black" mesh="g1_left_hip_pitch_link" />+ <body name="left_hip_roll_link" pos="0 0.052 -0.030465" quat="0.996179 0 -0.0873386 0">+ <inertial pos="0.029812 -0.001045 -0.087934" quat="0.977808 -1.97119e-05 0.205576 -0.0403793" mass="1.52" diaginertia="0.00254986 0.00241169 0.00148755" />+ <joint name="left_hip_roll_joint" axis="1 0 0" range="-0.5236 2.9671" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_left_hip_roll_link" />+ <geom class="g1_collision" mesh="g1_left_hip_roll_link" />+ <body name="left_hip_yaw_link" pos="0.025001 0 -0.12412">+ <inertial pos="-0.057709 -0.010981 -0.15078" quat="0.600598 0.15832 0.223482 0.751181" mass="1.702" diaginertia="0.00776166 0.00717575 0.00160139" />+ <joint name="left_hip_yaw_joint" axis="0 0 1" range="-2.7576 2.7576" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" mesh="g1_left_hip_yaw_link" />+ <geom class="g1_collision" mesh="g1_left_hip_yaw_link" />+ <body name="left_knee_link" pos="-0.078273 0.0021489 -0.17734" quat="0.996179 0 0.0873386 0">+ <inertial pos="0.005457 0.003964 -0.12074" quat="0.923418 -0.0327699 0.0158246 0.382067" mass="1.932" diaginertia="0.0113804 0.0112778 0.00146458" />+ <joint name="left_knee_joint" axis="0 1 0" range="-0.087267 2.8798" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_left_knee_link" />+ <geom class="g1_collision" mesh="g1_left_knee_link" />+ <body name="left_ankle_pitch_link" pos="0 -9.4445e-05 -0.30001">+ <inertial pos="-0.007269 0 0.011137" quat="0.603053 0.369225 0.369225 0.603053" mass="0.074" diaginertia="1.89e-05 1.40805e-05 6.9195e-06" />+ <joint name="left_ankle_pitch_joint" axis="0 1 0" range="-0.87267 0.5236" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_left_ankle_pitch_link" />+ <geom class="g1_collision" mesh="g1_left_ankle_pitch_link" />+ <body name="left_ankle_roll_link" pos="0 0 -0.017558">+ <inertial pos="0.026505 0 -0.016425" quat="-0.000481092 0.728482 -0.000618967 0.685065" mass="0.608" diaginertia="0.00167218 0.0016161 0.000217621" />+ <joint name="left_ankle_roll_joint" axis="1 0 0" range="-0.2618 0.2618" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_left_ankle_roll_link" />+ <geom class="g1_foot" pos="-0.05 0.025 -0.03" />+ <geom class="g1_foot" pos="-0.05 -0.025 -0.03" />+ <geom class="g1_foot" pos="0.12 0.03 -0.03" />+ <geom class="g1_foot" pos="0.12 -0.03 -0.03" />+ <site name="left_foot" />+ <geom name="left_foot_strike" type="box" pos="0.035 0 -0.02" size="0.105 0.04 0.022" contype="8" conaffinity="0" group="3" mass="0" density="0" rgba="0.2 0.6 0.9 0.3" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="right_hip_pitch_link" pos="0 -0.064452 -0.1027">+ <inertial pos="0.002741 -0.047791 -0.02606" quat="0.954862 -0.293964 0.0302556 -0.030122" mass="1.35" diaginertia="0.00181517 0.00153422 0.00116212" />+ <joint name="right_hip_pitch_joint" axis="0 1 0" range="-2.5307 2.8798" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_right_hip_pitch_link" />+ <geom class="g1_collision" material="g1_m_black" mesh="g1_right_hip_pitch_link" />+ <body name="right_hip_roll_link" pos="0 -0.052 -0.030465" quat="0.996179 0 -0.0873386 0">+ <inertial pos="0.029812 0.001045 -0.087934" quat="0.977808 1.97119e-05 0.205576 0.0403793" mass="1.52" diaginertia="0.00254986 0.00241169 0.00148755" />+ <joint name="right_hip_roll_joint" axis="1 0 0" range="-2.9671 0.5236" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_right_hip_roll_link" />+ <geom class="g1_collision" mesh="g1_right_hip_roll_link" />+ <body name="right_hip_yaw_link" pos="0.025001 0 -0.12412">+ <inertial pos="-0.057709 0.010981 -0.15078" quat="0.751181 0.223482 0.15832 0.600598" mass="1.702" diaginertia="0.00776166 0.00717575 0.00160139" />+ <joint name="right_hip_yaw_joint" axis="0 0 1" range="-2.7576 2.7576" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" mesh="g1_right_hip_yaw_link" />+ <geom class="g1_collision" mesh="g1_right_hip_yaw_link" />+ <body name="right_knee_link" pos="-0.078273 -0.0021489 -0.17734" quat="0.996179 0 0.0873386 0">+ <inertial pos="0.005457 -0.003964 -0.12074" quat="0.923439 0.0345276 0.0116333 -0.382012" mass="1.932" diaginertia="0.011374 0.0112843 0.00146452" />+ <joint name="right_knee_joint" axis="0 1 0" range="-0.087267 2.8798" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_right_knee_link" />+ <geom class="g1_collision" mesh="g1_right_knee_link" />+ <body name="right_ankle_pitch_link" pos="0 9.4445e-05 -0.30001">+ <inertial pos="-0.007269 0 0.011137" quat="0.603053 0.369225 0.369225 0.603053" mass="0.074" diaginertia="1.89e-05 1.40805e-05 6.9195e-06" />+ <joint name="right_ankle_pitch_joint" axis="0 1 0" range="-0.87267 0.5236" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_right_ankle_pitch_link" />+ <geom class="g1_collision" mesh="g1_right_ankle_pitch_link" />+ <body name="right_ankle_roll_link" pos="0 0 -0.017558">+ <inertial pos="0.026505 0 -0.016425" quat="0.000481092 0.728482 0.000618967 0.685065" mass="0.608" diaginertia="0.00167218 0.0016161 0.000217621" />+ <joint name="right_ankle_roll_joint" axis="1 0 0" range="-0.2618 0.2618" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_right_ankle_roll_link" />+ <geom class="g1_foot" pos="-0.05 0.025 -0.03" />+ <geom class="g1_foot" pos="-0.05 -0.025 -0.03" />+ <geom class="g1_foot" pos="0.12 0.03 -0.03" />+ <geom class="g1_foot" pos="0.12 -0.03 -0.03" />+ <site name="right_foot" />+ <geom name="right_foot_strike" type="box" pos="0.035 0 -0.02" size="0.105 0.04 0.022" contype="8" conaffinity="0" group="3" mass="0" density="0" rgba="0.2 0.6 0.9 0.3" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="waist_yaw_link">+ <inertial pos="0.003494 0.000233 0.018034" quat="0.289697 0.591001 -0.337795 0.672821" mass="0.214" diaginertia="0.000163531 0.000107714 0.000102205" />+ <joint name="waist_yaw_joint" axis="0 0 1" range="-2.618 2.618" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" mesh="g1_waist_yaw_link" />+ <body name="waist_roll_link" pos="-0.0039635 0 0.044">+ <inertial pos="0 2.3e-05 0" quat="0.5 0.5 -0.5 0.5" mass="0.086" diaginertia="8.245e-06 7.079e-06 6.339e-06" />+ <joint name="waist_roll_joint" axis="1 0 0" range="-0.52 0.52" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_waist_roll_link" />+ <body name="torso_link">+ <inertial pos="0.00203158 0.000339683 0.184568" quat="0.999803 -6.03319e-05 0.0198256 0.00131986" mass="7.818" diaginertia="0.121847 0.109825 0.0273735" />+ <joint name="waist_pitch_joint" axis="0 1 0" range="-0.52 0.52" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_torso_link" />+ <geom class="g1_collision" mesh="g1_torso_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_visual" material="g1_m_black" mesh="g1_logo_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_collision" material="g1_m_black" mesh="g1_logo_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_visual" material="g1_m_black" mesh="g1_head_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_collision" material="g1_m_black" mesh="g1_head_link" />+ <site name="imu_in_torso" pos="-0.03959 -0.00224 0.14792" size="0.01" />+ <body name="left_shoulder_pitch_link" pos="0.0039563 0.10022 0.24778" quat="0.990264 0.139201 1.38722e-05 -9.86868e-05">+ <inertial pos="0 0.035892 -0.011628" quat="0.654152 0.0130458 -0.326267 0.68225" mass="0.718" diaginertia="0.000465864 0.000432842 0.000406394" />+ <joint name="left_shoulder_pitch_joint" axis="0 1 0" range="-3.0892 2.6704" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_shoulder_pitch_link" />+ <geom size="0.03 0.025" pos="0 0.04 -0.01" quat="0.707107 0 0.707107 0" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="left_shoulder_roll_link" pos="0 0.038 -0.013831" quat="0.990268 -0.139172 0 0">+ <inertial pos="-0.000227 0.00727 -0.063243" quat="0.701256 -0.0196223 -0.00710317 0.712604" mass="0.643" diaginertia="0.000691311 0.000618011 0.000388977" />+ <joint name="left_shoulder_roll_joint" axis="1 0 0" range="-1.5882 2.2515" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_shoulder_roll_link" />+ <geom size="0.03 0.015" pos="-0.004 0.006 -0.053" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="left_shoulder_yaw_link" pos="0 0.00624 -0.1032">+ <inertial pos="0.010773 -0.002949 -0.072009" quat="0.716879 -0.0964829 -0.0679942 0.687134" mass="0.734" diaginertia="0.00106187 0.00103217 0.000400661" />+ <joint name="left_shoulder_yaw_joint" axis="0 0 1" range="-2.618 2.618" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_shoulder_yaw_link" />+ <geom class="g1_collision" mesh="g1_left_shoulder_yaw_link" />+ <body name="left_elbow_link" pos="0.015783 0 -0.080518">+ <inertial pos="0.064956 0.004454 -0.010062" quat="0.541765 0.636132 0.388821 0.388129" mass="0.6" diaginertia="0.000443035 0.000421612 0.000259353" />+ <joint name="left_elbow_joint" axis="0 1 0" range="-1.0472 2.0944" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_elbow_link" />+ <geom class="g1_collision" mesh="g1_left_elbow_link" />+ <body name="left_wrist_roll_link" pos="0.1 0.00188791 -0.01">+ <inertial pos="0.0171394 0.000537591 4.8864e-07" quat="0.575338 0.411667 -0.574906 0.411094" mass="0.085445" diaginertia="5.48211e-05 4.96646e-05 3.57798e-05" />+ <joint name="left_wrist_roll_joint" axis="1 0 0" range="-1.97222 1.97222" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_wrist_roll_link" />+ <geom class="g1_collision" mesh="g1_left_wrist_roll_link" />+ <body name="left_wrist_pitch_link" pos="0.038 0 0">+ <inertial pos="0.0229999 -0.00111685 -0.00111658" quat="0.249998 0.661363 0.293036 0.643608" mass="0.48405" diaginertia="0.000430353 0.000429873 0.000164648" />+ <joint name="left_wrist_pitch_joint" axis="0 1 0" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_left_wrist_pitch_link" />+ <geom class="g1_collision" mesh="g1_left_wrist_pitch_link" />+ <body name="left_wrist_yaw_link" pos="0.046 0 0">+ <inertial pos="0.0708244 0.000191745 0.00161742" quat="0.510571 0.526295 0.468078 0.493188" mass="0.254576" diaginertia="0.000646113 0.000559993 0.000147566" />+ <joint name="left_wrist_yaw_joint" axis="0 0 1" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_left_wrist_yaw_link" />+ <geom class="g1_collision" mesh="g1_left_wrist_yaw_link" />+ <geom pos="0.0415 0.003 0" quat="1 0 0 0" class="g1_visual" mesh="g1_left_rubber_hand" />+ <body name="left_mount" pos="0.08 0.0030 0" quat="0.7071068 0 0.7071068 0" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="right_shoulder_pitch_link" pos="0.0039563 -0.10021 0.24778" quat="0.990264 -0.139201 1.38722e-05 9.86868e-05">+ <inertial pos="0 -0.035892 -0.011628" quat="0.68225 -0.326267 0.0130458 0.654152" mass="0.718" diaginertia="0.000465864 0.000432842 0.000406394" />+ <joint name="right_shoulder_pitch_joint" axis="0 1 0" range="-3.0892 2.6704" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_shoulder_pitch_link" />+ <geom size="0.03 0.025" pos="0 -0.04 -0.01" quat="0.707107 0 0.707107 0" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="right_shoulder_roll_link" pos="0 -0.038 -0.013831" quat="0.990268 0.139172 0 0">+ <inertial pos="-0.000227 -0.00727 -0.063243" quat="0.712604 -0.00710317 -0.0196223 0.701256" mass="0.643" diaginertia="0.000691311 0.000618011 0.000388977" />+ <joint name="right_shoulder_roll_joint" axis="1 0 0" range="-2.2515 1.5882" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_shoulder_roll_link" />+ <geom size="0.03 0.015" pos="-0.004 -0.006 -0.053" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="right_shoulder_yaw_link" pos="0 -0.00624 -0.1032">+ <inertial pos="0.010773 0.002949 -0.072009" quat="0.687134 -0.0679942 -0.0964829 0.716879" mass="0.734" diaginertia="0.00106187 0.00103217 0.000400661" />+ <joint name="right_shoulder_yaw_joint" axis="0 0 1" range="-2.618 2.618" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_shoulder_yaw_link" />+ <geom class="g1_collision" mesh="g1_right_shoulder_yaw_link" />+ <body name="right_elbow_link" pos="0.015783 0 -0.080518">+ <inertial pos="0.064956 -0.004454 -0.010062" quat="0.388129 0.388821 0.636132 0.541765" mass="0.6" diaginertia="0.000443035 0.000421612 0.000259353" />+ <joint name="right_elbow_joint" axis="0 1 0" range="-1.0472 2.0944" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_elbow_link" />+ <geom class="g1_collision" mesh="g1_right_elbow_link" />+ <body name="right_wrist_roll_link" pos="0.1 -0.00188791 -0.01">+ <inertial pos="0.0171394 -0.000537591 4.8864e-07" quat="0.411667 0.575338 -0.411094 0.574906" mass="0.085445" diaginertia="5.48211e-05 4.96646e-05 3.57798e-05" />+ <joint name="right_wrist_roll_joint" axis="1 0 0" range="-1.97222 1.97222" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_wrist_roll_link" />+ <geom class="g1_collision" mesh="g1_right_wrist_roll_link" />+ <body name="right_wrist_pitch_link" pos="0.038 0 0">+ <inertial pos="0.0229999 0.00111685 -0.00111658" quat="0.643608 0.293036 0.661363 0.249998" mass="0.48405" diaginertia="0.000430353 0.000429873 0.000164648" />+ <joint name="right_wrist_pitch_joint" axis="0 1 0" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_right_wrist_pitch_link" />+ <geom class="g1_collision" mesh="g1_right_wrist_pitch_link" />+ <body name="right_wrist_yaw_link" pos="0.046 0 0">+ <inertial pos="0.0708244 -0.000191745 0.00161742" quat="0.493188 0.468078 0.526295 0.510571" mass="0.254576" diaginertia="0.000646113 0.000559993 0.000147566" />+ <joint name="right_wrist_yaw_joint" axis="0 0 1" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_right_wrist_yaw_link" />+ <geom class="g1_collision" mesh="g1_right_wrist_yaw_link" />+ <geom pos="0.0415 -0.003 0" quat="1 0 0 0" class="g1_visual" mesh="g1_right_rubber_hand" />+ <body name="right_mount" pos="0.08 -0.0030 0" quat="0.7071068 0 0.7071068 0" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="head_cam" pos="0.08 0 0.39">+ <camera name="head_left" pos="0 0.025 0" xyaxes="0 -1 0 0 0 1" fovy="58" />+ <camera name="head_right" pos="0 -0.025 0" xyaxes="0 -1 0 0 0 1" fovy="58" />+ <site name="head_center" size="0.01" group="5" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.agile b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.agilenew file mode 100644index 0000000000..096d7552fb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.agile@@ -0,0 +1,260 @@+================================================================================+DUAL LICENSE NOTICE+================================================================================++This repository contains code under two different licenses:++1. BSD 3-Clause License:+ - Applies to: third_party/rsl_rl/patches/ (RSL-RL compatibility patch)+ - Copyright holders: ETH Zurich, NVIDIA CORPORATION & AFFILIATES+ - See Section A below for full license text++2. Apache License 2.0:+ - Applies to: ALL OTHER portions of this repository+ - Copyright holder: NVIDIA CORPORATION & AFFILIATES+ - See Section B below for full license text++When using or distributing this software, you must comply with the license+terms applicable to each portion of the code. If you modify or redistribute+the RSL-RL compatibility patch (third_party/rsl_rl/patches/), you must comply+with the BSD 3-Clause License terms. For all other portions, you must comply with+the Apache 2.0 License terms.++================================================================================+SECTION A: BSD 3-Clause License (for third_party/rsl_rl/patches/)+================================================================================++Copyright (c) 2025, ETH Zurich+Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES+All rights reserved.++Redistribution and use in source and binary forms, with or without modification,+are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its contributors+ may be used to endorse or promote products derived from this software without+ specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++================================================================================+SECTION B: Apache License 2.0 (for all other portions of this repository)+================================================================================++Apache License+Version 2.0, January 2005+http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++"License" shall mean the terms and conditions for use, reproduction,+and distribution as defined by Sections 1 through 9 of this document.++"Licensor" shall mean the copyright owner or entity authorized by+the copyright owner that is granting the License.++"Legal Entity" shall mean the union of the acting entity and all+other entities that control, are controlled by, or are under common+control with that entity. For the purposes of this definition,+"control" means (i) the power, direct or indirect, to cause the+direction or management of such entity, whether by contract or+otherwise, or (ii) ownership of fifty percent (50%) or more of the+outstanding shares, or (iii) beneficial ownership of such entity.++"You" (or "Your") shall mean an individual or Legal Entity+exercising permissions granted by this License.++"Source" form shall mean the preferred form for making modifications,+including but not limited to software source code, documentation+source, and configuration files.++"Object" form shall mean any form resulting from mechanical+transformation or translation of a Source form, including but+not limited to compiled object code, generated documentation,+and conversions to other media types.++"Work" shall mean the work of authorship, whether in Source or+Object form, made available under the License, as indicated by a+copyright notice that is included in or attached to the work+(an example is provided in the Appendix below).++"Derivative Works" shall mean any work, whether in Source or Object+form, that is based on (or derived from) the Work and for which the+editorial revisions, annotations, elaborations, or other modifications+represent, as a whole, an original work of authorship. For the purposes+of this License, Derivative Works shall not include works that remain+separable from, or merely link (or bind by name) to the interfaces of,+the Work and Derivative Works thereof.++"Contribution" shall mean any work of authorship, including+the original version of the Work and any modifications or additions+to that Work or Derivative Works thereof, that is intentionally+submitted to Licensor for inclusion in the Work by the copyright owner+or by an individual or Legal Entity authorized to submit on behalf of+the copyright owner. For the purposes of this definition, "submitted"+means any form of electronic, verbal, or written communication sent+to the Licensor or its representatives, including but not limited to+communication on electronic mailing lists, source code control systems,+and issue tracking systems that are managed by, or on behalf of, the+Licensor for the purpose of discussing and improving the Work, but+excluding communication that is conspicuously marked or otherwise+designated in writing by the copyright owner as "Not a Contribution."++"Contributor" shall mean Licensor and any individual or Legal Entity+on behalf of whom a Contribution has been received by Licensor and+subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of+this License, each Contributor hereby grants to You a perpetual,+worldwide, non-exclusive, no-charge, royalty-free, irrevocable+copyright license to reproduce, prepare Derivative Works of,+publicly display, publicly perform, sublicense, and distribute the+Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of+this License, each Contributor hereby grants to You a perpetual,+worldwide, non-exclusive, no-charge, royalty-free, irrevocable+(except as stated in this section) patent license to make, have made,+use, offer to sell, sell, import, and otherwise transfer the Work,+where such license applies only to those patent claims licensable+by such Contributor that are necessarily infringed by their+Contribution(s) alone or by combination of their Contribution(s)+with the Work to which such Contribution(s) was submitted. If You+institute patent litigation against any entity (including a+cross-claim or counterclaim in a lawsuit) alleging that the Work+or a Contribution incorporated within the Work constitutes direct+or contributory patent infringement, then any patent licenses+granted to You under this License for that Work shall terminate+as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the+Work or Derivative Works thereof in any medium, with or without+modifications, and in Source or Object form, provided that You+meet the following conditions:++(a) You must give any other recipients of the Work or+Derivative Works a copy of this License; and++(b) You must cause any modified files to carry prominent notices+stating that You changed the files; and++(c) You must retain, in the Source form of any Derivative Works+that You distribute, all copyright, patent, trademark, and+attribution notices from the Source form of the Work,+excluding those notices that do not pertain to any part of+the Derivative Works; and++(d) If the Work includes a "NOTICE" text file as part of its+distribution, then any Derivative Works that You distribute must+include a readable copy of the attribution notices contained+within such NOTICE file, excluding those notices that do not+pertain to any part of the Derivative Works, in at least one+of the following places: within a NOTICE text file distributed+as part of the Derivative Works; within the Source form or+documentation, if provided along with the Derivative Works; or,+within a display generated by the Derivative Works, if and+wherever such third-party notices normally appear. The contents+of the NOTICE file are for informational purposes only and+do not modify the License. You may add Your own attribution+notices within Derivative Works that You distribute, alongside+or as an addendum to the NOTICE text from the Work, provided+that such additional attribution notices cannot be construed+as modifying the License.++You may add Your own copyright statement to Your modifications and+may provide additional or different license terms and conditions+for use, reproduction, or distribution of Your modifications, or+for any such Derivative Works as a whole, provided Your use,+reproduction, and distribution of the Work otherwise complies with+the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise,+any Contribution intentionally submitted for inclusion in the Work+by You to the Licensor shall be under the terms and conditions of+this License, without any additional terms or conditions.+Notwithstanding the above, nothing herein shall supersede or modify+the terms of any separate license agreement you may have executed+with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade+names, trademarks, service marks, or product names of the Licensor,+except as required for reasonable and customary use in describing the+origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or+agreed to in writing, Licensor provides the Work (and each+Contributor provides its Contributions) on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+implied, including, without limitation, any warranties or conditions+of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+PARTICULAR PURPOSE. You are solely responsible for determining the+appropriateness of using or redistributing the Work and assume any+risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory,+whether in tort (including negligence), contract, or otherwise,+unless required by applicable law (such as deliberate and grossly+negligent acts) or agreed to in writing, shall any Contributor be+liable to You for damages, including any direct, indirect, special,+incidental, or consequential damages of any character arising as a+result of this License or out of the use or inability to use the+Work (including but not limited to damages for loss of goodwill,+work stoppage, computer failure or malfunction, or any and all+other commercial damages or losses), even if such Contributor+has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing+the Work or Derivative Works thereof, You may choose to offer,+and charge a fee for, acceptance of support, warranty, indemnity,+or other liability obligations and/or rights consistent with this+License. However, in accepting such obligations, You may act only+on Your own behalf and on Your sole responsibility, not on behalf+of any other Contributor, and only if You agree to indemnify,+defend, and hold each Contributor harmless for any liability+incurred by, or claims asserted against, such Contributor by reason+of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++To apply the Apache License to your work, attach the following+boilerplate notice, with the fields enclosed by brackets "[]"+replaced with your own identifying information. (Don't include+the brackets!) The text should be enclosed in the appropriate+comment syntax for the file format. We also recommend that a+file or class name and description of purpose be included on the+same "printed page" as the copyright notice for easier+identification within third-party archives.++Copyright [yyyy] [name of copyright owner]++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.falcon b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.falconnew file mode 100644index 0000000000..69ceb6b302--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.falcon@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 Yuanhang Zhang+s+Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.unitree_rl_gym b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.unitree_rl_gymnew file mode 100644index 0000000000..9ad8f6dbb0--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.unitree_rl_gym@@ -0,0 +1,23 @@+BSD 3-Clause License+Copyright (c) 2016-2023 HangZhou YuShu TECHNOLOGY CO.,LTD. ("Unitree Robotics")+All rights reserved.+Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:+1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.+3. Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/agile_g1_velocity_height.npz b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/agile_g1_velocity_height.npznew file mode 100644index 0000000000..fe7e262950Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/agile_g1_velocity_height.npz differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/falcon_g1_29dof.npz b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/falcon_g1_29dof.npznew file mode 100644index 0000000000..d220b17c01Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/falcon_g1_29dof.npz differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/g1_deploy_mujoco.yaml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/g1_deploy_mujoco.yamlnew file mode 100644index 0000000000..db18fdfa78--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/g1_deploy_mujoco.yaml@@ -0,0 +1,26 @@+#+policy_path: "{LEGGED_GYM_ROOT_DIR}/deploy/pre_train/g1/motion.pt"+xml_path: "{LEGGED_GYM_ROOT_DIR}/resources/robots/g1_description/scene.xml"++# Total simulation time+simulation_duration: 60.0+# Simulation time step+simulation_dt: 0.002+# Controller update frequency (meets the requirement of simulation_dt * controll_decimation=0.02; 50Hz)+control_decimation: 10++kps: [100, 100, 100, 150, 40, 40, 100, 100, 100, 150, 40, 40]+kds: [2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2]++default_angles: [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0,+ -0.1, 0.0, 0.0, 0.3, -0.2, 0.0]++ang_vel_scale: 0.25+dof_pos_scale: 1.0+dof_vel_scale: 0.05+action_scale: 0.25+cmd_scale: [2.0, 2.0, 0.25]+num_actions: 12+num_obs: 47++cmd_init: [0.5, 0, 0]\ No newline at end of filediff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/motion.npz b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/motion.npznew file mode 100644index 0000000000..40ea903b13Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/bodies/unitree_g1/policy/motion.npz differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/README.md b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/README.mdnew file mode 100644index 0000000000..1bd69c7076--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/README.md@@ -0,0 +1,21 @@+# core/++The match core (docs/framework_zh.md §5): it hosts every match under one set of rules and never names a sport or a+harness. Version: `VERSION` in `__init__.py` (bump on every change; every sport's golden replay must still pass).++| File | Contract / job |+|---|---|+| `sport.py` | ② the sport interface: `MatchConfig` (seats, sides, format, modes, renderer), `Phase`, `Refused`, `MatchBase` (the optional hooks and their defaults), `ActionLayer` / `LowLayer` / `SchemaLayer`, `check_command`; request validation (core 0.2.11): `check_body` (every request), `check_action` + `parse_action` (every act: any exception while reading an action is the player's 400, never a technical failure; core 0.2.13: an `entity` from a seat without entities is refused) |+| `http.py`, `client.py`, `game.py` | ① the player protocol: the HTTP envelope (`/<seat>/<endpoint>`, limits; core 0.2.16: each authenticated seat its own budget), the client loop of built-in players, the generic `game` CLI (core 0.2.13: a shortcut sends `entity` as written, true / false as booleans and an enum value as text) |+| `realtime.py`, `turn.py`, `service.py` | flow: `eai-standard-realtime/1.0` (slowdown, freeze and review, act pipeline, delayed effects, entities) and `eai-standard-turn/1.0` (turns, chess clocks, reviews); what both share (seats and sides, observations, team channel, retirement, final.json); core 0.2.13: the realtime clock and the act segment restart when `Match.resume()` has returned; core 0.2.18: a declared reaction delay D (`sport.toml [timing] reaction_delay_steps`, `spec.reaction_delay`): an act takes effect at max(the next boundary, the step of the seat's latest world state + D), `local.py` alike; core 0.2.20: the team channel (`channel.py`) is read with a read mark and never consumed: every message has a per-side `seq`, `observe` / `status` / `wait` show the teammates' messages after `team_since` (else the recent ones) and `team_seq`, `POST /<seat>/team {"since": n}` pages through the log (before 0.2.20 each message went to whichever client of the seat read first); core 0.2.23: the reaction report (report only, no effect on validity or grading): every realtime act's `cmd` row logs `seen` (the step of the seat's latest world state), the header logs the timing, and final.json `reaction` gives per seat the acts that took effect within D (effect step - seen step <= D; D = 0: the next boundary) as a count and a share and the actual delay in steps (median, p90, max); the fresh-process replay recomputes it (`episode.reaction_report`, replay_check.json `reaction`; final.json `reaction.replayed`); core 0.2.26: after the end `observe` / `act` answer 409 with the final state and draw nothing, and once the match is finalized a late request's failure is only logged (it never voids a finished match) |+| `episode.py` | ③ the match record: `episode.jsonl` and the fresh-process replay (`python -m core.episode PLUGIN DIR`) |+| `diaglog.py`, `diagnose.py` | diagnostics (core 0.2.25; information only, never replayed, in no hash): the rows `observe` (k, view_steps), `act_received` (k, act_id, obs_id_last, seen), `effect`, `act_dropped`, `event` (what `Match.step()` returns), `team_delivered`, written by the service and by `local.py`; the post-match diagnosis `python -m core.diagnose PLUGIN RUN_DIR` (`load()` -> the `rep` dict with a deterministic `world()` replay; the sport's analysis `sports/<sport>/diagnose.py`: `units`, `implied`, `metrics`; writes `diag/units.jsonl`, `claims.jsonl`, `summary.json`); a sport's `diagnose.py` is never copied into a task |+| `outcome.py`, `grading.py` | judgement: the no-draw chain, N-side ranking, solo scoring; the verifier (validity, reward fields, no-code audit hookup; core 0.2.14: hidden official seeds and the continuous score; core 0.2.19: once a hidden seed set is registered only its seeds are official, over the sport's own `official_config`, which can only lower it) |+| `seeds.py` | hidden official seeds (core 0.2.14): the private set's format, the salted commitments, the registered sha256 and the membership test the verifier runs (copied into every task as `tests/seeds.py`) |+| `score.py` | the continuous score (core 0.2.14): sport.toml `[score]` (`share`, `margin`, `own` from `scores()`, or the `Match.continuous_score()` hook), one number per side, larger is better; a forfeiting side gets the declared `forfeit` value; final.json `continuous`, replayed and checked by the verifier |+| `observe.py`, `channel.py`, `rng.py`, `spec.py` | the observation whitelist and camera tiles (through `renderers/`), the reply images of an action (`Match.reply_views`, core 0.2.8: snapshotted under the lock, drawn off it by the same camera worker, attached to the reply as `observation`), the team channel, random streams by name, sport.toml |+| `seats.py`, `metering/` | per-seat counters, locks and chess clocks; the metering hookup (`think_clock.py`, `api_errors.py`: byte-identical copies); player modes (`PLAYER_MODE_<seat>`): `model` (metered by the seat's proxy, required for validity), `oracle` (exempt), `unmetered` (core 0.2.29: the runner meters the model itself, e.g. a plain Harbor with native agents; no proxy, no meter required) |+| `spectator.py` | the broadcast log (`broadcast.jsonl`, the legacy writer copied as `spectator/broadcast_log.py`) and the replay video (`replay.mp4`, a fresh-process replay drawn by the spectator renderer; core 0.2.13: written as `replay.part.mp4` and renamed when complete, so a killed render leaves no `replay.mp4`; core 0.2.28: a sport's own `Sport.spectator_scene(cfg)` + `Match.spectator_state()` when defined); never read back |+| final.json compatibility | `service.py` `COMPAT`: the sport's fields are lifted to the top level (unless a core field has the name) and `score` is set, so the Season-1 readers work; the sport fields also stay under `sport_fields` |+| `workers.py`, `serve.py`, `launch.py` | worker processes (plan, render, camera), the service entry point, the launcher (one metering proxy per seat; core 0.2.22: a seat's proxy keeps no RO_SEAT_* and no other seat's per-seat variable, and a seat on route `chatgpt` no task-wide credential; none for an unmetered seat, core 0.2.29) |+| `local.py`, `testkit.py`, `tests/` | in-process matches of built-in players, the generic test suite of every sport (core 0.2.12: `prestart_no_show` asks for the no-show decision at step 0, not for an unfinished world: a sport's forfeit hook may end its world; core 0.2.13: `fairness` plays a format with its declared sides and counts sides, not seats; core 0.2.17: the fresh-process replays of `determinism` and `solo_quit` may take the sport's `[timing] replay_timeout_s` when it is above 1800 s), the core's own tests |diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/__init__.pynew file mode 100644index 0000000000..1dff7faa1f--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/__init__.py@@ -0,0 +1,26 @@+"""RoboOlympics match core (docs/framework_zh.md §5): hosts every match under one set of rules.++Flow (clock, slowdown, freeze and review, seats and turns), rules (formats, modes), records (episode log, replay,+metering) and judgement (outcome, validity). It names no sport and no harness (ci_checks/check-core-purity.sh), computes+no physics, and changes only in its own commits with a version bump (VERSION) and every sport's golden replay passing.+"""+VERSION = "0.2.29" # 0.2.29: player mode "unmetered" (PLAYER_MODE_<seat>: the runner meters the model; no proxy, no meter)+# (fexam-export, renumbered above main again; it was 0.2.27 there)+# 0.2.28: a sport's own spectator scene for the replay video (Sport.spectator_scene(cfg) with+# Match.spectator_state(); core/spectator.py), never the players' images (0.2.27 is skipped: an unmerged branch uses it)+# 0.2.26: after the end, observe / act answer 409 with the final state and draw nothing (realtime and+# turn); after finalization a late draw returns no images and a late failure is only logged, never an error+# 0.2.25: diagnostic records (information only, never replayed, in no hash; core/diaglog.py):+# observe rows carry k and view_steps (both protocols), act_received k / act_id / obs_id_last / seen, new rows effect,+# act_dropped, event (what Match.step() returns) and team_delivered; core/local.py writes the same; the post-match+# diagnosis python -m core.diagnose PLUGIN RUN_DIR (core/diagnose.py: load() -> rep with a replayed world(), the+# sport's diagnose.py). 0.2.24 is skipped+# 0.2.23: the reaction report (report only): final.json `reaction` per seat, acts within the+# declared reaction delay D (count, share) and the actual delay (median, p90, max); act rows log `seen`, the replay+# recomputes it (core/episode.reaction_report)+# 0.2.22: a seat's metering proxy holds no other seat's credentials (launch.seat_env), a ChatGPT-subscription seat no task-wide key+# 0.2.21: built-in players may talk on the team channel (message(view); core/client.py, core/local.py);+# a preview format ([formats.<f>] preview = true) is never an official configuration+# 0.2.20: the team channel is read with a read mark (seq, team_since, POST /team), never consumed+# 0.2.19: once frozen (hidden seeds registered) only a registered hidden seed is official, over the sport's own rule; 0.2.18: a declared reaction delay+PROTOCOLS = {"realtime": "eai-standard-realtime/1.0", "turn": "eai-standard-turn/1.0"}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/channel.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/channel.pynew file mode 100644index 0000000000..d0bf924897--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/channel.py@@ -0,0 +1,132 @@+"""The team channel (docs/framework_zh.md §6.1, one player per robot): short text messages between the seats of one+side, a core service so that no sport writes it. Declared in sport.toml:++ [team_channel]+ max_bytes = 120 # per message (UTF-8)+ min_interval_s = 1.0 # game time between two messages of one seat+ max_messages = 200 # per seat and match+ recent_s = 2.0 # optional: the default window of observe / status without a read mark (game seconds)+ recent_max = 20 # optional: at most this many messages in that window++A message is stamped with the sender's game time (step k) and a sequence number `seq` (1, 2, ... per side, core+0.2.20) and shown to the other seats of the SAME side only, from that step on; the other side never sees it. Every+message is a row of the episode (`team`, information only: it does not change the world, so the replay does not need+it).++Reading never consumes (core 0.2.20; before 0.2.20 every message was handed out once per seat, so an agent's own+`status` call or monitor script took messages away from its program): `observe` and `status` show the teammates'+messages with seq > `team_since` when the request gives that read mark, else the RECENT ones (the last `recent_s` game+seconds, at most `recent_max` messages: a bounded default that repeats across calls), always with `team_seq`, the+newest seq of the side. `POST /<seat>/team {"since": n}` reads the log after n (at most `page_max` per reply, `more`+when there are more). Every client of a seat (the agent, its program, a monitor) reads the same log with its own+read mark.++The task parameter RO_TEAM_CHANNEL=off switches a declared channel off (the no-communication setting of the+multi-agent taxonomy: same teams, same rules, the teammates cannot talk); the default is on."""+from __future__ import annotations++import os++from .sport import Refused+++class TeamChannel:+ def __init__(self, cfg, conf: dict | None):+ self.cfg, self.conf = cfg, dict(conf or {})+ self.declared = bool(conf) and any(len(cfg.seats_of(s)) > 1 for s in cfg.side_list())+ self.switched_off = os.environ.get("RO_TEAM_CHANNEL", "on").strip().lower() == "off"+ self.enabled = self.declared and not self.switched_off+ self.max_bytes = int(self.conf.get("max_bytes", 120))+ self.min_interval_s = float(self.conf.get("min_interval_s", 1.0))+ self.max_messages = int(self.conf.get("max_messages", 200))+ self.recent_s = float(self.conf.get("recent_s", 2.0))+ self.recent_max = int(self.conf.get("recent_max", 20))+ self.page_max = 500+ self.log: list[dict] = []+ self.last_k: dict[str, int] = {}+ self.seq: dict[str, int] = {} # side -> the newest seq+ self.delivered: dict[str, set] = {} # seat -> seqs already returned to it (core 0.2.25, diagnostics)++ def deliver(self, seat: str, rows: list[dict], k: int) -> list[dict]:+ """The messages of `rows` (as messages() / page() return them) returned to `seat` for the first time, as+ team_delivered rows (core 0.2.25, diagnostics only: when each recipient first got each message)."""+ got = self.delivered.setdefault(seat, set())+ out = []+ for r in rows:+ if r["seq"] not in got:+ got.add(r["seq"])+ out.append({"seat": seat, "from": r["from"], "seq": r["seq"], "sent_k": r["k"], "k": int(k)})+ return out++ def say(self, seat: str, text, k: int, dt: float) -> tuple[int, dict]:+ if not self.enabled:+ if self.declared:+ return 403, {"error": "the team channel is off in this task (no-communication setting)"}+ return 404, {"error": "this task has no team channel"}+ if not isinstance(text, str) or not text.strip():+ return 400, {"error": "text must be a non-empty string"}+ if len(text.encode()) > self.max_bytes:+ return 400, {"error": f"at most {self.max_bytes} bytes per message"}+ sent = sum(1 for m in self.log if m["seat"] == seat)+ if sent >= self.max_messages:+ return 429, {"error": f"at most {self.max_messages} messages per match"}+ gap = self.min_interval_s / dt if dt else 0+ if seat in self.last_k and k - self.last_k[seat] < gap:+ return 429, {"error": f"at most one message every {self.min_interval_s} game seconds"}+ self.last_k[seat] = k+ side = self.cfg.side_of(seat)+ self.seq[side] = self.seq.get(side, 0) + 1+ msg = {"seat": seat, "side": side, "k": k, "seq": self.seq[side], "text": text}+ self.log.append(msg)+ return 200, {"sent": {"k": k, "t_sim": k * dt, "seq": msg["seq"]}}++ @staticmethod+ def since_arg(value, name: str = "team_since"):+ """A client's read mark: None (absent) or a non-negative integer seq; anything else is the caller's error."""+ if value is None:+ return None+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):+ raise Refused(f"{name} must be a non-negative integer (a seq)")+ try:+ n = int(value)+ except (TypeError, ValueError, OverflowError):+ raise Refused(f"{name} must be a non-negative integer (a seq)") from None+ if n < 0 or n != float(value):+ raise Refused(f"{name} must be a non-negative integer (a seq)")+ return n++ def _side_log(self, seat: str, k: int) -> list[dict]:+ side = self.cfg.side_of(seat)+ return [m for m in self.log if m["side"] == side and m["k"] <= k]++ @staticmethod+ def _row(m) -> dict:+ return {"from": m["seat"], "seq": m["seq"], "k": m["k"], "text": m["text"]}++ def messages(self, seat: str, k: int, dt: float, since: int | None = None) -> tuple[list[dict], int]:+ """(the teammates' messages for `seat` at step k, the side's newest seq). With a read mark: every message with+ seq > since (at most page_max, the oldest first); without: the recent ones (the last recent_s game seconds,+ at most recent_max). Never consumes."""+ if not self.enabled:+ return [], 0+ log = self._side_log(seat, k)+ top = log[-1]["seq"] if log else 0+ mates = [m for m in log if m["seat"] != seat]+ if since is None:+ lo = k - (self.recent_s / dt if dt else 0)+ out = [m for m in mates if m["k"] >= lo][-self.recent_max:]+ else:+ out = [m for m in mates if m["seq"] > since][:self.page_max]+ return [self._row(m) for m in out], top++ def page(self, seat: str, k: int, since) -> tuple[int, dict]:+ """POST /<seat>/team {"since": n}: the teammates' messages after seq n (default 0), at most page_max."""+ if not self.enabled:+ if self.declared:+ return 403, {"error": "the team channel is off in this task (no-communication setting)"}+ return 404, {"error": "this task has no team channel"}+ n = self.since_arg(since if since is not None else 0, "since")+ log = self._side_log(seat, k)+ mates = [m for m in log if m["seat"] != seat and m["seq"] > n]+ return 200, {"messages": [self._row(m) for m in mates[:self.page_max]],+ "team_seq": log[-1]["seq"] if log else 0, "more": len(mates) > self.page_max}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/client.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/client.pynew file mode 100644index 0000000000..84258d872b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/client.py@@ -0,0 +1,147 @@+"""Contract ①, the player's side: a stdlib client of the match service and the loop that lets a built-in player (the+sport's reference player, scripted opponents, check policies) play over HTTP exactly as a model's program would.++A built-in player is an object made by factory(spec, seat, seed) with+ act(view) -> body | None view = {"state": <the seat's state>, "observation": <the /observe observation>}+ (body = the /act request; None = nothing now, realtime only)+ review(reply) -> (why, plan) optional; called after each own action (turn) or at each review (realtime)+ message(view) -> text | None optional (realtime, core 0.2.21): a team-channel message to the seat's teammates+ (POST /say; refused messages, e.g. faster than the channel allows, are dropped)++ python3 -m core.client MODULE:FACTORY (SIM_URL, SEAT; e.g. the task's solution/oracle_play.py)+"""+from __future__ import annotations++import importlib+import json+import os+import sys+import time+import urllib.error+import urllib.request+++class Seat:+ """One seat's calls. The service allows 20 requests per second and 4 open requests per seat: the client keeps+ under that (MIN_GAP_S between calls) and retries a request the HTTP layer refused before reading it (a bare 429+ or a reset connection), which never reached the match."""+ MIN_GAP_S = 0.06++ def __init__(self, base: str, seat: str, timeout: float = 600):+ self.base, self.seat, self.timeout, self.last = base.rstrip("/"), seat, timeout, 0.0++ def call(self, ep: str, body: dict | None = None, tries: int = 20) -> dict:+ for i in range(tries):+ time.sleep(max(0.0, self.last + self.MIN_GAP_S - time.monotonic()))+ self.last = time.monotonic()+ req = urllib.request.Request(f"{self.base}/{self.seat}/{ep}",+ data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=self.timeout) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ raw = e.read()+ if e.code == 429 and not raw and i + 1 < tries: # the HTTP layer's limit, not the match's+ time.sleep(0.25 * (i + 1))+ continue+ try:+ out = json.loads(raw)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+ except urllib.error.URLError as e:+ if isinstance(e.reason, (BrokenPipeError, ConnectionResetError, ConnectionRefusedError)) and \+ i + 1 < tries:+ time.sleep(0.25 * (i + 1))+ continue+ raise+ raise RuntimeError("the match service kept refusing")+++def wait_for(base: str, seat: str, deadline_s: float = 300) -> dict:+ t = time.time()+ while time.time() - t < deadline_s:+ try:+ out = Seat(base, seat, 10).call("spec")+ if "error" not in out:+ return out+ except OSError:+ pass+ time.sleep(1)+ raise RuntimeError("the match service did not answer")+++def review_of(player, reply) -> tuple[str, str]:+ f = getattr(player, "review", None)+ return f(reply) if f else ("played as planned", "go on with the same plan")+++REPLY_IMAGES = [0] # acts whose reply carried images of their result (core 0.2.8)+++def play_turn(c: Seat, player) -> dict:+ c.call("start", {})+ while True:+ st = c.call("wait", {"timeout_s": 60}).get("state") or {}+ if st.get("done"):+ return st+ if not st.get("your_turn"):+ continue+ if st.get("awaiting_review"):+ why, plan = review_of(player, st)+ c.call("ready", {"why": why, "plan": plan})+ continue+ view = c.call("observe", {})+ body = player.act({"state": view.get("state") or {}, "observation": view.get("observation") or {}})+ reply = c.call("act", body)+ REPLY_IMAGES[0] += bool((reply.get("observation") or {}).get("image_png_b64"))+ if (reply.get("state") or {}).get("done"):+ return reply["state"]+ if reply.get("http_status"):+ print("refused:", json.dumps(reply)[:300], file=sys.stderr)+ continue+ why, plan = review_of(player, reply)+ c.call("ready", {"why": why, "plan": plan})+++def play_realtime(c: Seat, player, every_s: float = 0.05) -> dict:+ c.call("start", {})+ while True:+ view = c.call("observe", {})+ now = view.get("now") or {}+ if now.get("done"):+ return now+ if now.get("world") == "frozen" and now.get("phase") == "review" and not now.get("ready", {}).get(c.seat):+ why, plan = review_of(player, now)+ c.call("ready", {"why": why, "plan": plan})+ continue+ if now.get("world") == "running":+ v = {"state": now, "observation": view.get("observation") or {}}+ body = player.act(v)+ if body is not None:+ c.call("act", body)+ say = getattr(player, "message", None)+ text = say(v) if say is not None else None+ if text:+ c.call("say", {"text": text})+ c.call("wait", {"dt": every_s})+++def main(argv):+ mod, _, name = argv[0].partition(":")+ sys.path.insert(0, os.getcwd())+ factory = getattr(importlib.import_module(mod), name or "Reference")+ base, seat = os.environ.get("SIM_URL", "http://sim:8000"), os.environ.get("SEAT", "A")+ spec = wait_for(base, seat)+ player = factory(spec, seat, int(os.environ.get("RO_PLAYER_SEED", "0")))+ c = Seat(base, seat)+ proto = spec.get("protocol", "")+ end = play_turn(c, player) if proto.startswith("eai-standard-turn") else play_realtime(c, player)+ print(json.dumps({"final_state": {k: end.get(k) for k in ("reason", "won", "winner", "scores") if k in end},+ "replies_with_images": REPLY_IMAGES[0]}))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/diaglog.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/diaglog.pynew file mode 100644index 0000000000..76eefa943d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/diaglog.py@@ -0,0 +1,93 @@+"""Diagnostic records (core 0.2.25): environment-side rows of episode.jsonl for the post-match diagnosis+(core/diagnose.py). They are information only: no replay reads them, they are not in commands_sha or any state hash,+they never change what a seat is sent, and a failure to write one never ends a match.++Rows (every row also has the episode's "ev", "ts", "wall"):+ {"ev": "observe", "seat", "obs_id", "k", "view_steps", "query", ...} an observation returned to the seat: k = the+ step of the world state it reports; view_steps = the step of each image frame (the sport's camera job may+ report older frames, e.g. a short history; [k] for the core's cameras; [] without images); obs_id counts the+ seat's observations (1, 2, ...)+ {"ev": "act_received", "seat", "k", "act_id", "obs_id_last", "seen", "entity", "decision", ...} an act accepted+ for its effect: act_id = 1, 2, ... per seat (the order the service accepted them); obs_id_last = the seat's+ latest observation returned before the act arrived (None: none yet); seen = the step of the latest world state+ sent to the seat in any reply (the reaction report's s, core 0.2.23)+ {"ev": "effect", "seat", "act_id", "k", "entity", ["rejected"], ["info"]} that act's command took effect before+ step k (it follows its `cmd` row; the cmd row itself is unchanged); turn protocol: info = Match.apply's answer+ {"ev": "act_dropped", "seat", "act_id", "k", "why"} that act never took effect; why: unit_over (the unit ended+ before its effect step), unit_over_planning (it ended while the act was planned), unit_changed, match_over+ {"ev": "event", "k", "events"} what Match.step() returned for the step that ended at k (non-empty lists only)+ {"ev": "team_delivered", "seat", "from", "seq", "sent_k", "k"} a teammate's message first returned to `seat` at+ step k (sent at sent_k), once per recipient and message+"""+from __future__ import annotations++import math++DIAG_ROWS = ("observe", "act_received", "effect", "act_dropped", "event", "team_delivered")+++def jsonable(x, depth: int = 0):+ """A JSON-safe copy of what a sport returned (numpy scalars and arrays, tuples, sets; anything else as its repr)."""+ if depth > 12:+ return repr(x)[:200]+ if x is None or isinstance(x, (bool, str, int)):+ return x+ if isinstance(x, float):+ return x if math.isfinite(x) else None+ if isinstance(x, dict):+ return {str(k): jsonable(v, depth + 1) for k, v in x.items()}+ if isinstance(x, (list, tuple, set, frozenset)):+ return [jsonable(v, depth + 1) for v in x]+ tolist = getattr(x, "tolist", None) # numpy arrays and scalars+ if callable(tolist):+ try:+ return jsonable(tolist(), depth + 1)+ except Exception: # noqa: BLE001+ pass+ return repr(x)[:200]+++def view_steps(meta: dict | None, job, k: int) -> list[int]:+ """The step of each image frame of an observation: the sport's own (camera job meta `view_steps`), else [k] when+ images were made from the state now, else []."""+ vs = (meta or {}).get("view_steps")+ if isinstance(vs, (list, tuple)):+ try:+ return [int(v) for v in vs]+ except (TypeError, ValueError):+ pass+ return [] if job is None else [int(k)]+++class Acts:+ """Per-seat act ids and the latest observation returned to each seat (what act_received links to)."""++ def __init__(self, seats):+ self.next = {s: 0 for s in seats}+ self.last_obs: dict = {s: None for s in seats}++ def new(self, seat) -> int:+ self.next[seat] = self.next.get(seat, 0) + 1+ return self.next[seat]++ def observed(self, seat, obs_id):+ self.last_obs[seat] = obs_id++ def new_obs(self, seat) -> int:+ """In-process play (core/local.py): the next observation id, returned at once."""+ n = (self.last_obs.get(seat) or 0) + 1+ self.last_obs[seat] = n+ return n+++def safe(write):+ """A row writer that never raises (a diagnostic row must not end a match)."""+ def w(ev, **row):+ try:+ write(ev, **row)+ except Exception: # noqa: BLE001+ try:+ write(ev, **{k: jsonable(v) for k, v in row.items()})+ except Exception: # noqa: BLE001+ pass+ return wdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/diagnose.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/diagnose.pynew file mode 100644index 0000000000..a006962eba--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/diagnose.py@@ -0,0 +1,443 @@+"""Post-match diagnosis (core 0.2.25; capability measurement framework §7): read a finished match's records, replay+its world deterministically, and run the sport's analysis (sports/<sport>/diagnose.py). Nothing here is part of a+match: no match imports it, it changes no record, and a bug in it changes no official result.++ python -m core.diagnose PLUGIN RUN_DIR [--diagnose FILE] [--out DIR] [--no-sport]++RUN_DIR holds episode.jsonl (or episode.jsonl.gz) and, when there are any, final.json, replay_check.json,+local_result.json and the program snapshots (snapshots/, or ../snapshots/ and ../../snapshots/ of a Harbor trial:+tools/snapshot_watch.py). Writes RUN_DIR/diag/ (or --out): units.jsonl, claims.jsonl, summary.json.++The sport's analysis, sports/<sport>/diagnose.py (never copied into a task: tools/sportlib.NOT_IN_SIM):+ units(rep) -> [{"id", "seat", "k0", "k1", ...}] decision units (one incoming ball, one possession ...)+ implied(rep, units) -> [{"unit", "seat", "k_cmd", "act_id", "quantity", "implied", "truth", "err_space",+ "err_time", ...}] claims read from the commands, with the true value+ metrics(units, claims) -> {seat: {metric_id: {"value", "capability", "status", ...}}}+ capability in A1 A2 A3 A4 B1 B2 B3 C1 C2; status in official conditional behaviour unvalidated+Looked up as --diagnose, else diagnose.py next to PLUGIN, else sports/<sport>/diagnose.py of this repository.++rep = load(run_dir, plugin) (INTERFACE "diag/1"):+ interface, run_dir, plugin, sport, protocol, revision, core_version, header, cfg (dict), seats, sides+ {seat: side}, dt (control step, s; None without a plugin)+ rows every row of episode.jsonl, in order+ cmd, observe, act_received, effect, act_dropped, event, team, team_delivered, unit_over, resume, ready, review,+ forfeit, retire, end the rows of that "ev", in order ([] when the episode has none)+ has {name: bool}: which diagnostic rows the episode has (core >= 0.2.25 writes them)+ obs {seat: {obs_id: observe row}}+ acts {seat: [act]} in act_id order; act = {act_id, seat, entity, k_recv, unit, decision,+ obs_id_last, obs (its observe row or None), k_obs, view_steps, seen, k_effect (None:+ no effect), cmd (the low-level command that took effect, or None), rejected, dropped+ (why, or None)}+ events [{"k", **event}]: every event Match.step() returned (event rows, flattened)+ final, replay_check, local_result those JSON files, or None+ snapshots {"dir", "rows": snapshots.jsonl rows, "procs": procs.jsonl rows} per seat, or {}+ world world(build=None) -> World: a fresh deterministic replay (below); build(cfg) -> Match+ replaces the sport's build (e.g. a screening variant's patched opponent)+World (realtime: k = control steps; turn: k = Match.k, the actions so far):+ w.at(k, after=False) the Match with m.k == k, as the seats saw it at k: before the rows logged at k+ (commands that took effect before step k); after=True: after them. Forward is cheap,+ backward rebuilds from the start.+ w.m, w.k the match now and its step+ w.events {k: events} that Match.step() returned while replaying (also for old episodes)+ w.run(fn) calls fn(m) at every step to the end (realtime: after each step; turn: after each row)+ w.fork() an independent match in the same state (counterfactual play): a deep copy, else a+ second replay to the same point+"""+from __future__ import annotations++import argparse+import copy+import gzip+import hashlib+import importlib.util+import json+import math+import os+import statistics+import sys+from pathlib import Path++from .episode import REPLAYED, _dispatch, header_cfg, load_plugin+from .sport import FINISHED++INTERFACE = "diag/1"+ROWS = ("cmd", "observe", "act_received", "effect", "act_dropped", "event", "team", "team_delivered", "unit_over",+ "resume", "ready", "review", "forfeit", "retire", "end")+DIAG = ("observe", "act_received", "effect", "act_dropped", "event", "team_delivered")+CAPABILITIES = ("A1", "A2", "A3", "A4", "B1", "B2", "B3", "C1", "C2")+STATUSES = ("official", "conditional", "behaviour", "unvalidated")+ROOT = Path(__file__).resolve().parents[1]+++def read_episode(run_dir) -> list[dict]:+ d = Path(run_dir)+ if (d / "episode.jsonl").exists():+ text = (d / "episode.jsonl").read_text()+ elif (d / "episode.jsonl.gz").exists():+ with gzip.open(d / "episode.jsonl.gz", "rt") as f:+ text = f.read()+ else:+ raise FileNotFoundError(f"no episode.jsonl in {d}")+ out = []+ for line in text.splitlines():+ if line.strip():+ try:+ out.append(json.loads(line))+ except json.JSONDecodeError: # a line cut by a killed writer: the rest is still usable+ continue+ return out+++def _json(p: Path):+ try:+ return json.loads(p.read_text())+ except (OSError, json.JSONDecodeError):+ return None+++def _jsonl(p: Path) -> list[dict]:+ try:+ return [json.loads(x) for x in p.read_text().splitlines() if x.strip()]+ except (OSError, json.JSONDecodeError):+ return []+++def find_snapshots(run_dir) -> dict:+ """Program snapshots of the match (tools/snapshot_watch.py): {seat: {"dir", "rows", "procs"}}."""+ d = Path(run_dir).resolve()+ for base in (d / "snapshots", d.parent / "snapshots", d.parent.parent / "snapshots"):+ if base.is_dir():+ out = {}+ for s in sorted(x for x in base.iterdir() if x.is_dir()):+ out[s.name] = {"dir": str(s), "rows": _jsonl(s / "snapshots.jsonl"), "procs": _jsonl(s / "procs.jsonl")}+ return out+ return {}+++def link_acts(rows: list[dict]) -> tuple[dict, dict]:+ """(acts by seat, observations by seat): every accepted act with its observation, effect step and command."""+ obs: dict = {}+ acts: dict = {}+ last_cmd: dict = {} # seat -> the latest cmd row (an effect row follows its cmd row)+ for r in rows:+ ev = r.get("ev")+ if ev == "observe" and "obs_id" in r:+ obs.setdefault(r["seat"], {})[r["obs_id"]] = r+ elif ev == "cmd":+ last_cmd[r["seat"]] = r+ elif ev == "act_received" and r.get("act_id") is not None:+ seat = r["seat"]+ o = obs.get(seat, {}).get(r.get("obs_id_last"))+ acts.setdefault(seat, {})[r["act_id"]] = {+ "act_id": r["act_id"], "seat": seat, "entity": r.get("entity"), "k_recv": r.get("k"),+ "unit": r.get("unit"), "decision": r.get("decision"), "obs_id_last": r.get("obs_id_last"), "obs": o,+ "k_obs": o.get("k") if o else None, "view_steps": o.get("view_steps") if o else None,+ "seen": r.get("seen"), "k_effect": None, "cmd": None, "rejected": False, "dropped": None}+ elif ev == "effect":+ a = acts.get(r["seat"], {}).get(r.get("act_id"))+ if a is not None:+ c = last_cmd.get(r["seat"])+ a["k_effect"] = r.get("k")+ a["cmd"] = c.get("cmd") if c is not None and c.get("k") == r.get("k") else None+ a["rejected"] = bool(r.get("rejected"))+ if "info" in r:+ a["info"] = r["info"]+ elif ev == "act_dropped":+ a = acts.get(r["seat"], {}).get(r.get("act_id"))+ if a is not None:+ a["dropped"] = r.get("why")+ return {s: [v[i] for i in sorted(v)] for s, v in acts.items()}, obs+++class World:+ """A deterministic replay of the episode's world, stepped forward on demand (see the module text)."""++ def __init__(self, sport, rows: list[dict], build=None):+ self.sport, self.build, self.rows = sport, build, rows+ self.head = next(r for r in rows if r["ev"] == "header")+ self.cfg = header_cfg(self.head)+ self.rep = [r for r in rows if r["ev"] in REPLAYED and r["ev"] != "header"]+ end = next((r for r in self.rep if r["ev"] == "end"), None)+ self.turn = sport.protocol == "turn"+ if not self.turn:+ self.at_k: dict = {}+ for r in self.rep:+ self.at_k.setdefault(int(r["k"]), []).append(r)+ self.k_end = int(end["k"]) if end else max(self.at_k, default=0)+ self.events: dict = {}+ self.reset()++ def reset(self):+ self.m = (self.build or self.sport.build)(self.cfg)+ self.forfeits, self.retired = [], []+ self.done_k = None # realtime: the step whose rows were applied+ self.i = 0 # turn: the next row++ @property+ def k(self) -> int:+ return int(self.m.k)++ def _apply_rows(self):+ if self.done_k != self.m.k:+ for r in self.at_k.get(self.m.k, []):+ _dispatch(self.m, r, self.forfeits, self.retired)+ self.done_k = self.m.k++ def _step(self) -> bool:+ """Realtime: the rows of this step, then one step; False at the end of the match."""+ self._apply_rows()+ if self.m.phase().state == FINISHED or self.m.k >= self.k_end:+ return False+ ev = self.m.step()+ if ev:+ self.events[self.m.k] = ev+ return True++ def at(self, k: int, after: bool = False):+ k = int(k)+ if self.turn:+ if self.i:+ last = int(self.rep[self.i - 1].get("k", 0))+ if last > k or (last == k and not after):+ self.reset()+ while self.i < len(self.rep):+ r = self.rep[self.i]+ rk = int(r.get("k", self.m.k))+ if rk > k or (rk == k and not after):+ break+ _dispatch(self.m, r, self.forfeits, self.retired)+ self.i += 1+ return self.m+ if k < self.k or (k == self.k and self.done_k == k and not after):+ self.reset()+ while self.k < k:+ if not self._step():+ break+ if after and self.k == k:+ self._apply_rows()+ return self.m++ def run(self, fn=None):+ """To the end of the match, fn(m) after every step (turn: after every row)."""+ if self.turn:+ while self.i < len(self.rep):+ _dispatch(self.m, self.rep[self.i], self.forfeits, self.retired)+ self.i += 1+ if fn is not None:+ fn(self.m)+ return self.m+ while self._step():+ if fn is not None:+ fn(self.m)+ return self.m++ def fork(self):+ """An independent match in the state of this one, for counterfactual play: a deep copy, or (a match that+ cannot be copied, e.g. one holding MuJoCo rollout objects) a second replay to the same point."""+ try:+ return copy.deepcopy(self.m)+ except Exception: # noqa: BLE001+ w = World(self.sport, self.rows, self.build)+ if self.turn:+ while w.i < self.i:+ _dispatch(w.m, w.rep[w.i], w.forfeits, w.retired)+ w.i += 1+ else:+ w.at(self.k, after=self.done_k == self.k)+ return w.m+++def load(run_dir, plugin: str | None = None, build=None) -> dict:+ """The records of one match as the sport's analysis reads them (the module text lists the keys)."""+ d = Path(run_dir)+ rows = read_episode(d)+ head = next((r for r in rows if r.get("ev") == "header"), None)+ if head is None:+ raise ValueError(f"{d}: the episode has no header")+ cfg = head["cfg"]+ seats = list(cfg["seats"])+ sides = {s: (cfg.get("sides") or {}).get(s, s) for s in seats}+ by = {name: [] for name in ROWS}+ for r in rows:+ if r.get("ev") in by:+ by[r["ev"]].append(r)+ acts, obs = link_acts(rows)+ events = [{"k": r["k"], **(e if isinstance(e, dict) else {"value": e})} for r in by["event"]+ for e in (r.get("events") or [])]+ sport = load_plugin(plugin) if plugin else None+ dt = None+ if sport is not None:+ try:+ dt = float((build or sport.build)(header_cfg(head)).dt or 0) or None+ except Exception: # noqa: BLE001+ dt = None++ def world(build_override=None):+ if sport is None:+ raise RuntimeError("load(run_dir, plugin) without a plugin has no world()")+ return World(sport, rows, build_override or build)++ rep = {"interface": INTERFACE, "run_dir": str(d), "plugin": plugin, "sport": head.get("sport"),+ "protocol": head.get("protocol") or (sport.protocol if sport else None), "revision": head.get("revision"),+ "core_version": (head.get("versions") or {}).get("core"), "header": head, "cfg": cfg, "seats": seats,+ "sides": sides, "dt": dt, "rows": rows, **by, "has": {n: bool(by[n]) for n in DIAG}, "obs": obs,+ "acts": acts, "events": events, "final": _json(d / "final.json"),+ "replay_check": _json(d / "replay_check.json"), "local_result": _json(d / "local_result.json"),+ "snapshots": find_snapshots(d), "world": world}+ return rep+++def _q(v: list, p: float):+ if not v:+ return None+ x = sorted(v)+ return x[min(len(x) - 1, max(0, math.ceil(p * len(x)) - 1))]+++def linkage(rep: dict) -> dict:+ """Per seat: how completely the acts link to an observation and to an effect or a drop (the logging check)."""+ out = {}+ for seat in rep["seats"]:+ A = rep["acts"].get(seat, [])+ ids = [a["act_id"] for a in A]+ eff = [a for a in A if a["k_effect"] is not None]+ drop = [a for a in A if a["dropped"] is not None]+ lag_obs = [a["k_effect"] - a["k_obs"] for a in eff if a["k_obs"] is not None]+ lag_recv = [a["k_effect"] - a["k_recv"] for a in eff if a["k_recv"] is not None]+ out[seat] = {+ "acts": len(A), "act_ids_contiguous": ids == list(range(1, len(A) + 1)),+ "with_observation": sum(a["obs"] is not None for a in A),+ "obs_id_unknown": sum(a["obs_id_last"] is not None and a["obs"] is None for a in A),+ "before_any_observation": sum(a["obs_id_last"] is None for a in A),+ "effect": len(eff), "effect_with_cmd": sum(a["cmd"] is not None for a in eff),+ "dropped": len(drop), "dropped_by": {w: sum(a["dropped"] == w for a in drop)+ for w in sorted({a["dropped"] for a in drop})},+ "unresolved": sum(a["k_effect"] is None and a["dropped"] is None for a in A),+ "both": sum(a["k_effect"] is not None and a["dropped"] is not None for a in A),+ "obs_to_effect_steps": {"median": statistics.median(lag_obs) if lag_obs else None,+ "p90": _q(lag_obs, 0.9), "max": max(lag_obs, default=None)},+ "recv_to_effect_steps": {"median": statistics.median(lag_recv) if lag_recv else None,+ "max": max(lag_recv, default=None)},+ "observations": len(rep["obs"].get(seat, {})),+ }+ return out+++def c1(rep: dict) -> dict:+ """C1 (description only, framework §3): the program's reliability from the core's rows, per seat."""+ out = {}+ dt = rep.get("dt") or 0.0+ refused = {}+ for r in rep["rows"]:+ if r.get("ev") in ("refused_invalid", "refused_not_model", "refused_query"):+ refused.setdefault(r.get("seat"), {}).setdefault(r["ev"], 0)+ refused[r.get("seat")][r["ev"]] += 1+ for seat in rep["seats"]:+ A = rep["acts"].get(seat, [])+ eff = [a for a in A if a["k_effect"] is not None]+ ks = [a["k_effect"] for a in eff]+ gaps = [b - a for a, b in zip(ks, ks[1:])]+ out[seat] = {"acts": len(A), "effects": len(eff), "rejected": sum(a["rejected"] for a in eff),+ "dropped": sum(a["dropped"] is not None for a in A), "refused": refused.get(seat, {}),+ "first_effect_k": ks[0] if ks else None,+ "first_effect_s": round(ks[0] * dt, 4) if ks and dt else None,+ "effect_gap_steps": {"median": statistics.median(gaps) if gaps else None, "p90": _q(gaps, 0.9),+ "max": max(gaps, default=None)},+ "observations": len(rep["obs"].get(seat, {}))}+ return out+++def load_diagnoser(path):+ spec = importlib.util.spec_from_file_location("ro_sport_diagnose", path)+ mod = importlib.util.module_from_spec(spec)+ sys.path.insert(0, str(Path(path).resolve().parent))+ spec.loader.exec_module(mod)+ return mod+++def find_diagnoser(plugin: str | None, sport: str | None, given: str | None = None):+ if given:+ return Path(given)+ for p in ([Path(plugin).resolve().parent / "diagnose.py"] if plugin else []) + \+ ([ROOT / "sports" / sport / "diagnose.py"] if sport else []):+ if p.is_file():+ return p+ return None+++def check_metrics(metrics) -> list[str]:+ """The shape of metrics() (the shared interface): per seat {metric_id: {value, capability, status}}."""+ bad = []+ if not isinstance(metrics, dict):+ return ["metrics() must return {seat: {metric_id: {...}}}"]+ for seat, ms in metrics.items():+ if not isinstance(ms, dict):+ bad.append(f"{seat}: not a dict")+ continue+ for mid, v in ms.items():+ if not isinstance(v, dict) or "value" not in v:+ bad.append(f"{seat}.{mid}: needs value")+ continue+ if v.get("capability") not in CAPABILITIES:+ bad.append(f"{seat}.{mid}: capability {v.get('capability')!r} not in {CAPABILITIES}")+ if v.get("status") not in STATUSES:+ bad.append(f"{seat}.{mid}: status {v.get('status')!r} not in {STATUSES}")+ return bad+++def _dump(x):+ from .diaglog import jsonable+ return json.dumps(jsonable(x))+++def diagnose(rep: dict, mod=None, out: Path | None = None) -> dict:+ """Run the sport's analysis (mod: its diagnose module, or None for the core's part only) and write out/."""+ out = Path(out or Path(rep["run_dir"]) / "diag")+ out.mkdir(parents=True, exist_ok=True)+ units, claims, metrics, errors = [], [], {}, []+ if mod is not None:+ units = list(mod.units(rep))+ claims = list(mod.implied(rep, units))+ metrics = mod.metrics(units, claims)+ errors += check_metrics(metrics)+ (out / "units.jsonl").write_text("".join(_dump(u) + "\n" for u in units))+ (out / "claims.jsonl").write_text("".join(_dump(c) + "\n" for c in claims))+ fin = rep.get("final") or rep.get("local_result") or {}+ summary = {"interface": INTERFACE, "sport": rep["sport"], "revision": rep["revision"],+ "core_version": rep["core_version"], "run_dir": rep["run_dir"], "seats": rep["seats"],+ "has": rep["has"], "outcome": {k: fin.get(k) for k in ("scores", "winner", "valid_trial", "reason")+ if k in fin},+ "diagnoser": None if mod is None else {+ "file": getattr(mod, "__file__", None),+ "sha256": hashlib.sha256(Path(mod.__file__).read_bytes()).hexdigest() if getattr(+ mod, "__file__", None) else None,+ "validity": getattr(mod, "VALIDITY_REPORT", None)},+ "units": len(units), "claims": len(claims), "metrics": metrics, "linkage": linkage(rep),+ "c1": c1(rep), "events": len(rep["events"]), "snapshots": {+ s: {"snapshots": len(v["rows"]), "saved": sum(1 for r in v["rows"] if r.get("tar")),+ "procs": len(v["procs"])} for s, v in rep["snapshots"].items()},+ "errors": errors}+ (out / "summary.json").write_text(_dump(summary))+ return summary+++def main(argv=None):+ ap = argparse.ArgumentParser(prog="python -m core.diagnose")+ ap.add_argument("plugin")+ ap.add_argument("run_dir")+ ap.add_argument("--diagnose", default=None, help="the sport's diagnose.py (default: next to PLUGIN, else "+ "sports/<sport>/diagnose.py)")+ ap.add_argument("--out", default=None)+ ap.add_argument("--no-sport", action="store_true", help="only the core's part (linkage, C1)")+ a = ap.parse_args(argv)+ rep = load(a.run_dir, a.plugin)+ path = None if a.no_sport else find_diagnoser(a.plugin, rep["sport"], a.diagnose)+ mod = load_diagnoser(path) if path else None+ s = diagnose(rep, mod, Path(a.out) if a.out else None)+ print(json.dumps({k: s[k] for k in ("sport", "units", "claims", "errors")} | {"diagnoser": str(path) if path+ else None}))+ return 1 if s["errors"] else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/episode.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/episode.pynew file mode 100644index 0000000000..c395b61f24--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/episode.py@@ -0,0 +1,255 @@+"""Contract ③ (docs/framework_zh.md §4.3): the episode log (episode.jsonl) and the fresh-process replay.++episode.jsonl is append-only, one JSON object per line. Rows the replay reads (everything else is information):+ {"ev": "header", "cfg": MatchConfig, "sport", "revision", "protocol", "source_sha", "versions"}+ (+ realtime, core 0.2.23: "timing": {reaction_delay_steps,+ effect_delay_steps})+ {"ev": "cmd", "k": K, "seat": S, "cmd": LOW_LEVEL_COMMAND} applied before control step K (turn: as action K);+ a delayed command is logged at its effect step; a+ realtime act's row also has "seen" (core 0.2.23)+ {"ev": "resume", "k": K} a review ended before step K+ {"ev": "forfeit", "k": K, "seat": S, "why": W} a core decision that ends the match+ {"ev": "retire", "k": K, "seat": S, "side": D, "why": W} a side leaves, the match goes on (N sides)+ {"ev": "end", "k": K, "reason": R}+Diagnostic rows (core 0.2.25; core/diaglog.py lists them: observe, act_received, effect, act_dropped, event,+team_delivered) are information only, like every row not listed above: the replay never reads them.+Replay (python -m core.episode PLUGIN DIR) rebuilds the match from the header, re-applies the rows at their steps and+writes DIR/replay_check.json: state_sha, scores, winner, ranking, k, commands_sha, source_sha, the continuous+score by side (sport.toml [score], core 0.2.14; null without one) and the reaction report (core 0.2.23,+reaction_report: the same numbers as final.json `reaction`).+Reply images are a pure function of the replayed match (core 0.2.8): python -m core.episode PLUGIN DIR --reply N+draws the reply image of the N-th command row (1-based) into DIR/reply_N.png (+ reply_N.json: the tiles).+"""+from __future__ import annotations++import hashlib+import importlib.util+import json+import math+import os+import statistics+import sys+import threading+import time+from pathlib import Path++from . import score as score_mod+from . import seeds as seeds_mod+from . import spec as spec_mod+from .outcome import decide+from .sport import FINISHED, MatchConfig, sha_json++REPLAYED = ("header", "cmd", "resume", "forfeit", "retire", "end")+++def source_sha(*dirs) -> str:+ """Every file under the given directories (path + bytes), so a changed simulator invalidates old episodes."""+ h = hashlib.sha256()+ for d in dirs:+ d = Path(d)+ for p in sorted(x for x in d.rglob("*") if x.is_file() and "__pycache__" not in x.parts):+ h.update(str(p.relative_to(d)).encode())+ h.update(p.read_bytes())+ return h.hexdigest()+++def load_plugin(path: str):+ """The plugin module at `path` (its directory goes first on sys.path, so its simulator modules import)."""+ path = os.path.abspath(path)+ sys.path.insert(0, os.path.dirname(path))+ spec = importlib.util.spec_from_file_location("ro_plugin", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod.SPORT+++class Episode:+ def __init__(self, path):+ self.path = Path(path)+ self.lock = threading.Lock()+ self.t0 = time.monotonic()+ self.commands = [] # the replayed rows, for commands_sha++ def write(self, ev: str, **row):+ rec = {"ev": ev, "ts": round(time.time(), 3), "wall": round(time.monotonic() - self.t0, 4), **row}+ with self.lock:+ if ev in REPLAYED and ev != "header":+ self.commands.append({k: v for k, v in rec.items() if k not in ("ts", "wall")})+ with self.path.open("a") as f:+ f.write(json.dumps(rec, default=float) + "\n")++ def commands_sha(self) -> str:+ with self.lock:+ return sha_json(self.commands)+++def reaction_report(rows, seats, react: int = 0, effect_delay: int = 0) -> dict:+ """The reaction report (core 0.2.23; report only, no effect on validity or grading). A realtime act's command row+ carries `seen` = s, the step of the latest world state the service had sent to the seat when the act arrived (any+ reply's `now`), and is logged at its effect step k; its actual delay is k - s control steps. It took effect within+ the declared reaction delay D (sport.toml [timing] reaction_delay_steps; core 0.2.18) when k - s <= D ++ effect_delay (the action layer's fixed `delay_steps`, 0 in every sport today); with D = 0 that is the next+ control-step boundary after s. Per seat: acts (rows with a known s), within_d, share = within_d / acts (None+ without acts), delay_steps {median, p90 (nearest rank), max} (None without acts), unseen (act rows without s: the+ seat had been sent no world state). Rows without `seen` (layer ticks, episodes before 0.2.23) are not acts here."""+ lags: dict = {s: [] for s in seats}+ unseen = {s: 0 for s in seats}+ for r in rows:+ if r.get("ev") != "cmd" or "seen" not in r:+ continue+ seat = r["seat"]+ lags.setdefault(seat, [])+ unseen.setdefault(seat, 0)+ if r["seen"] is None:+ unseen[seat] += 1+ else:+ lags[seat].append(int(r["k"]) - int(r["seen"]))+ limit = int(react) + int(effect_delay)+ by_seat = {}+ for seat, v in lags.items():+ x = sorted(v)+ n, within = len(x), sum(1 for d in x if d <= limit)+ by_seat[seat] = {"acts": n, "within_d": within, "share": round(within / n, 6) if n else None,+ "delay_steps": {"median": float(statistics.median(x)), "p90": x[math.ceil(0.9 * n) - 1],+ "max": x[-1]} if n else None,+ "unseen": unseen[seat]}+ return {"policy": "report_only", "reaction_delay_steps": int(react), "effect_delay_steps": int(effect_delay),+ "rule": "within D: effect step - seen step <= reaction_delay_steps + effect_delay_steps (D = 0: the next "+ "control-step boundary)", "by_seat": by_seat}+++def _dispatch(match, row, forfeits, retired, on_cmd=None):+ if row["ev"] == "cmd":+ info = match.apply(row["seat"], row["cmd"]) or {}+ if on_cmd is not None:+ on_cmd(match, row, info)+ elif row["ev"] == "resume":+ match.resume()+ elif row["ev"] == "forfeit":+ match.forfeit(row["seat"], row["why"])+ forfeits.append(row)+ elif row["ev"] == "retire":+ match.retire(row["side"], row["why"])+ retired.append(row["side"])+++def header_cfg(head: dict) -> MatchConfig:+ """The match configuration of an episode header. A hidden official seed (core/seeds.py; core 0.2.14) is written+ as -1 with its commitment: the seed comes from the environment (RO_SEED, RO_SEED_SALT: the sim service's own, or+ `tools/seeds.py resolve` on the official run host) and must give that commitment."""+ d = dict(head["cfg"])+ hid = head.get("seed_hidden")+ if hid:+ seed, salt = os.environ.get("RO_SEED", ""), os.environ.get("RO_SEED_SALT", "")+ if not seed or not salt:+ raise ValueError("a hidden-seed episode: set RO_SEED and RO_SEED_SALT (tools/seeds.py resolve)")+ if seeds_mod.commitment(head.get("sport", d.get("sport", "")), int(seed), salt) != hid.get("commitment"):+ raise ValueError("a hidden-seed episode: RO_SEED / RO_SEED_SALT do not give its commitment")+ d["seed"] = int(seed)+ return MatchConfig.from_json(d)+++def replay(sport, rows: list[dict], observer=None, on_cmd=None, decl: dict | None = None) -> dict:+ """observer(match): called with the initial state, after every turn-protocol row and after every realtime step+ (spectator video; it must not change the match). on_cmd(match, row, info): right after each command row took+ effect, with what Match.apply returned (reply images; it must not change the match either). With the sport's+ declarations (`decl`, sport.toml), also the continuous score of every side (core/score.py, core 0.2.14)."""+ head = next(r for r in rows if r["ev"] == "header")+ cfg = header_cfg(head)+ match = sport.build(cfg)+ rep = [r for r in rows if r["ev"] in REPLAYED and r["ev"] != "header"]+ end = next((r for r in rep if r["ev"] == "end"), None)+ forfeits: list[dict] = []+ retired: list[str] = []+ seen = observer or (lambda m: None)+ seen(match)+ if sport.protocol == "turn":+ for r in rep:+ _dispatch(match, r, forfeits, retired, on_cmd)+ if r["ev"] == "cmd":+ seen(match)+ else:+ at: dict[int, list] = {}+ for r in rep:+ at.setdefault(int(r["k"]), []).append(r)+ k_end = int(end["k"]) if end else max(at, default=0)+ while True:+ for r in at.pop(match.k, []):+ _dispatch(match, r, forfeits, retired, on_cmd)+ if match.phase().state == FINISHED or match.k >= k_end:+ break+ match.step()+ seen(match)+ if at:+ raise ValueError(f"rows after the end of the match at steps {sorted(at)[:5]}")+ fo = forfeits[0] if forfeits else None+ out = decide(match, fo["seat"] if fo else None, fo["why"] if fo else None, cfg.side_list(), cfg.side_of,+ retired)+ return {"state_sha": match.state_digest(), "scores": match.scores(), "winner": out.winner,+ "ranking": out.ranking, "decided_by": out.decided_by, "k": match.k,+ "finished": match.phase().state == FINISHED,+ "commands_sha": sha_json([{k: v for k, v in r.items() if k not in ("ts", "wall")} for r in rep]),+ "source_sha": head.get("source_sha"), "revision": head.get("revision"), "cfg": head["cfg"],+ "continuous": _continuous(match, decl, cfg, fo, retired),+ "reaction": None if sport.protocol == "turn" else+ reaction_report(rep, cfg.seats, *(int((head.get("timing") or {}).get(k) or 0)+ for k in ("reaction_delay_steps", "effect_delay_steps")))}+++def _continuous(match, decl, cfg, fo, retired):+ """The replayed continuous score by side (as Service.continuous), None without a declaration."""+ if not decl:+ return None+ gone = list(retired) + ([cfg.side_of(fo["seat"])] if fo else [])+ c = score_mod.compute(match, decl, cfg.side_list(), gone)+ return c and c["by_side"]+++def read_rows(path) -> list[dict]:+ return [json.loads(x) for x in Path(path).read_text().splitlines() if x.strip()]+++def reply_image(plugin: str, rows: list[dict], n: int) -> dict | None:+ """The reply image of the n-th command row (1-based), drawn from the replayed match as the live service drew it+ (the same job, the task's renderer of the header's cfg, the players' scene): {"png", "tiles", ...} or None."""+ from . import spec as spec_mod+ from .observe import CameraWorker, players_scene, reply_job+ sport = load_plugin(plugin)+ columns = int((spec_mod.load(plugin).get("observation") or {}).get("columns", 2))+ got, count = [], [0]++ def on_cmd(match, row, info):+ count[0] += 1+ if count[0] == n and hasattr(match, "reply_views"):+ got.append(reply_job(match, match.reply_views(row["seat"], row["cmd"], info), columns))+ replay(sport, rows, on_cmd=on_cmd)+ if not got or got[0] is None:+ return None+ cfg = header_cfg(next(r for r in rows if r["ev"] == "header"))+ return CameraWorker(players_scene(sport, plugin, cfg), cfg.renderer).draw_job(got[0])+++def main(argv):+ plugin, d = argv[0], Path(argv[1])+ if "--reply" in argv:+ n = int(argv[argv.index("--reply") + 1])+ img = reply_image(plugin, read_rows(d / "episode.jsonl"), n)+ if img is None:+ print(json.dumps({"reply": n, "image": False}))+ return+ (d / f"reply_{n}.png").write_bytes(img["png"])+ (d / f"reply_{n}.json").write_text(json.dumps({k: v for k, v in img.items() if k != "png"}))+ print(json.dumps({"reply": n, "image": str(d / f"reply_{n}.png"), "tiles": len(img["tiles"])}))+ return+ sport = load_plugin(plugin)+ rows = read_rows(d / "episode.jsonl")+ out = replay(sport, rows, decl=spec_mod.load(plugin))+ hid = next(r for r in rows if r["ev"] == "header").get("seed_hidden")+ if hid: # the commitment the replay's seed gave (never the seed)+ out["seed_commitment"] = hid["commitment"]+ (d / "replay_check.json").write_text(json.dumps(out, default=float))+ print(json.dumps({k: out[k] for k in ("state_sha", "scores", "winner", "k")}, default=float))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/game.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/game.pynew file mode 100644index 0000000000..10223a69ca--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/game.py@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""game - your seat in the match (the same commands for every sport; the actions are the sport's, see `game spec`).++ game spec the sport: actions (types, fields, ranges), cameras, units, rules, timing+ game status the current state, no images+ game start you are ready (preparation over); the match begins when every seat has started+ game wait [SECONDS] turn-based: block until it is your turn; real time: let the world run SECONDS (<= 1)+ game observe [QUERY_JSON] the state and the camera images (saved as PNG under /app/output/views/)+ game act ACTION_JSON one action, e.g. game act '{"type": "throw", ...}' (if the sport shows the result+ in images, they are saved like observe's, as reply_*.png)+ game ready "WHY" "PLAN" your review (after each of your actions, turn-based; at each review, real time)+ game say "TEXT" team formats: a message to your teammates (never shown to the other side)+ game team [SINCE] team formats: your teammates' messages after seq SINCE (default 0); reading never+ consumes them (observe / status show the recent ones and team_seq, the newest seq)+Sport shortcuts (generated from the sport's declaration):+@@SHORTCUTS@@"""+import base64+import json+import os+import sys+import tempfile+import urllib.error+import urllib.request++COMMANDS = json.loads('@@COMMANDS@@') # shortcut -> [action type, field, field, ...]+VIEWS = "/app/output/views"+BASE = os.environ.get("SIM_URL", "http://sim:8000") + "/" + os.environ.get("SEAT", "A")+++def call(ep, body=None):+ req = urllib.request.Request(BASE + "/" + ep, data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=600) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ try:+ out = json.load(e)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+++def save(b64, name):+ os.makedirs(VIEWS, exist_ok=True)+ fd, p = tempfile.mkstemp(dir=VIEWS, prefix=name + "_", suffix=".png")+ with os.fdopen(fd, "wb") as f:+ f.write(base64.b64decode(b64))+ return p+++def show(o):+ ob = o.get("observation")+ if isinstance(ob, dict) and ob.get("image_png_b64"):+ ob["image_file"] = save(ob.pop("image_png_b64"), "reply" if ob.get("of") else "obs")+ for k in [k for k in o if k.endswith("_image_b64")]:+ if o[k]:+ o[k[:-4] + "_file"] = save(o.pop(k), k[:-10])+ else:+ o.pop(k)+ print(json.dumps(o, indent=1))+++def arg(name, x):+ """A shortcut's argument as the act body carries it: `entity` as written (an id), true / false as booleans, a+ number as a number, anything else (an enum value) as written; the core checks every field against the schema."""+ if name == "entity":+ return x+ if x in ("true", "false"):+ return x == "true"+ try:+ return float(x)+ except ValueError:+ return x+++def main(a):+ turn = call("spec").get("protocol", "").startswith("eai-standard-turn") if a[:1] == ["wait"] else None+ if a == ["spec"]:+ show(call("spec"))+ elif a == ["status"]:+ show(call("status"))+ elif a == ["start"]:+ show(call("start", {}))+ elif a[:1] == ["wait"] and len(a) <= 2:+ if turn:+ while True:+ o = call("wait", {"timeout_s": 60})+ st = o.get("state") or {}+ if "error" in o or st.get("done") or st.get("your_turn"):+ break+ show(o)+ else:+ show(call("wait", {"dt": float(a[1]) if len(a) == 2 else 0.1}))+ elif a[:1] == ["observe"] and len(a) <= 2:+ show(call("observe", {"query": json.loads(a[1])} if len(a) == 2 else {}))+ elif a[:1] == ["act"] and len(a) == 2:+ show(call("act", json.loads(a[1])))+ elif a[:1] == ["ready"] and len(a) == 3:+ show(call("ready", {"why": a[1], "plan": a[2]}))+ elif a[:1] == ["say"] and len(a) == 2:+ show(call("say", {"text": a[1]}))+ elif a[:1] == ["team"] and len(a) <= 2:+ show(call("team", {"since": int(a[1]) if len(a) == 2 else 0}))+ elif a and a[0] in COMMANDS and len(a) == len(COMMANDS[a[0]]):+ kind, *names = COMMANDS[a[0]]+ show(call("act", {"type": kind, **{n: arg(n, x) for n, x in zip(names, a[1:])}}))+ else:+ sys.exit(__doc__)+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/grading.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/grading.pynew file mode 100644index 0000000000..f63442d2ca--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/grading.py@@ -0,0 +1,198 @@+"""The verifier (separate sandbox, no network, no simulator): reads what the sim wrote (/data/final.json,+/data/replay_check.json), checks the fresh-process replay agrees with the live match, applies the one validity rule+(technical failures void the trial; a player's own problems are a valid loss, among them a side that never started+in its start window or before the player sessions ended: reason no_show, no_show = 1, <seat>_no_show = 1, core 0.2.7;+and a single side whose session ended after the start and before the end of the match: reason abandoned, abandoned =+1; core 0.2.6) and the no-code audit of+direct play,+and writes reward.json = common fields + the sport's own fields (tests/sport_grade.py: evaluate(final) -> numbers).+The task's formats and official configurations come from tests/contract.json (generated from sport.toml).++Hidden official seeds (core 0.2.14, core/seeds.py): once the sport registers a hidden seed set (contract official+hidden_seeds: sha256, counts and commitments per cell = format x level), official_config needs the match seed to be+one of its cell: the commitment the sim recorded (final.json seed_proof; the replay must give the same one) must be in+the registered cell (hidden_seed = 1, hidden_seed_index = its position; else 0 and -1). A hidden seed is never written:+seed = -1 here and in every record. The public [official] seeds then no longer count as official.+Core 0.2.19: this holds over the sport's own official_config too (tests/sport_grade.py may replace the core's value+with a legacy per-format rule): with a registered set, official_config = 1 needs hidden_seed = 1 and the sport's+value 1, so the sport's rule can only lower it and a public-seed match is never official.+Continuous score (core 0.2.14, core/score.py): final.json continuous.by_side (the replay must agree) becomes+<seat>_continuous_score per seat and, for a single-side format, continuous_score; larger is better.++success: duel / team / multi -> the trial is valid (who won is in <seat>_won / <seat>_place);+ single against a scripted opponent -> valid and the seat's side won;+ single without an opponent (solo) -> valid, complete and the score reaches the success line."""+from __future__ import annotations++import importlib.util+import json+import os+import shutil+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+DATA = Path(os.environ.get("RCB_DATA", "/data"))+LOG = Path(os.environ.get("RCB_LOG", "/logs/verifier"))+COMPLETE = ("match_over", "ready_timeout", "clock", "abandoned", "no_show")+++def _load(name):+ p = HERE / f"{name}.py"+ if not p.exists():+ return None+ spec = importlib.util.spec_from_file_location(name, p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++try: # core/seeds.py; in a task, its copy next to this file (tests/seeds.py)+ from . import seeds as seedset+except ImportError:+ seedset = _load("seeds")+++def hidden_index(d, contract) -> int | None:+ """The match seed's position in its cell (format x level) of the sport's registered hidden official seed set+ (core 0.2.14, core/seeds.py): the commitment the sim recorded (final.json seed_proof; the seed and its salt are+ never written) must be in that cell's registered commitments. None if it is not one."""+ reg = (contract.get("official") or {}).get("hidden_seeds")+ proof = d.get("seed_proof") or {}+ if not reg or seedset is None:+ return None+ return seedset.index(contract.get("sport", ""), d.get("format") or "", (d.get("cfg") or {}).get("level"),+ proof.get("commitment"), reg)+++def official(d, contract) -> bool:+ """An official configuration: the seed (a registered hidden seed once the sport has a hidden set, else one of the+ public [official] seeds), the slowdown, the first player and the level."""+ off = contract.get("official", {})+ if ((contract.get("formats") or {}).get(d.get("format") or "") or {}).get("preview"):+ return False # a preview format ([formats.<f>] preview = true; core 0.2.21) is never official+ ok = True+ if off.get("hidden_seeds"):+ ok &= hidden_index(d, contract) is not None+ elif "seeds" in off:+ ok &= int(d.get("seed") or 0) in off["seeds"]+ if "slowdowns" in off:+ ok &= float(d.get("slowdown") or 0) in off["slowdowns"].get(d.get("play", "program"), [])+ if off.get("first_any"):+ ok &= d.get("first") in d["cfg"]["seats"] or d.get("first") in (d.get("sides") or {}).values()+ if "levels" in off and d["cfg"].get("level") is not None:+ ok &= int(d["cfg"]["level"]) in off["levels"]+ return bool(ok)+++def line_ok(score, line: dict) -> bool:+ if "score_at_least" in line:+ return score >= line["score_at_least"]+ if "score_at_most" in line:+ return score <= line["score_at_most"]+ return False+++def grade(d, r, contract, evaluate, audits=None):+ seats = d["cfg"]["seats"]+ side = d.get("sides") or {s: s for s in seats}+ cont = (d.get("continuous") or {}).get("by_side")+ replay = bool(d.get("deterministic") and r.get("state_sha") == d["state_sha"] and r.get("scores") == d["scores"]+ and r.get("winner") == d["match_winner"] and r.get("commands_sha") == d["commands_sha"]+ and r.get("source_sha") == d["source_sha"] and r.get("k") == d["steps"]+ and (cont is None or r.get("continuous") == cont)+ and (not d.get("seed_proof") or r.get("seed_commitment") == d["seed_proof"].get("commitment")))+ solo = bool(d.get("solo"))+ single = len(set(side.values())) == 1+ complete = d.get("reason") in COMPLETE and (single or d.get("match_winner") in side.values())+ errors = bool(d.get("errors") or any(d["meter_error"].values()) or any(d["proxy_error"].values()))+ valid = bool(d.get("valid_trial") and d.get("finalized") and replay and complete and not errors)+ direct = d.get("play") == "direct"+ audits = audits or {}+ bad = {s: bool(direct and d["player_modes"].get(s) == "model" and audits.get(s, (0, []))[1]) for s in seats}+ winner = d["match_winner"]+ if any(bad.values()): # a no-code violation loses the match (all of them: nobody wins)+ rest = sorted({side[s] for s in seats if not bad[s]})+ winner = rest[0] if len(rest) == 1 and not single else None+ fmt = (contract.get("formats") or {}).get(d.get("format") or "", {})+ if solo:+ score = d["scores"].get(side[seats[0]], 0)+ success = valid and d.get("reason") == "match_over" and not any(bad.values()) and \+ line_ok(score, fmt.get("success", {}))+ elif single:+ success = valid and winner == side[seats[0]]+ else:+ success = valid+ out = dict(success=int(success), valid_trial=int(valid), technical_failure=int(not valid), grader_error=0,+ missing_log=0, deterministic=int(replay), match_over=int(d.get("reason") == "match_over"),+ seed=int(d.get("seed") or 0), official_config=int(official(d, contract)),+ video_rendered=int(bool(d.get("video")) or (DATA / "replay.mp4").exists()), direct_play=int(direct),+ lowlevel_actions=int(d.get("action_level") == "low"), solo=int(solo),+ no_show=int(d.get("reason") == "no_show"), abandoned=int(d.get("reason") == "abandoned"))+ hidx = hidden_index(d, contract)+ out.update(hidden_seed=int(hidx is not None), hidden_seed_index=hidx if hidx is not None else -1)+ if cont is not None: # the continuous score (core 0.2.14): larger is better+ worst = float((contract.get("score") or {}).get("forfeit", 0.0))+ for s in seats:+ out[s + "_continuous_score"] = worst if bad[s] else float(cont.get(side[s], worst))+ if single:+ out["continuous_score"] = out[seats[0] + "_continuous_score"]+ ranking = d.get("ranking") or []+ for s in seats:+ out[s + "_won"] = int(valid and winner == side[s] and not bad[s])+ out[s + "_no_show"] = int(d.get("reason") == "no_show" and not (d.get("joined") or {}).get(s, True))+ if len(set(side.values())) > 2:+ out[s + "_place"] = ranking.index(side[s]) + 1 if valid and side[s] in ranking else 0+ out[s + "_transient_api_errors"] = int(d["transient_api_errors"].get(s, 0))+ out[s + "_unrecovered_api_errors"] = int(d["unrecovered_api_errors"].get(s, 0))+ if direct:+ out[s + "_nocode_tool_calls"] = int(audits.get(s, (0, []))[0])+ out[s + "_nocode_violations"] = len(audits.get(s, (0, []))[1])+ out[s + "_nocode_forfeit"] = int(bad[s])+ out.update(evaluate(d))+ if (contract.get("official") or {}).get("hidden_seeds"):+ # core 0.2.19: once the sport registered a hidden seed set (frozen), only a match on a registered hidden seed of+ # its cell is official, whatever the sport's own official_config says (its legacy public-seed rule); the+ # sport's rule (e.g. its slowdowns) can only lower the value+ out["official_config"] = int(out.get("official_config") == 1 and hidx is not None)+ return out+++def main():+ LOG.mkdir(parents=True, exist_ok=True)+ try:+ contract = json.loads((HERE / "contract.json").read_text())+ evaluate = _load("sport_grade").evaluate+ d, r = (json.loads((DATA / f).read_text()) for f in ("final.json", "replay_check.json"))+ audits = None+ if d.get("play") == "direct":+ nmod = _load("nocode_audit") # the players' no-code audit (players/nocode/)+ # calls the gateway blocked never reached the agent, so they are not judged (direct-native/1.1 rule)+ audits = {s: nmod.nocode_audit(DATA / f"think_calls_{s}.jsonl",+ skip_ids=nmod.gate_blocked_ids(DATA / f"direct_gate_{s}.jsonl"))+ for s in d["cfg"]["seats"]}+ (LOG / "nocode_audit.json").write_text(json.dumps({s: dict(tool_calls=a[0], violations=a[1][:50])+ for s, a in audits.items()}, indent=1))+ out = grade(d, r, contract, evaluate, audits)+ hs = (contract.get("official") or {}).get("hidden_seeds") or {}+ (LOG / "versions.json").write_text(json.dumps({+ "versions": d.get("versions"), "renderer": d.get("renderer"),+ "seed_set": {"sha256": hs.get("sha256"), "counts": hs.get("counts"), "index": hidden_index(d, contract)}+ if hs else None,+ "continuous_score": {k: (d.get("continuous") or {}).get(k) for k in ("name", "from", "higher_is_better")}+ if d.get("continuous") else None}))+ for f in ("final.json", "replay_check.json", "episode.jsonl", "replay.mp4"):+ if (DATA / f).exists():+ shutil.copy(DATA / f, LOG / f)+ except Exception as e: # noqa: BLE001+ print(type(e).__name__, str(e))+ out = dict(success=0, valid_trial=0, technical_failure=1, grader_error=1,+ missing_log=int(not (DATA / "final.json").exists()))+ assert all(isinstance(v, (int, float)) for v in out.values())+ (LOG / "reward.json").write_text(json.dumps(out))+ (LOG / "reward.txt").write_text(str(out["success"]) + "\n")+ print(out)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/http.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/http.pynew file mode 100644index 0000000000..1a24ac0309--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/http.py@@ -0,0 +1,199 @@+"""Contract ① (docs/framework_zh.md §4.1), the envelope: the seat-facing HTTP layer shared by both protocols: /<SEAT>/<endpoint>, the caller's address must be that seat's+container (SEAT_HOSTS=A=seat_a,B=seat_b; without it only localhost), at most 4 open requests and 20 per second per+seat, JSON bodies up to 64 KiB. A service maps endpoints to methods returning (status, body).++The budget (core 0.2.16) belongs to the authenticated seat: the seat a request names in its path, once the caller's+address is allowed to be that seat. A request for a seat its address may not be is refused (403) before it spends+anything, so a seat never spends another seat's budget. Before a request is read, an address may hold the budget of+every seat it may be (4 open connections and 20 per second per such seat); an address that may be no seat is refused.+Cores <= 0.2.15 charged a connection to the first seat its address may be: without SEAT_HOSTS every local seat shared+the first seat's budget (a team format's local seats got 429s). Every refusal for the budget is a bare 429 (no body),+which never reached the match: core/client.py retries it."""+from __future__ import annotations++import json+import socket+import sys+import threading+import time+import traceback+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import parse_qsl++from .sport import Refused, check_body++SLOTS, RATE = 4, 20 # per seat: open requests, requests per second+++def seat_allowed(seat, addr, hosts):+ if seat not in hosts:+ return addr in ("127.0.0.1", "::1")+ try:+ return addr in {a[4][0] for a in socket.getaddrinfo(hosts[seat], None)}+ except OSError:+ return False+++def make_server(service, seats, hosts, port=8000):+ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *a):+ pass++ def setup(self):+ super().setup()+ self.connection.settimeout(10)++ def send(self, code, value):+ raw = json.dumps(value, default=float).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True+ try:+ self.wfile.write(raw)+ except (BrokenPipeError, ConnectionResetError):+ pass++ def dispatch(self, post):+ path, _, self.qs = self.path.partition("?") # a GET may carry ?team_since=N (core 0.2.20)+ bits = path.strip("/").split("/")+ if len(bits) != 2 or bits[0] not in seats or not seat_allowed(bits[0], self.client_address[0], hosts):+ return self.send(403, {"error": "seat not authorized"})+ seat, ep = bits+ if not self.server.admit(seat): # the authenticated seat's own budget, never another seat's+ return self.too_many()+ try:+ self.handle_seat(seat, ep, post)+ finally:+ self.server.release(seat)++ def too_many(self):+ try: # read a small body first: closing on unread data may reset the reply+ n = int(self.headers.get("Content-Length", "0"))+ if 0 < n <= 65536:+ self.rfile.read(n)+ except (ValueError, OSError):+ pass+ self.send_response(429)+ self.send_header("Content-Length", "0")+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True++ def handle_seat(self, seat, ep, post):+ try: # the request itself: any problem is the caller's (400), never a failure+ body = {}+ if not post and self.qs: # GET parameters: small integers only (team_since, since)+ for key, val in parse_qsl(self.qs[:256], keep_blank_values=False)[:4]:+ if key in ("team_since", "since"):+ if not val.isdigit() or len(val) > 12:+ raise Refused(f"{key} must be a non-negative integer (a seq)")+ body[key] = int(val)+ if post:+ n = int(self.headers.get("Content-Length", "0"))+ if not 0 <= n <= 65536:+ raise Refused("request too large (at most 64 KiB)")+ body = json.loads(self.rfile.read(n) or b"{}")+ if not isinstance(body, dict):+ raise Refused("JSON object required")+ check_body(body)+ except Refused as exc:+ return self.send(exc.code, {"error": str(exc)})+ except Exception: # noqa: BLE001+ return self.send(400, {"error": "malformed request: a JSON object of at most 64 KiB required"})+ try:+ fn = service.routes(post).get(ep)+ code, out = (404, {"error": "unknown endpoint"}) if fn is None else fn(seat, body)+ except Refused as exc:+ code, out = exc.code, {"error": str(exc)}+ if exc.cause:+ print(f"refused {seat}/{ep}: {exc.cause}", file=sys.stderr, flush=True)+ except (ValueError, TypeError, KeyError, OverflowError) as exc:+ code, out = 400, {"error": "invalid request"}+ print(f"invalid request {seat}/{ep}: {type(exc).__name__}: {str(exc)[:200]}", file=sys.stderr,+ flush=True)+ except BlockingIOError as exc: # core/workers.py: our own text+ code, out = 429, {"error": str(exc)}+ except Exception as exc: # noqa: BLE001+ traceback.print_exc()+ service.failure(ep, exc)+ code, out = 500, {"error": "technical failure"} # the details stay in the logs (G9)+ self.send(code, service.public(out) if hasattr(service, "public") else out) # no hidden seed++ def do_GET(self):+ self.dispatch(False)++ def do_POST(self):+ self.dispatch(True)++ class Bounded(ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, *a, **kw):+ super().__init__(*a, **kw)+ self.lock = threading.Lock()+ self.slots = {s: threading.BoundedSemaphore(SLOTS) for s in seats}+ self.arrivals = {s: [] for s in seats}+ self.open = {} # address -> connections not yet closed+ self.recent = {} # address -> connection times in the last second++ def admit(self, seat):+ """A request of the authenticated seat: its own open requests and rate (in a handler thread)."""+ with self.lock:+ now = time.monotonic()+ self.arrivals[seat] = [t for t in self.arrivals[seat] if now - t < 1]+ if len(self.arrivals[seat]) >= RATE or not self.slots[seat].acquire(False):+ return False+ self.arrivals[seat].append(now)+ return True++ def release(self, seat):+ self.slots[seat].release()++ def process_request(self, request, addr):+ # before the request is read: the address may hold the budget of every seat it may be, no more+ n = sum(1 for s in seats if seat_allowed(s, addr[0], hosts))+ with self.lock:+ now = time.monotonic()+ recent = [t for t in self.recent.get(addr[0], ()) if now - t < 1]+ ok = n > 0 and len(recent) < RATE * n and self.open.get(addr[0], 0) < SLOTS * n+ if ok:+ self.recent[addr[0]] = recent + [now]+ self.open[addr[0]] = self.open.get(addr[0], 0) + 1+ elif recent:+ self.recent[addr[0]] = recent+ else:+ self.recent.pop(addr[0], None)+ if not ok:+ try:+ request.settimeout(.1)+ request.sendall(b"HTTP/1.1 429 Too Many Requests\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")+ except OSError:+ pass+ self.shutdown_request(request)+ return+ try:+ super().process_request(request, addr)+ except Exception:+ self.closed(addr[0])+ raise++ def closed(self, host):+ with self.lock:+ left = self.open.get(host, 0) - 1+ if left > 0:+ self.open[host] = left+ else:+ self.open.pop(host, None)++ def process_request_thread(self, request, addr):+ try:+ super().process_request_thread(request, addr)+ finally:+ self.closed(addr[0])++ return Bounded(("0.0.0.0", port), Handler)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/launch.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/launch.pynew file mode 100644index 0000000000..ff8a35575d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/launch.py@@ -0,0 +1,97 @@+"""Trusted launcher of a task's sim container: one metering proxy per seat (the unchanged think_proxy.py of players/+metering, copied by the generator to metering/think_proxy.py next to core/; seat i on port 18090 + i; model+credentials stay in this container) and the match service (core.serve).++A seat in player mode "unmetered" (PLAYER_MODE_<seat>, core 0.2.29) gets no proxy: its runner meters the model.++Per-seat settings of a seat's proxy (the runner sets them; the compose file passes them through):+ RO_SEAT_SELECT_<seat> = "VAR=SOURCE,..." VAR takes SOURCE's value (e.g. a second account's credential)+ RO_SEAT_ENV_<VAR>_<seat> = value a non-empty value replaces VAR (e.g. the route of OpenAI-style calls)+After the mapping a proxy keeps no RO_SEAT_SELECT_* / RO_SEAT_ENV_* and no other seat's per-seat variable (<VAR>_<other+seat> for every per-seat VAR, PLAYER_MODE_<other seat>): a seat's proxy never holds another seat's credentials. A seat+on route "chatgpt" (THINK_OPENAI_ROUTE: a ChatGPT subscription) keeps only the credentials given to it alone (non-empty+RO_SEAT_ENV_<VAR>_<seat>); every task-wide credential (e.g. the OpenRouter or Azure key) is dropped from its proxy.+A credential is a per-seat VAR that is not a THINK_* setting.+"""+import os+import subprocess+import sys+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SEATS = os.environ.get("RO_SEATS", "A,B").split(",")+DATA = os.environ.get("RCB_DATA", "/data")+PROXY = ROOT.parent / os.environ.get("RO_METER_PROXY", "metering/think_proxy.py")+++def seat_env(seat: str, env: dict, seats=None) -> dict:+ """The environment of `seat`'s metering proxy."""+ seats = seats or SEATS+ env = dict(env)+ env["THINK_CLIENT_HOST"] = "seat_" + seat.lower() if len(seats) > 1 else env.get("THINK_CLIENT_HOST", "player")+ env["THINK_USAGE_FILE"] = f"{DATA}/think_usage_{seat}.json"+ env["THINK_CALLS_FILE"] = f"{DATA}/think_calls_{seat}.jsonl"+ for pair in filter(None, env.get(f"RO_SEAT_SELECT_{seat}", "").split(",")):+ var, _, src = pair.partition("=")+ if var and src in env:+ env[var] = env[src]+ own = set() # the VARs given to this seat alone+ for key in [k for k in env if k.endswith("_" + seat) and k.startswith("RO_SEAT_ENV_")]:+ if env[key]:+ own.add(key[len("RO_SEAT_ENV_"):-len(seat) - 1])+ env[key[len("RO_SEAT_ENV_"):-len(seat) - 1]] = env[key]+ per_seat = {"PLAYER_MODE"} # every VAR set per seat (any seat's RO_SEAT_ENV_<VAR>_<s>)+ for s in seats:+ per_seat |= {k[len("RO_SEAT_ENV_"):-len(s) - 1] for k in env+ if k.startswith("RO_SEAT_ENV_") and k.endswith("_" + s) and len(k) > len("RO_SEAT_ENV_") + len(s) + 1}+ others = [s for s in seats if s != seat]+ for k in list(env):+ if k.startswith(("RO_SEAT_ENV_", "RO_SEAT_SELECT_")) or any(k == f"{v}_{o}" for o in others for v in per_seat):+ del env[k]+ if env.get("THINK_OPENAI_ROUTE", "").strip().lower() == "chatgpt": # a subscription seat: its own credentials only+ for k in per_seat - own:+ if not k.startswith("THINK_") and k != "PLAYER_MODE":+ env.pop(k, None)+ return env+++def seat_mode(seat: str, env=None) -> str:+ """The seat's player mode, as core.seats.Seat reads it."""+ env = os.environ if env is None else env+ return env.get(f"PLAYER_MODE_{seat}", env.get("RCB_PLAYER_MODE", "model"))+++def main():+ if len(sys.argv) > 1: # one seat's proxy+ seat = sys.argv[1]+ env = seat_env(seat, dict(os.environ))+ os.execve(sys.executable, [sys.executable, str(PROXY), str(18090 + SEATS.index(seat))], env)+ Path(DATA).mkdir(exist_ok=True)+ for s in SEATS:+ open(f"{DATA}/think_calls_{s}.jsonl", "a").close()+ procs = []+ try:+ metered = [s for s in SEATS if seat_mode(s) != "unmetered"]+ if PROXY.exists():+ for s in metered: # an unmetered seat (core 0.2.29) gets no proxy+ procs.append(subprocess.Popen([sys.executable, __file__, s]))+ elif metered:+ print(f"no metering proxy at {PROXY}: model seats cannot play", file=sys.stderr, flush=True)+ procs.append(subprocess.Popen([sys.executable, "-m", "core.serve"], cwd=ROOT.parent))+ while all(p.poll() is None for p in procs):+ time.sleep(.5)+ raise RuntimeError("a required service exited")+ finally:+ for p in procs:+ if p.poll() is None:+ p.terminate()+ for p in procs:+ try:+ p.wait(timeout=3)+ except subprocess.TimeoutExpired:+ p.kill()+++if __name__ == "__main__":+ main()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/local.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/local.pynew file mode 100644index 0000000000..76ed991488--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/local.py@@ -0,0 +1,244 @@+"""In-process matches of built-in players (no HTTP, no wall clock): what the checks (tools/check) use for the generic+tests, the fairness check and golden recordings. The players see what they would see over HTTP (core/client.py: the+whitelisted observation with the camera images), the actions go through the same action layer, and the episode is the+same episode.jsonl the live service writes, so `python -m core.episode` replays it in a fresh process.++ play(sport, cfg, players, data=None, render=True) -> {"scores", "winner", "decided_by", "ranking", "k", "digest", ...}+"""+from __future__ import annotations++import base64+import json+from pathlib import Path++from . import PROTOCOLS, VERSION+from . import score as score_mod+from . import spec as spec_mod+from .channel import TeamChannel+from .diaglog import Acts, jsonable, safe, view_steps+from .episode import Episode+from .observe import CameraWorker, filter_fields, players_scene+from .outcome import decide+from .service import own_hook, public_spec+from .sport import FINISHED, UNIT_OVER, Refused, parse_action++MAX_REFUSED = 50 # local play: a player whose actions keep being refused fails the match run++DEFAULT_CLOCK_S = 3600.0+++class Views:+ """The view a player gets: {"state": core fields + the whitelisted observation, "observation": images}."""++ def __init__(self, sport, cfg, m, decl, render: bool, plugin: str | None = None, channel=None):+ self.sport, self.cfg, self.m, self.render, self.plugin = sport, cfg, m, render, plugin+ self.channel = channel # the team channel (core/channel.py), as the live service runs it+ self.allowed = spec_mod.whitelist(decl)+ self.columns = int((decl.get("observation") or {}).get("columns", 2))+ self.cam = None+ self.leaks: list[str] = []+ self.own_images = own_hook(m, "camera_job") or not own_hook(m, "cameras")+ self.log = None # diagnostic rows (core 0.2.25): set by play() with an episode+ self.acts = Acts(cfg.seats)++ def view(self, seat, extra: dict, query=None) -> dict:+ obs, bad = filter_fields(self.m.observe(seat, query), self.allowed)+ self.leaks += bad+ if self.channel is not None and self.channel.enabled: # as Service.observation (core 0.2.21)+ msgs, top = self.channel.messages(seat, self.m.k, self.m.dt or 1.0) # the recent ones, never consumed+ obs["team_messages"], obs["team_seq"] = msgs, top+ if self.log is not None:+ for d in self.channel.deliver(seat, msgs, self.m.k):+ self.log("team_delivered", **d)+ out = {"state": {"seat": seat, **extra, **obs}, "observation": {}}+ job, meta = None, {}+ if self.render and self.own_images:+ job, meta = self.m.camera_job(seat)+ if job is not None:+ img = self.sport.worker_call(None, "render", job)+ out["observation"] = {"image_png_b64": base64.b64encode(img["png"]).decode(), **meta}+ elif self.render:+ cams = self.m.cameras(seat, query)+ if cams:+ if self.cam is None:+ scene = (players_scene(self.sport, self.plugin, self.cfg) if self.plugin else+ self.sport.scene(self.cfg))+ self.cam = CameraWorker(scene, self.cfg.renderer)+ job = cams+ img = self.cam.draw(self.m.render_state(), cams, self.columns)+ out["observation"] = {"image_png_b64": base64.b64encode(img["png"]).decode(), "tiles": img["tiles"]}+ if self.log is not None: # as the service's observe row+ obs_id = self.acts.new_obs(seat)+ self.log("observe", seat=seat, obs_id=obs_id, k=self.m.k, view_steps=view_steps(meta, job, self.m.k),+ query=query)+ return out+++def _header(ep, sport, cfg):+ if ep is not None:+ ep.write("header", cfg=cfg.to_json(), sport=sport.name, revision=sport.revision, protocol=sport.protocol,+ source_sha=None, versions={"core": VERSION, "sport": sport.revision}, local=True)+++def seat_spec(sport, cfg, seat, m=None, plugin=None) -> dict:+ """What GET /spec tells `seat` (without the protocol's timing part)."""+ decl = spec_mod.load(plugin) if plugin else {}+ m = m or sport.build(cfg)+ return {"seat": seat, "side": cfg.side_of(seat), "protocol": PROTOCOLS[sport.protocol], "revision": sport.revision,+ "action_level": cfg.action_level, "play": cfg.play, "format": cfg.format,+ **public_spec(sport, cfg, seat, m, sport.action_layer(cfg.action_level), decl)}+++def make_players(sport, cfg, names: dict, plugin=None, seed=None) -> dict:+ """seat -> built-in player, by name (Sport.players())."""+ table = sport.players()+ return {s: table[n](seat_spec(sport, cfg, s, plugin=plugin), s, cfg.seed if seed is None else seed)+ for s, n in names.items()}+++def play(sport, cfg, players: dict, data: Path | str | None = None, render: bool = True, plugin: str | None = None,+ max_actions: int = 10000, max_steps: int = 10 ** 7, every: int = 5) -> dict:+ """Play one match of built-in players (seat -> player). Turn protocol: the sport's to_move() decides who acts;+ realtime: every `every` control steps each seat may act; reviews end at once. A declared reaction delay D+ (sport.toml [timing] reaction_delay_steps, core 0.2.18; read when `plugin` is given) holds an act until D steps+ after the observation it answers, where it is lowered and applied (core/realtime.py); a seat with an act held+ does not observe."""+ decl = spec_mod.load(plugin) if plugin else {}+ m = sport.build(cfg)+ layer = sport.action_layer(cfg.action_level)+ ep = None+ if data is not None:+ Path(data).mkdir(parents=True, exist_ok=True)+ (Path(data) / "episode.jsonl").unlink(missing_ok=True)+ ep = Episode(Path(data) / "episode.jsonl")+ _header(ep, sport, cfg)+ channel = TeamChannel(cfg, decl.get("team_channel"))+ views = Views(sport, cfg, m, decl, render, plugin, channel)+ clocks = {s: DEFAULT_CLOCK_S for s in cfg.seats}+ refused = {s: 0 for s in cfg.seats}+ log = (lambda ev, **row: ep.write(ev, **row)) if ep is not None else (lambda ev, **row: None)+ dlog = safe(log) # diagnostic rows (core/diaglog.py, core 0.2.25)+ if ep is not None:+ views.log = dlog+ acts = views.acts+ refused: dict = {}+ if sport.protocol == "turn":+ n = 0+ while m.phase().state != FINISHED and n < max_actions:+ seat = m.to_move()+ v = views.view(seat, {"phase": "play", "turn": "you", "your_turn": True, "done": False,+ "clock_left_s": clocks[seat]})+ body = players[seat].act(v)+ try:+ cmd = parse_action(layer, seat, body, m, {"clock_left_s": dict(clocks)})+ except Refused: # an invalid request is refused (HTTP 400 in a real match), not a crash+ refused[seat] = refused.get(seat, 0) + 1+ if refused[seat] > MAX_REFUSED:+ raise RuntimeError(f"seat {seat}: more than {MAX_REFUSED} refused actions in local play")+ continue+ low, _info = layer.lower(seat, cmd, None, m)+ act_id = acts.new(seat)+ dlog("act_received", seat=seat, k=m.k, act_id=act_id, obs_id_last=acts.last_obs.get(seat), decision=cmd)+ log("cmd", k=m.k, seat=seat, cmd=low)+ k_cmd = m.k+ applied = m.apply(seat, low) or {}+ dlog("effect", seat=seat, act_id=act_id, k=k_cmd, info=jsonable(applied),+ **({"rejected": True} if "rejected" in applied else {}))+ n += 1+ else:+ plan = {s: sport.worker_init("plan", s, cfg) for s in cfg.seats} if getattr(layer, "worker", None) else {}+ delay = int(getattr(layer, "delay_steps", 0) or 0)+ react = spec_mod.reaction_delay(decl)+ scheduled: list = []+ held: dict = {} # seat -> (effect step, cmd): the declared reaction delay++ def effect(seat, cmd, act_id=None):+ job = layer.snapshot(seat, cmd, m, m.k)+ prepared = None+ if job is not None:+ prepared = (sport.worker_call(plan[seat], "plan", job) if plan else layer.prepare(job))+ low, info = layer.lower(seat, cmd, prepared, m)+ if delay:+ scheduled.append((m.k + delay, seat, low, act_id))+ else:+ apply(seat, low, act_id)++ def apply(seat, low, act_id, count=True):+ log("cmd", k=m.k, seat=seat, cmd=low)+ rej = "rejected" in (m.apply(seat, low) or {})+ if rej and count:+ refused[seat] = refused.get(seat, 0) + 1+ if act_id is not None:+ dlog("effect", seat=seat, act_id=act_id, k=m.k, **({"rejected": True} if rej else {}))++ def say(seat, v):+ """a built-in player's team-channel message (optional message(view) -> text | None; core 0.2.21), sent+ under the channel's limits as POST /<seat>/say would be (a refused message is dropped)"""+ f = getattr(players[seat], "message", None)+ text = f(v) if f is not None and channel.enabled else None+ if text and channel.say(seat, text, m.k, m.dt or 1.0)[0] == 200:+ log("team", seat=seat, k=m.k, seq=channel.seq.get(cfg.side_of(seat)), text=text)++ while m.phase().state != FINISHED and m.k < max_steps:+ if m.phase().state == UNIT_OVER:+ for x in scheduled:+ dlog("act_dropped", seat=x[1], act_id=x[3], k=m.k, why="unit_over")+ for seat, x in held.items():+ dlog("act_dropped", seat=seat, act_id=x[2], k=m.k, why="unit_over")+ scheduled.clear()+ held.clear()+ log("resume", k=m.k)+ m.resume()+ tick = getattr(layer, "tick", None) # a layer's per-step command (core/realtime.py apply_pending)+ if tick is not None:+ for seat in cfg.seats:+ low = tick(seat, m)+ if low is not None:+ log("cmd", k=m.k, seat=seat, cmd=low)+ if "rejected" in (m.apply(seat, low) or {}):+ refused[seat] = refused.get(seat, 0) + 1+ for item in [x for x in scheduled if x[0] <= m.k]:+ scheduled.remove(item)+ apply(item[1], item[2], item[3], count=False)+ for seat in [s for s in cfg.seats if s in held and held[s][0] <= m.k]:+ _k, cmd, act_id = held.pop(seat)+ effect(seat, cmd, act_id)+ if m.k % every == 0:+ for seat in cfg.seats:+ if seat in held: # one act in flight+ continue+ v = views.view(seat, {"phase": "running", "world": "running", "step": m.k,+ "t_sim": m.k * m.dt, "done": False})+ body = players[seat].act(v)+ say(seat, v)+ if body is None:+ continue+ try:+ cmd = parse_action(layer, seat, body, m, {})+ except Refused: # refused as in a real match (HTTP 400): the world goes on+ refused[seat] = refused.get(seat, 0) + 1+ continue+ act_id = acts.new(seat)+ dlog("act_received", seat=seat, k=m.k, act_id=act_id, obs_id_last=acts.last_obs.get(seat),+ seen=m.k, entity=(cmd.get("entity") if isinstance(cmd, dict) else None), decision=cmd)+ if react:+ held[seat] = (m.k + react, cmd, act_id)+ else:+ effect(seat, cmd, act_id)+ events = m.step()+ if events:+ dlog("event", k=m.k, events=jsonable(events))+ for x in scheduled: # never took effect: the match ended first+ dlog("act_dropped", seat=x[1], act_id=x[3], k=m.k, why="match_over")+ for seat, x in held.items():+ dlog("act_dropped", seat=seat, act_id=x[2], k=m.k, why="match_over")+ finished = m.phase().state == FINISHED+ log("end", k=m.k, reason="match_over" if finished else "unfinished")+ out = decide(m, None, None, cfg.side_list(), cfg.side_of)+ res = {"scores": m.scores(), "winner": out.winner, "decided_by": out.decided_by, "ranking": out.ranking,+ "solo": out.solo, "k": m.k, "digest": m.state_digest(), "finished": finished,+ "observation_leaks": sorted(set(views.leaks)), "rejected": refused, "final_fields": m.final_fields(),+ "continuous": score_mod.compute(m, decl, cfg.side_list())}+ if data is not None:+ (Path(data) / "local_result.json").write_text(json.dumps(res, default=float))+ return resdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/api_errors.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/api_errors.pynew file mode 100644index 0000000000..e9bd733ddc--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/api_errors.py@@ -0,0 +1,132 @@+"""Model-API errors of one seat, classified for the trial's validity (docs/EAI_STANDARD_REALTIME_1_0.md, "Validity").++The metering proxy (think_proxy.py) logs every request of a seat to its think_calls file (think_calls.jsonl, or+think_calls_<seat>.jsonl in a duel) and counts failed model calls and in-proxy 429 retries in the usage file. A model-API+error is a model call that did not complete successfully (an HTTP error such as 429 or 5xx, a stream error, a broken+connection) or one 429 retry inside the proxy. Each error is+ * transient when a later model call of the same seat completed successfully (the harness retried and got past it);+ * unrecovered when no model call of that seat completed successfully after it (the agent stopped, or the session+ ended, because of the model API, e.g. an account rate limit it could not get past).+A seat's model API failed the trial (`api_failure`, the trial's proxy_error) only if it had an unrecovered error or more+than MAX_TRANSIENT_API_ERRORS transient errors in the match. Transient errors below the limit are only counted and+reported. Azure deployment switches (azure_failovers) are not errors: the request completed on another replica.++The same file is copied into every Olympiad task's sim (scripts/olympiad/generate.py) and used by+scripts/olympiad/regrade_transient.py. Standard library only.+"""+from __future__ import annotations++import json+import os+import threading++MAX_TRANSIENT_API_ERRORS = 5+++def calls_file_for(usage_file: str) -> str:+ """The think_calls file the proxy writes next to `usage_file` (think_proxy.py's own rule)."""+ base = os.path.basename(usage_file)+ if "think_usage" in base:+ return usage_file.replace("think_usage", "think_calls").rsplit(".json", 1)[0] + ".jsonl"+ return os.path.join(os.path.dirname(usage_file) or ".", "think_calls.jsonl")+++class SeatApiErrors:+ """Incremental classifier of one seat's think_calls records (reads only the lines added since the last call)."""++ def __init__(self, calls_file: str | None = None):+ self.calls_file = calls_file+ self.lock = threading.Lock()+ self.reset()++ def reset(self) -> None:+ self.offset = 0+ self.error_times: list[float] = [] # when each error happened (a failed call's end, a retry's time)+ self.last_ok = None # end time of the latest successfully completed model call+ self.logged_failed = 0 # failed model calls in the log+ self.logged_retries = 0 # in-proxy 429 retries in the log+ self.model_calls = 0++ def add(self, rec) -> None:+ if not isinstance(rec, dict) or not rec.get("model_call"):+ return+ self.model_calls += 1+ end = _num(rec.get("t1"), _num(rec.get("t0"), 0.0))+ retries = rec.get("retries") if isinstance(rec.get("retries"), list) else []+ for r in retries:+ self.error_times.append(_num(r.get("at") if isinstance(r, dict) else None, end))+ self.logged_retries += len(retries)+ if rec.get("status") == 200 and rec.get("completed") is True:+ self.last_ok = end if self.last_ok is None else max(self.last_ok, end)+ else:+ self.logged_failed += 1+ self.error_times.append(end)++ def read(self) -> None:+ if not self.calls_file:+ return+ try:+ with open(self.calls_file, "rb") as f:+ f.seek(0, os.SEEK_END)+ if f.tell() < self.offset: # the file was replaced: start again+ self.reset()+ f.seek(self.offset)+ data = f.read()+ except OSError:+ return+ end = data.rfind(b"\n")+ if end < 0:+ return+ self.offset += end + 1 # only complete lines; a line being written waits+ for line in data[:end].splitlines():+ if line.strip():+ try:+ self.add(json.loads(line))+ except ValueError:+ pass # not a record (think_proxy.py writes whole lines)++ def summary(self, usage: dict | None = None) -> dict:+ transient = sum(1 for t in self.error_times if self.last_ok is not None and self.last_ok > t)+ unrecovered = len(self.error_times) - transient+ missing = 0+ if isinstance(usage, dict): # counted by the proxy but not (yet) in the log: not recovered+ missing = (max(0, int(usage.get("failed_model_calls", 0) or 0) - self.logged_failed)+ + max(0, int(usage.get("rate_limit_retries", 0) or 0) - self.logged_retries))+ unrecovered += missing+ return {"transient_api_errors": transient, "unrecovered_api_errors": unrecovered,+ "api_failure": bool(unrecovered > 0 or transient > MAX_TRANSIENT_API_ERRORS),+ "model_calls_logged": self.model_calls, "unlogged_api_errors": missing}+++def _num(v, default):+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else default+++def classify_calls(records, usage: dict | None = None) -> dict:+ """Classify a list of think_calls records (dicts). Returns transient_api_errors, unrecovered_api_errors and+ api_failure (unrecovered > 0 or transient > MAX_TRANSIENT_API_ERRORS)."""+ s = SeatApiErrors()+ for rec in records:+ s.add(rec)+ return s.summary(usage)+++def classify_file(calls_file: str, usage: dict | None = None) -> dict:+ s = SeatApiErrors(calls_file)+ s.read()+ return s.summary(usage)+++_SEATS: dict[str, SeatApiErrors] = {}+_SEATS_LOCK = threading.Lock()+++def seat_api_errors(usage_file: str, usage: dict | None = None) -> dict:+ """The classification of the seat metered in `usage_file` (its think_calls file read incrementally), for a server's+ final record. `usage`: that seat's usage counters, already read."""+ path = calls_file_for(usage_file)+ with _SEATS_LOCK:+ s = _SEATS.setdefault(path, SeatApiErrors(path))+ with s.lock:+ s.read()+ return s.summary(usage)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/think_clock.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/think_clock.pynew file mode 100644index 0000000000..a80909054a--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/metering/think_clock.py@@ -0,0 +1,114 @@+"""Wallclock model-turn gate. Oracle exemption must be explicitly enabled by the runner."""+from __future__ import annotations+import json+import os+import threading+import time++USAGE_FILE = os.environ.get("THINK_USAGE_FILE", "/data/think_usage.json")+++class MeterError(RuntimeError):+ pass+++def read_usage(path=USAGE_FILE):+ try:+ with open(path) as f:+ value = json.load(f)+ return value if isinstance(value, dict) else {}+ except (OSError, ValueError):+ return {}+++class ThinkClock:+ def __init__(self, seconds_per_ktok=0.0, usage_file=USAGE_FILE, **kwargs):+ self.usage_file = usage_file+ self.mode = kwargs.get("mode") or os.environ.get("RCB_PLAYER_MODE", "model")+ self.min_started_at = 0.0+ if self.mode not in ("model", "oracle"):+ raise ValueError("RCB_PLAYER_MODE must be model or oracle")+ act_rule = os.environ.get("RCB_ACT_RULE", "per_response")+ if act_rule not in ("per_response", "program"):+ raise ValueError("RCB_ACT_RULE must be per_response or program")+ self.rule = "explicit_oracle" if self.mode == "oracle" else (+ "program" if act_rule == "program" else "completed_act_calls")+ self._calls_at_decision = 0+ self._epoch = None+ self._last = {}+ self.lock = threading.Lock()++ def check_ready(self):+ if self.mode == "oracle":+ return {}+ u = read_usage(self.usage_file)+ counters = ("model_calls_completed", "act_calls_completed", "requests", "in_flight")+ if (not isinstance(u.get("epoch"), str) or not u["epoch"]+ or any(type(u.get(k)) is not int or u[k] < 0 for k in counters)+ or u["requests"] < 1 or u["act_calls_completed"] > u["model_calls_completed"]+ or u["model_calls_completed"] > u["requests"]):+ raise MeterError("model meter is missing, invalid, or has not received a model request")+ if self._epoch is not None and u["epoch"] != self._epoch:+ raise MeterError("model meter restarted during this match")+ self._epoch = u["epoch"]+ if u["act_calls_completed"] < self._calls_at_decision:+ raise MeterError("model meter counters moved backwards during this match")+ return u++ def settle(self, max_wait_s=2.0):+ """Drain the response carrying start/ready before discarding its act credits."""+ if self.mode == "oracle" or self.rule == "program":+ return # program play: no per-response act credits to discard+ deadline = time.monotonic() + max_wait_s+ while self.check_ready()["in_flight"]:+ if time.monotonic() >= deadline:+ raise MeterError("model response did not settle before the match resumed")+ time.sleep(.01)++ def rebase(self):+ """Discard all pre-start/review act credits. Caller first settles model traffic."""+ with self.lock:+ if self.mode == "oracle":+ return+ u = self.check_ready()+ if u["in_flight"]:+ raise MeterError("cannot rebase the model meter while responses are in flight")+ self._calls_at_decision = u["act_calls_completed"]+ self._last = {}++ def last_call(self):+ return dict(self._last)++ def decided_by_model(self):+ with self.lock:+ if self.mode == "oracle":+ self._last = {"oracle": True}+ return True+ if self.rule == "program":+ # Program play: the agent's own program may act; a live, metered model session is still required.+ u = self.check_ready()+ self._last = {"program": True, "act_calls_completed": u["act_calls_completed"],+ "model_calls_completed": u["model_calls_completed"], "epoch": u["epoch"]}+ return True+ deadline = time.monotonic() + float(os.environ.get("WALLCLOCK_RULE_WAIT_S", "1"))+ while True:+ u = self.check_ready()+ done = u["act_calls_completed"]+ if done > self._calls_at_decision and u.get("last_act_started_at", 0) >= self.min_started_at:+ self._calls_at_decision = done+ self._last = {"act_calls_completed": done, "model_calls_completed": u["model_calls_completed"],+ "response_seq": u.get("last_act_response_seq"),+ "epoch": u["epoch"], "last_completed_at": u.get("last_act_call_at"),+ "request_started_at": u.get("last_act_started_at")}+ return True+ if not u["in_flight"] or time.monotonic() >= deadline:+ return False+ time.sleep(.01)++ def begin_segment(self, started_at):+ """Discard frozen requests, including responses still in flight at the barrier."""+ with self.lock:+ self.min_started_at = started_at+ if self.mode != "oracle":+ self._calls_at_decision = self.check_ready()["act_calls_completed"]+ self._last = {}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/observe.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/observe.pynew file mode 100644index 0000000000..94b46fc9b3--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/observe.py@@ -0,0 +1,154 @@+"""Observations (sport rule 1, docs/framework_zh.md §9): what a seat gets is the camera images, its own body and the+referee's information, and nothing else. The sport declares the fields of Match.observe() in sport.toml+([observation] fields); a field outside that whitelist is never delivered and is a technical error of the match.++The camera images: Match.cameras(seat, query) returns camera definitions, the task's renderer (renderers/, chosen by+the task parameter `renderer`) draws them from the sport's scene and Match.render_state(), and the core lays the+images out as tiles of one PNG (left to right, `columns` per row), described in the reply (`tiles`).++Reply images (core 0.2.8): Match.reply_views(seat, cmd, info) right after an action -> reply_job() snapshots the+frames under the lock -> CameraWorker.draw_job() draws them off the lock (the same renderer, scene and worker as the+observation) -> one PNG of tiles, each tile also naming its frame (`frame`, `label`) when there are several.++The scene of the players' images (core 0.2.9, renderer rule 6): Sport.scene(cfg), or the presentation scene the sport+declares for its players (sports/<sport>/presentation/presentation.toml `players`, bundled into the simulator by the+generator; renderers/presentation.players_scene): the same kinematics, finer visual meshes. Any other presentation+scene is refused (spectators only)."""+from __future__ import annotations++import copy+import struct+import zlib+from pathlib import Path++import numpy as np+++class WhitelistError(Exception):+ pass+++def filter_fields(obs: dict, allowed: set[str] | None) -> tuple[dict, list[str]]:+ """(the whitelisted part of obs, the names that were not allowed)."""+ if allowed is None:+ return obs, []+ bad = sorted(k for k in obs if k not in allowed)+ return {k: v for k, v in obs.items() if k in allowed}, bad+++def png(img: np.ndarray) -> bytes:+ """A minimal RGB8 PNG encoder (no imaging library needed in the sim)."""+ img = np.ascontiguousarray(img, dtype=np.uint8)+ h, w = img.shape[:2]+ raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))++ def chunk(tag, data):+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)++ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))+ + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))+++def reply_job(m, spec: dict | None, columns: int) -> dict | None:+ """Under the lock: Match.reply_views()'s answer -> a self-contained draw job (deep copies: the match may move on+ while the job is drawn off the lock). A frame without a state gets render_state() now."""+ if not spec or not spec.get("frames"):+ return None+ order = spec.get("order", "frame")+ if order not in ("frame", "camera"):+ raise ValueError(f"reply_views: order must be 'frame' or 'camera', not {order!r}")+ now = None+ frames = []+ for f in spec["frames"]:+ st = f.get("state")+ if st is None:+ now = m.render_state() if now is None else now+ st = now+ cams = list(f.get("cameras") or [])+ if not cams:+ raise ValueError("reply_views: every frame needs at least one camera")+ frames.append({"state": st, "cams": cams, "label": f.get("label")})+ return copy.deepcopy({"frames": frames, "order": order, "columns": int(spec.get("columns") or columns),+ "note": spec.get("note")})+++def compose(images: list[np.ndarray], names: list[str], columns: int = 2) -> tuple[np.ndarray, list[dict]]:+ """Tiles left to right, `columns` per row, each at its own size; -> (sheet, [{camera, x, y, width, height}])."""+ rows = [list(range(i, min(i + columns, len(images)))) for i in range(0, len(images), columns)]+ widths = [sum(images[j].shape[1] for j in r) for r in rows]+ heights = [max(images[j].shape[0] for j in r) for r in rows]+ sheet = np.zeros((sum(heights), max(widths), 3), np.uint8)+ tiles, y = [], 0+ for r, hgt in zip(rows, heights):+ x = 0+ for j in r:+ h, w = images[j].shape[:2]+ sheet[y:y + h, x:x + w] = images[j][..., :3]+ tiles.append({"camera": names[j], "x": x, "y": y, "width": w, "height": h})+ x += w+ y += hgt+ return sheet, tiles+++def players_scene(sport, plugin: str, cfg):+ """The scene of the players' images: the sport's presentation scene when it declares `players`, else+ Sport.scene(cfg)."""+ scene = sport.scene(cfg)+ d = Path(plugin).resolve().parent+ if not (d / "presentation" / "presentation.toml").is_file():+ return scene+ from renderers import presentation+ return presentation.players_scene(d, scene)+++class CameraWorker:+ """Draws a seat's camera definitions with the task's renderer (in-process or inside a render worker process)."""++ def __init__(self, scene, renderer_name: str | None):+ import renderers+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):+ raise ValueError("the players' images are drawn from the match scene (Sport.scene) or the presentation "+ "scene the sport declares for them; any other presentation scene is for spectators only "+ "(renderer rule 6)")+ self.name = renderer_name or renderers.DEFAULT+ self.renderer = renderers.load(self.name)(scene)++ def draw(self, state: dict, cams: list[dict], columns: int = 2) -> dict:+ from renderers.base import CameraDef+ defs = [CameraDef.from_dict(c) for c in cams]+ images = self.renderer.render(state, defs)+ sheet, tiles = compose(images, [c.name for c in defs], columns)+ return {"png": png(sheet), "tiles": tiles, "renderer": self.name}++ def draw_frames(self, job: dict) -> dict:+ """A reply job (reply_job()): every frame's cameras drawn from that frame's state, laid out frame after+ frame or camera after camera; a tile names its camera, and its frame (index, label) when there are several."""+ from renderers.base import CameraDef+ frames = job["frames"]+ drawn = [] # per frame: [(name, image)]+ for f in frames:+ defs = [CameraDef.from_dict(c) for c in f["cams"]]+ drawn.append(list(zip([c.name for c in defs], self.renderer.render(f["state"], defs))))+ cells = [] # (frame index, camera name, image)+ if job.get("order") == "camera":+ for j in range(max(len(d) for d in drawn)):+ cells += [(i, d[j][0], d[j][1]) for i, d in enumerate(drawn) if j < len(d)]+ else:+ cells = [(i, name, img) for i, d in enumerate(drawn) for name, img in d]+ sheet, tiles = compose([c[2] for c in cells], [c[1] for c in cells], int(job.get("columns", 2)))+ many = len(frames) > 1+ for t, (i, _, _) in zip(tiles, cells):+ if many:+ t["frame"] = i+ if frames[i].get("label"):+ t["label"] = frames[i]["label"]+ out = {"png": png(sheet), "tiles": tiles, "renderer": self.name}+ if job.get("note"):+ out["note"] = job["note"]+ return out++ def draw_job(self, job: dict) -> dict:+ """Any job of the core's camera worker: a reply job (frames) or an observation (state + cameras)."""+ if "frames" in job:+ return self.draw_frames(job)+ return self.draw(job["state"], job["cams"], job.get("columns", 2))diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/outcome.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/outcome.pynew file mode 100644index 0000000000..11916961f2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/outcome.py@@ -0,0 +1,50 @@+"""The no-draw decision chain (docs/framework_zh.md §5): a forfeit (a core decision: review or clock time, abandonment,+or a side that never started, "no_show"; sides that retired before it rank last, the last to retire first), then the+sport's tiebreaks in order (rulebook result -> rulebook tiebreak -> capped extra play -> last resort; the last one must+decide). A match with more than two sides is decided by the sport's classification (Match.ranking, best first). A solo+match (single format without an opponent: tiebreaks() == []) has no winner; its result is the score against the+success line. A match that did not finish has no winner."""+from __future__ import annotations++from dataclasses import dataclass, field++from .sport import FINISHED+++@dataclass+class Outcome:+ winner: str | None+ decided_by: str+ scores: dict+ ranking: list = field(default_factory=list)+ solo: bool = False+++def decide(match, forfeit_seat: str | None = None, why: str | None = None, sides=("A", "B"),+ side_of=lambda s: s, retired=()) -> Outcome:+ scores = match.scores()+ sides = list(sides)+ rules = match.tiebreaks()+ solo = len(sides) == 1 and not rules+ if forfeit_seat is not None:+ lost = side_of(forfeit_seat)+ others = [s for s in sides if s != lost and s not in retired]+ if len(others) == 1:+ return Outcome(others[0], f"forfeit:{why}", scores, others + [lost] + list(reversed(retired)))+ if not others and len(sides) == 1: # a single player who forfeits loses (to the line or the opponent)+ return Outcome(None, f"forfeit:{why}", scores, [], solo)+ if match.phase().state != FINISHED:+ return Outcome(None, "unfinished", scores, [], solo)+ if solo:+ return Outcome(None, "score", scores, list(sides), True)+ if len(sides) > 2:+ ranking = list(match.ranking() or [])+ if sorted(ranking) != sorted(sides):+ raise RuntimeError("a match of more than two sides must rank every side (Match.ranking)")+ return Outcome(ranking[0], "ranking", scores, ranking)+ for name, rule in rules:+ w = rule(match)+ if w is not None:+ rest = [s for s in sides if s != w]+ return Outcome(w, name, scores, [w] + rest)+ raise RuntimeError("a finished match must be decided by its last tiebreak (no draws)")diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/realtime.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/realtime.pynew file mode 100644index 0000000000..af44b36845--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/realtime.py@@ -0,0 +1,462 @@+"""Protocol eai-standard-realtime/1.0: a continuous world paced at slowdown S (one control step every dt x S wall+seconds), frozen at every unit end for the reviews of the seats the referee names (Phase.review).++Phases: prepare (until every seat sent start/ready; after the first, START_TIMEOUT_S: a side that has not started by+then loses, "no_show"; if none started, the match does not count; a single side has START_TIMEOUT_S from the service+start, else it loses) -> running -> review (each seat+in Phase.review sends ready WHY PLAN within READY_TIMEOUT_S, else its side loses, or with more than two sides retires+while the others go on) -> running ... -> over. The collect (every player session has ended) before the end: before+the start a side that has not started loses at once ("no_show", core 0.2.7; if no side started, "collected"); a single+side whose match has started loses ("abandoned", a valid loss, core 0.2.6); otherwise the match ends "collected"+(unfinished, not a valid trial).+Acts: one per (seat, entity) in flight (429); program play needs a live metered session, per-response play a fresh+completed model response (think_clock.py); the high action layer prepares off the world lock (in the seat's plan+worker) and is lowered at the next control-step boundary, where the whole batch of ready acts takes effect together,+or `delay_steps` later (the effect step is what the episode logs). Declared reaction delay (core 0.2.18): a sport+may declare D = sport.toml [timing] reaction_delay_steps; an act then takes effect (and is lowered) at step+max(the next control-step boundary, s + D), s = the step of the latest world state the service sent to the seat before+the act arrived (the `now` of any reply: observe, act, wait, status, ready), the same D for every seat, so that a+program that answers within D steps always gets exactly D, whatever the machine's load; a slower one gets its own+latency as before. Not declared: D = 0, the rule above unchanged. Observations may carry a query (observation+parameters, e.g. which camera) that the sport validates. Reply images (core 0.2.8): an act that takes effect at once+gets the images of its result (Match.reply_views), snapshotted at the effect step under the lock and drawn off the+lock after the act's timing is taken (`wall_s_after_request` excludes it; `render_wall_s` reports it), like an+observation; the world runs on meanwhile.+"""+from __future__ import annotations++import base64+import json+import math+import os+import time++import numpy as np++from . import spec as spec_mod+from .diaglog import jsonable, view_steps+from .episode import reaction_report+from .service import Service+from .sport import FINISHED, UNIT_OVER, Refused, parse_action+++def query_of(body) -> dict | None:+ q = (body or {}).get("query")+ if q is None:+ return None+ if not isinstance(q, dict) or len(json.dumps(q)) > 4096:+ raise Refused("query must be a JSON object of at most 4 KiB")+ return q+++class RealtimeService(Service):+ protocol = "realtime"+ protocol_id = "eai-standard-realtime/1.0"++ def __init__(self, *a, **kw):+ super().__init__(*a, **kw)+ self.slowdown = float(self.cfg.slowdown or 20)+ if not np.isfinite(self.slowdown) or self.slowdown <= 0:+ raise ValueError("invalid slowdown")+ self.period = self.m.dt * self.slowdown+ self.ready_deadline = self.resume_at = self.anchor = self.segment_start = None+ if len(self.cfg.side_list()) == 1: # nobody to wait for: the start window opens now+ self.ready_deadline = time.monotonic() + self.start_window()+ self.pending: dict = {} # (seat, entity) -> act waiting for the next boundary+ self.scheduled: list = [] # [effect_k, seat, low] lowered acts with a delayed effect+ self.delay = int(getattr(self.layer, "delay_steps", 0) or 0)+ self.react = spec_mod.reaction_delay(self.decl) # declared reaction delay D (core 0.2.18), 0 = none+ self.seen: dict = {} # seat -> step of the latest world state sent to it+ self.lates, self.run_steps, self.run_wall = [], 0, 0.0+ for st in self.seats.values():+ st.stats.update(attempts=0, applied=0, refused=0, refused_invalid=0, dropped=0, observations=0, plan_s=[],+ act_s=[], obs_age_s=[])++ def routes(self, post):+ if post:+ return {"start": self.ready, "ready": self.ready, "act": self.act, "wait": self.wait,+ "observe": self.observe, "say": self.say, "team": self.team}+ return {"spec": self.spec, "status": self.status, "observe": self.observe, "team": self.team}++ def spec_core(self):+ return {"timing": {"slowdown": self.slowdown, "control_dt": self.m.dt, "period_s": self.period,+ "policy": "report_only", "effect_delay_steps": self.delay,+ "reaction_delay_steps": self.react},+ "start": self.start_rule(),+ "decision_rule": ("program play: your own program may observe and act without a new model response; "+ "one act per seat in flight" if os.environ.get("RCB_ACT_RULE") == "program" else+ "one fresh completed model response per act, after both players resume")}++ def start_window(self) -> float:+ return float(os.environ.get("START_TIMEOUT_S") or os.environ.get("READY_TIMEOUT_S", "60"))++ # ------------------------------------------------------------------ replies+ def state(self, seat, query=None, since=None):+ core = {"phase": self.phase, "done": self.phase == "over", "reason": self.reason,+ "ready": {s: st.ready for s, st in self.seats.items()},+ "world": "running" if self.phase == "running" else "frozen", "step": self.m.k,+ "t_sim": self.m.k * self.m.dt}+ self.seen[seat] = self.m.k # every reply's `now` is a world state the seat has seen+ if self.retired:+ core["retired"] = list(self.retired)+ return {**core, **self.observation(seat, query, since)}++ def status(self, seat, body=None):+ since = self.team_since(body)+ with self.cond:+ return 200, self.state(seat, since=since)++ def ready(self, seat, body):+ st = self.seats[seat]+ st.meter.settle() # never under the world lock (may wait for a stream)+ with self.cond:+ if self.phase not in ("prepare", "review"):+ return 409, {"error": "not awaiting ready", "now": self.state(seat)}+ if st.retired:+ return 409, {"error": "your side has retired"}+ if self.phase == "review" and seat not in self.due():+ return 409, {"error": "no review is due from you now"}+ unit = self.m.unit()+ if st.ready:+ return 409, {"error": "ready already submitted"}+ why, plan = body.get("why", ""), body.get("plan", "")+ if not isinstance(why, str) or not isinstance(plan, str) or len(why) > 2000 or len(plan) > 2000:+ return 400, {"error": "why and plan must be strings of at most 2000 characters"}+ if self.phase == "review" and (not why.strip() or not plan.strip()):+ return 400, {"error": "both review fields required"}+ st.joined = st.ready = True+ if self.ready_deadline is None:+ self.ready_deadline = time.monotonic() + (self.start_window() if self.phase == "prepare" else+ float(os.environ.get("READY_TIMEOUT_S", "60")))+ if self.phase == "review":+ self.reviews.append({"seat": seat, "after_unit": unit, "why": why, "plan": plan})+ self.ep.write("ready", seat=seat, unit=unit, why=why, plan=plan)+ self.barrier()+ self.cond.notify_all()+ while self.phase in ("prepare", "review") and self.m.unit() == unit: # one start event releases all+ self.cond.wait(.5)+ return 200, {"accepted": "ready", "now": self.state(seat)}++ def barrier(self):+ if all(self.seats[s].ready for s in self.due()):+ self.resume_at = time.monotonic() + float(os.environ.get("BARRIER_LEAD_S", ".2"))++ def due(self):+ seats = self.cfg.seats if self.phase == "prepare" else self.m.phase().review+ return [s for s in seats if not self.seats[s].retired]++ def act(self, seat, body):+ st = self.seats[seat]+ try:+ cmd = parse_action(self.layer, seat, body, self.m, {})+ except Refused as exc: # a malformed action: the player's own error, never a failure+ with self.cond:+ self.refused_invalid(seat, exc)+ raise+ entity = str(cmd.get("entity", "")) if isinstance(cmd, dict) else ""+ arrived = time.monotonic()+ lock = st.act_lock(entity)+ if not lock.acquire(False):+ return 429, {"error": "one act request per seat" + (" and entity" if entity else "") + " may be in flight"}+ try:+ with self.cond:+ st.count("attempts")+ if self.phase != "running":+ return 409, {"error": "the match is over" if self.phase == "over" else "world is not running",+ "now": self.state(seat)}+ if st.retired:+ return 409, {"error": "your side has retired"}+ unit = self.m.unit()+ seen = self.seen.get(seat) # the world state this act answers (reaction delay)+ if not st.meter.decided_by_model():+ with self.cond:+ st.count("refused")+ self.ep.write("refused_not_model", seat=seat, unit=unit)+ return 429, {"error": "act needs a fresh completed response started after resume, one act per response"}+ receipt = st.meter.last_call()+ with self.cond:+ if self.phase != "running" or self.m.unit() != unit:+ return 409, {"error": "unit ended during response confirmation"}+ job = self.layer.snapshot(seat, cmd, self.m, st.stats["attempts"])+ act_id = self.acts.new(seat) # diagnostics (core 0.2.25): act -> observation -> effect+ self.ep.write("act_received", seat=seat, unit=unit, decision=cmd, model_call=receipt, k=self.m.k,+ act_id=act_id, obs_id_last=self.acts.last_obs.get(seat), seen=seen,+ entity=entity or None)+ prepared = None+ if job is not None:+ prepared = (self.workers["plan", seat].call(job) if self.layer.worker else self.layer.prepare(job))+ with self.cond:+ if isinstance(prepared, dict) and "worker_s" in prepared:+ st.sample("plan_s", prepared["worker_s"])+ if self.phase != "running" or self.m.unit() != unit:+ st.count("dropped")+ self.dropped({"act_id": act_id}, seat, "unit_over_planning" if self.phase != "over" else "match_over")+ return 409, {"error": "unit ended during planning", "now": self.state(seat)}+ item = {"unit": unit, "cmd": cmd, "prepared": prepared, "arrived": arrived, "result": None,+ "act_id": act_id, "entity": entity}+ if seen is not None:+ item["seen"] = seen # the reaction report (core 0.2.23), any D+ if self.react:+ item["earliest"] = seen + self.react+ self.pending[seat, entity] = item+ while item["result"] is None and self.phase == "running" and self.m.unit() == unit:+ self.cond.wait(.5)+ if item["result"] is None:+ return 409, {"error": "unit ended before effect", "now": self.state(seat)}+ out = {"call": "act", "took_effect": item["result"], "now": self.state(seat)}+ if item.get("images") is not None: # drawn off the lock: the world runs on+ try:+ out["observation"] = self.reply_images(seat, item["images"])+ except Exception as exc: # noqa: BLE001+ self.failure("act_images", exc)+ return 500, {**out, "error": "technical failure"}+ return 200, out+ finally:+ lock.release()++ def apply_now(self, seat, low, act=None):+ """Log and apply one low-level command. An act's row (act = its pending item) also carries `seen`, the step of+ the world state the act answered (None if the seat had been sent none): the reaction report (core 0.2.23)."""+ self.ep.write("cmd", k=self.m.k, seat=seat, cmd=low, **({"seen": act.get("seen")} if act is not None else {}))+ info = self.m.apply(seat, low) or {}+ if act is not None and act.get("act_id") is not None: # diagnostics (core 0.2.25): not in the cmd row+ self.diag("effect", seat=seat, act_id=act["act_id"], k=self.m.k, entity=act.get("entity") or None,+ **({"rejected": True} if "rejected" in info else {}))+ return info++ def dropped(self, item, seat, why):+ """An accepted act that will never take effect (diagnostics, core 0.2.25)."""+ if item.get("act_id") is not None:+ self.diag("act_dropped", seat=seat, act_id=item["act_id"], k=self.m.k, why=why)++ def apply_pending(self):+ tick = getattr(self.layer, "tick", None) # a layer's per-step command (the skill in the loop's step(),+ if tick is not None: # skilleval/inloop.py): applied and logged like any other+ for seat in self.cfg.seats:+ if self.seats[seat].retired:+ continue+ low = tick(seat, self.m)+ if low is not None and "rejected" in self.apply_now(seat, low):+ self.seats[seat].count("rejected")+ due = [x for x in self.scheduled if x[0] <= self.m.k]+ self.scheduled = [x for x in self.scheduled if x[0] > self.m.k]+ for _, seat, low, act in due:+ info = self.apply_now(seat, low, act)+ if "rejected" in info:+ self.seats[seat].count("rejected")+ batch, self.pending = self.pending, {}+ for (seat, _entity), item in batch.items():+ st = self.seats[seat]+ if item["unit"] != self.m.unit():+ st.count("dropped")+ self.dropped(item, seat, "unit_changed")+ continue+ if item.get("earliest", 0) > self.m.k: # held until its reaction delay has passed (core 0.2.18)+ self.pending[seat, _entity] = item+ continue+ low, info = self.layer.lower(seat, item["cmd"], item["prepared"], self.m)+ if self.delay:+ self.scheduled.append([self.m.k + self.delay, seat, low, {"seen": item.get("seen"),+ "act_id": item["act_id"],+ "entity": item["entity"]}])+ info = {"effect_step": self.m.k + self.delay, **info}+ else:+ applied = self.apply_now(seat, low, item)+ item["images"] = self.reply_job(seat, low, applied)+ info = {**applied, **info}+ if "rejected" in info:+ st.count("rejected")+ elapsed = time.monotonic() - item["arrived"]+ item["result"] = {"step": self.m.k, "t_sim": self.m.k * self.m.dt, "wall_s_after_request": elapsed,+ **({"seen_step": item["seen"], "reaction_delay_steps": self.react}+ if self.react and "seen" in item else {}),+ **self.layer.reply(seat, item["cmd"], info, self.m)}+ st.count("applied")+ st.sample("act_s", elapsed)++ def observe(self, seat, body=None):+ st = self.seats[seat]+ query = query_of(body)+ since = self.team_since(body)+ if not st.view_lock.acquire(False):+ return 429, {"error": "one observation per seat may be in flight"}+ try:+ with self.cond:+ if self.phase == "over": # core 0.2.26: no images after the end, the final state only+ return 409, {"error": "the match is over", "now": self.state(seat, since=since)}+ now, (job, meta) = self.query_guard(seat, query, lambda: (self.state(seat, query, since),+ self.camera_job(seat, query)))+ st.count("observations")+ obs_id = st.stats["observations"]+ k_obs = self.m.k+ meta = dict(meta)+ steps = view_steps(meta, job, k_obs)+ out = self.draw(seat, job) or {}+ age = max(0.0, time.monotonic() - meta.pop("wall_mono", time.monotonic()))+ with self.cond:+ st.sample("obs_age_s", age)+ self.ep.write("observe", seat=seat, obs_id=obs_id, age_s=age, query=query, k=k_obs, view_steps=steps)+ self.acts.observed(seat, obs_id) # what the seat's next act answers (act_received)+ obs = {"obs_id": obs_id, **meta, "obs_age_wall_s": age, "render_wall_s": out.get("worker_s", 0.0)}+ if out.get("png"):+ obs["image_png_b64"] = base64.b64encode(out["png"]).decode()+ if out.get("tiles"):+ obs["tiles"] = out["tiles"]+ return 200, {"call": "observe", "now": now, "observation": obs}+ finally:+ st.view_lock.release()++ def wait(self, seat, body):+ try:+ d = float(body.get("dt", 0))+ except (TypeError, ValueError, OverflowError):+ d = math.nan+ if not np.isfinite(d) or not 0 < d <= 1:+ return 400, {"error": "dt must be 0..1 game seconds"}+ since = self.team_since(body)+ with self.cond:+ target, unit = self.m.k + int(np.ceil(d / self.m.dt)), self.m.unit()+ while self.phase == "running" and self.m.unit() == unit and self.m.k < target:+ self.cond.wait(.5)+ return 200, {"now": self.state(seat, since=since)}++ # ------------------------------------------------------------------ the world loop+ def on_end(self):+ if self.segment_start is not None:+ self.run_wall += time.monotonic() - self.segment_start+ self.segment_start = None+ self.drop_all("match_over")++ def drop_all(self, why):+ """The acts waiting for their effect step will never take effect: act_dropped rows, queues cleared."""+ for (s, _e), item in self.pending.items():+ self.dropped(item, s, why)+ for _k, s, _low, act in self.scheduled:+ self.dropped(act, s, why)+ self.pending.clear()+ self.scheduled.clear()++ def timeout(self):+ """The ready window ran out. In prepare (the start window): a side that never started loses ("no_show", see+ Service.close_start_window); in a review: a late side loses (or retires)."""+ if self.phase == "prepare":+ self.ready_deadline = None+ if self.close_start_window():+ self.barrier() # the present seats have all started: run after the lead time+ return+ missing = [s for s in self.due() if not self.seats[s].ready]+ sides = []+ for s in missing:+ if self.cfg.side_of(s) not in sides:+ sides.append(self.cfg.side_of(s))+ if len(sides) == 1 or (len(self.active_sides()) > 2 and len(sides) < len(self.active_sides())):+ for side in sides:+ seat = next(s for s in missing if self.cfg.side_of(s) == side)+ if not self.lose(seat, "ready_timeout"):+ return+ self.ready_deadline = time.monotonic() + float(os.environ.get("READY_TIMEOUT_S", "60"))+ self.barrier()+ return+ self.end("incomplete")++ def loop(self):+ try:+ while True:+ with self.cond:+ if self.phase == "over":+ return+ now = time.monotonic()+ if self.phase in ("prepare", "review"):+ if self.resume_at is not None and now >= self.resume_at:+ if self.m.phase().state == UNIT_OVER:+ self.ep.write("resume", k=self.m.k)+ self.m.resume()+ now, epoch = time.monotonic(), time.time() # the run starts when resume() returns+ for st in self.seats.values():+ st.meter.begin_segment(epoch)+ st.ready = False+ self.phase, self.anchor, self.segment_start = "running", (now, self.m.k), now+ self.resume_at = self.ready_deadline = None+ self.ep.write("run", k=self.m.k, started_epoch=epoch)+ self.bc.event("run")+ self.cond.notify_all()+ elif self.ready_deadline and now > self.ready_deadline:+ self.timeout()+ continue+ else:+ self.cond.wait(.01)+ continue+ a, k = self.anchor+ due = a + (self.m.k - k + 1) * self.period+ delay = due - time.monotonic()+ if delay > 0:+ time.sleep(min(delay, .02))+ continue+ with self.cond:+ if self.phase != "running":+ continue+ self.apply_pending()+ events = self.m.step()+ if events: # diagnostics (core 0.2.25): what the step returned+ self.diag("event", k=self.m.k, events=jsonable(events))+ self.bc.frame(force=self.m.phase().state != "playing")+ self.run_steps += 1+ self.lates.append(max(0.0, time.monotonic() - due))+ ph = self.m.phase()+ if ph.state != "playing":+ for s, _e in self.pending:+ self.seats[s].count("dropped")+ self.drop_all("unit_over")+ self.ep.write("unit_over", k=self.m.k, unit=self.m.unit(), reason=ph.reason)+ self.bc.event("unit_over", unit=self.m.unit(), reason=ph.reason, scores=self.m.scores())+ if ph.state == FINISHED:+ self.end("match_over")+ else:+ self.phase = "review"+ self.run_wall += time.monotonic() - self.segment_start+ self.segment_start = None+ self.ready_deadline = time.monotonic() + float(os.environ.get("READY_TIMEOUT_S", "60"))+ if not self.due(): # nobody reviews: go on after the lead time+ self.barrier()+ self.cond.notify_all()+ if self.m.k % 50 == 0 or self.phase != "running":+ self.write_final()+ except Exception as exc: # noqa: BLE001+ self.failure("world", exc)++ def header_extra(self) -> dict:+ """The episode header's timing (core 0.2.23): what the reaction report of a replay needs."""+ return {"timing": {"reaction_delay_steps": spec_mod.reaction_delay(self.decl),+ "effect_delay_steps": int(getattr(self.layer, "delay_steps", 0) or 0)}}++ def reaction_final(self) -> dict:+ """final.json `reaction` (core 0.2.23, report only: no effect on validity or grading): per seat, how many acts+ took effect within the declared reaction delay D, and the distribution of the actual delay, from the episode's+ command rows (core/episode.reaction_report); `replayed`: the fresh-process replay's report is the same."""+ with self.ep.lock:+ rows = list(self.ep.commands)+ out = reaction_report(rows, self.cfg.seats, self.react, self.delay)+ rr = (self.replay or {}).get("reaction")+ out["replayed"] = None if not self.replay else bool(rr and rr.get("by_seat") == out["by_seat"])+ return out++ def extra_final(self):+ L = self.lates+ return {"reaction": self.reaction_final(), "slowdown": self.slowdown, "timing_policy": "report_only", "timing_invalid": False,+ "sim_lag": {"late_max_s": max(L, default=0), "late_p99_s": float(np.percentile(L, 99)) if L else 0,+ "run_steps": self.run_steps, "run_sim_s": self.run_steps * self.m.dt,+ "run_wall_s": self.run_wall, "period_s": self.period}}++ def collect(self):+ """Every player session has ended. Before the start every side that has not started loses ("no_show", a valid+ loss; Service.no_show_at_collect, core 0.2.7); a single side whose match has started loses ("abandoned", a+ valid loss; Service.abandon_single, core 0.2.6). Otherwise (two or more sides after the start, or no side+ started) the match ends "collected": unfinished, no winner, not a valid trial."""+ with self.cond:+ if self.no_show_at_collect():+ self.ready_deadline = None+ elif not self.abandon_single():+ self.end("collected")+++__all__ = ["RealtimeService", "Refused"]diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/rng.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/rng.pynew file mode 100644index 0000000000..37efff2c79--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/rng.py@@ -0,0 +1,15 @@+"""Random numbers by name (docs/framework_zh.md §5, rule 4 of the sport rules): every random draw of a sport comes from+a stream named by the sport, seeded from the match seed and the name only, so a stream never depends on how many+draws another stream made, and a replay in a fresh process draws the same numbers."""+from __future__ import annotations++import hashlib++import numpy as np+++def stream(cfg_or_seed, name: str) -> np.random.Generator:+ seed = getattr(cfg_or_seed, "seed", cfg_or_seed)+ sport = getattr(cfg_or_seed, "sport", "")+ h = hashlib.sha256(f"{sport}|{int(seed)}|{name}".encode()).digest()+ return np.random.Generator(np.random.PCG64(int.from_bytes(h[:16], "little")))diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/score.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/score.pynew file mode 100644index 0000000000..d37235fa44--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/score.py@@ -0,0 +1,89 @@+"""The continuous score (core 0.2.14, docs/framework_zh.md §4.3): one number per side, LARGER IS BETTER, that the+leaderboards and statistics read next to the win (final.json `continuous`, reward.json `<seat>_continuous_score` and,+for a single-side format, `continuous_score`). The sport defines it in sport.toml [score]:++ name an id ([a-z][a-z0-9_]*), e.g. point_share, mean_per_throw, goal_difference+ text the definition in one sentence (README, site)+ from share own score / the sum of every side's score in Match.scores() (0.5 when nothing was scored)+ margin own score - the best other score in Match.scores()+ own own score (a single format scored against a line)+ hook Match.continuous_score() -> {side: number} (anything else, e.g. a mean per throw)+ forfeit the value of a side that forfeited (no_show, abandoned, clock, review time) or retired: a side cannot+ keep a good number by walking away; it should be the worst value the definition allows+ range optional [lo, hi]: the values the definition can take (core.testkit checks them)++A sport without [score] has no continuous score (the fields are absent); tools/check warns, and fails once the sport+has registered hidden official seeds (it is frozen for a season)."""+from __future__ import annotations++import math+import re++KINDS = ("share", "margin", "own", "hook")+NAME = re.compile(r"^[a-z][a-z0-9_]*$")+++def declaration(decl: dict) -> dict | None:+ return decl.get("score") or None+++def problems(decl: dict, has_hook: bool) -> list[str]:+ """What is wrong with sport.toml [score] (empty: fine, or not declared)."""+ d = declaration(decl)+ if d is None:+ return []+ out = []+ if not NAME.match(str(d.get("name", ""))):+ out.append("name: an id [a-z][a-z0-9_]*")+ if not str(d.get("text", "")).strip():+ out.append("text: the definition in one sentence")+ if d.get("from") not in KINDS:+ out.append(f"from: one of {', '.join(KINDS)}")+ if (d.get("from") == "hook") != has_hook:+ out.append("from = \"hook\" iff the plugin defines continuous_score()")+ if not isinstance(d.get("forfeit"), (int, float)) or isinstance(d.get("forfeit"), bool):+ out.append("forfeit: a number (the value of a side that forfeits)")+ r = d.get("range")+ if r is not None and not (isinstance(r, list) and len(r) == 2 and all(isinstance(x, (int, float)) for x in r)+ and r[0] < r[1]):+ out.append("range: [lo, hi] with lo < hi")+ if d.get("from") in ("share", "margin") and not any(+ len(set((f.get("sides") or {s: s for s in f.get("seats", [])}).values())) > 1 or f.get("opponent")+ for f in (decl.get("formats") or {}).values()):+ out.append(f"from = \"{d.get('from')}\" needs a format with an opponent")+ return out+++def compute(match, decl: dict, sides, forfeited=()) -> dict | None:+ """{"name", "from", "higher_is_better": True, "by_side": {side: float}, "forfeited": [sides]} for the player+ sides at the end of a match, None without a declaration. Raises on a non-finite value (a sport bug)."""+ d = declaration(decl)+ if d is None:+ return None+ kind = d["from"]+ if kind == "hook":+ raw = match.continuous_score()+ if raw is None:+ raise RuntimeError("[score] from = \"hook\" but Match.continuous_score() returned None")+ vals = {s: raw.get(s) for s in sides}+ else:+ sc = {str(k): float(v) for k, v in (match.scores() or {}).items()}+ vals = {}+ for s in sides:+ own = sc.get(s, 0.0)+ others = [v for k, v in sc.items() if k != s]+ if kind == "share":+ tot = own + sum(others)+ vals[s] = own / tot if tot > 0 else 0.5+ elif kind == "margin":+ vals[s] = own - max(others) if others else own+ else:+ vals[s] = own+ by = {}+ for s in sides:+ v = float(d["forfeit"]) if s in forfeited else vals.get(s)+ if v is None or isinstance(v, bool) or not math.isfinite(float(v)):+ raise RuntimeError(f"continuous score of side {s}: {v!r} is not a finite number")+ by[s] = round(float(v), 6)+ return {"name": d["name"], "from": kind, "higher_is_better": True, "by_side": by,+ "forfeited": [s for s in sides if s in forfeited]}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/seats.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/seats.pynew file mode 100644index 0000000000..94cb549406--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/seats.py@@ -0,0 +1,87 @@+"""Seats: metering (the unchanged think_clock.py / api_errors.py), per-seat counters, one-request-in-flight locks (per+entity for acts), the chess clock of the turn protocol, and the validity fields every final.json carries."""+from __future__ import annotations++import os+import threading+import time+from pathlib import Path++from .metering.api_errors import seat_api_errors+from .metering.think_clock import ThinkClock, read_usage++UNMETERED_MODES = ("oracle", "unmetered") # player modes whose model the sim does not meter+++class Seat:+ def __init__(self, name: str, data: Path, clock_s: float | None = None, side: str | None = None):+ self.name, self.side = name, side or name+ self.mode = os.environ.get(f"PLAYER_MODE_{name}", os.environ.get("RCB_PLAYER_MODE", "model"))+ if self.mode not in UNMETERED_MODES + ("model",):+ raise ValueError(f"PLAYER_MODE_{name} must be model, oracle or unmetered")+ # "unmetered" (core 0.2.29): the runner meters the seat's model itself (a single-seat task run by a plain+ # Harbor with its native agents, e.g. the export to the upstream benchmark): no metering proxy, so the meter+ # takes the gate's exemption (ThinkClock's oracle rule; think_clock.py stays unchanged) and no meter is+ # required for validity (Service.need_meter); final.json records the mode as it is.+ self.meter = ThinkClock(usage_file=str(Path(data) / f"think_usage_{name}.json"),+ mode="oracle" if self.mode in UNMETERED_MODES else self.mode)+ self.act_locks: dict[str, threading.Lock] = {}+ self.view_lock = threading.Lock()+ self.joined = self.ready = self.retired = False+ self.stats: dict = {}+ self.clock_s, self.used, self.turn_t0, self.turn_busy = clock_s, 0.0, None, 0.0+ self.frozen, self.frozen_at = 0, None # off-lock service in progress (images being drawn): no clock++ def act_lock(self, entity: str = "") -> threading.Lock:+ return self.act_locks.setdefault(entity, threading.Lock())++ def count(self, key: str, n: int = 1):+ self.stats[key] = self.stats.get(key, 0) + n++ def sample(self, key: str, v: float):+ self.stats.setdefault(key, []).append(v)++ # chess clock (turn protocol): runs on this seat's turn only; service time inside the turn does not count+ def clock_used(self, now=None) -> float:+ if self.turn_t0 is None:+ return self.used+ now = now or time.time()+ if self.frozen: # the clock stands still while the service draws this seat's images+ now = max(self.turn_t0, min(now, self.frozen_at))+ return self.used + max(0.0, now - self.turn_t0 - self.turn_busy)++ def freeze(self, now):+ """Service work for this seat continues off the lock (drawing its images, core 0.2.8): stop the clock."""+ if self.frozen == 0:+ self.frozen_at = now+ self.frozen += 1++ def thaw(self, now):+ self.frozen -= 1+ if self.frozen == 0:+ if self.turn_t0 is not None:+ self.turn_busy += max(0.0, now - max(self.frozen_at, self.turn_t0))+ self.frozen_at = None++ def clock_left(self) -> float:+ return (self.clock_s or 0.0) - self.clock_used()++ def start_turn(self, now):+ self.turn_t0, self.turn_busy = now, 0.0++ def stop_turn(self, now):+ if self.turn_t0 is not None:+ self.used = self.clock_used(now)+ self.turn_t0 = None+++def validity_fields(seats: dict[str, Seat], need_meter) -> dict:+ """Metering and model-API validity of every seat (the one rule of api_errors.py)."""+ usage = {s: read_usage(st.meter.usage_file) for s, st in seats.items()}+ meter = {s: bool(need_meter(seats[s]) and (not usage[s].get("epoch") or not usage[s].get("requests")))+ for s in seats}+ apis = {s: seat_api_errors(seats[s].meter.usage_file, usage[s]) for s in seats}+ return {"meter_error": meter, "proxy_error": {s: a["api_failure"] for s, a in apis.items()},+ "transient_api_errors": {s: a["transient_api_errors"] for s, a in apis.items()},+ "unrecovered_api_errors": {s: a["unrecovered_api_errors"] for s, a in apis.items()},+ "player_modes": {s: st.mode for s, st in seats.items()}}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/seeds.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/seeds.pynew file mode 100644index 0000000000..c6a2ae4c83--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/seeds.py@@ -0,0 +1,178 @@+"""Hidden official seeds (core 0.2.14, docs/framework_zh.md §6.4): a sport frozen for a season plays its official+matches on a seed set that only the organisers hold. The repository has its commitments, never the seeds.++ cells the set is partitioned by format x level: one cell per format ("duel") or per format and level of a+ format with levels ("match/L1", "match/L2", ...; cell_of); every cell has its own seeds, none shared+ private set {"schema": PRIVATE, "sport", "created", "cells": {cell: [{"seed": int, "salt": 32 hex}, ...]}}: outside+ git, on the official run host only (tools/seeds.py: $RO_SEEDS_DIR/<sport>.hidden_seeds.json, 0600)+ commitments one per seed, in cell order: sha256("ro-hidden-seeds/1|<sport>|<seed>|<salt>"); the salt (128 random+ bits) makes a commitment say nothing about its seed+ registration set_sha256 (the sport and every cell's commitments) and the count per cell: sport.toml+ [official.hidden_seeds] sha256, counts; the commitments are public (sports/<sport>/seed_commitments.json)++At run time the runner hands one seed, its salt and its index to the sim service only (RO_SEED, RO_SEED_SALT,+RO_SEED_INDEX); the players' containers never see them. In such a match the core writes the seed nowhere: the+episode header, final.json, replay_check.json and the broadcast log carry seed -1 and the commitment only+(final.json seed_proof), the sport's own fields and the players' observations and /spec are scrubbed (scrub()), and+the fresh-process replay takes the seed from the same environment and checks it against the commitment. The salt is+never written either (with it, a six-digit seed would follow from its commitment by brute force). The verifier finds+the commitment in the cell of the match's format and level (index()): hidden_seed, hidden_seed_index. The private set+plus the index is the only record of the seed; after the season the set may be published and anyone can recompute+set_sha256 from it.++Standard library only: the generator copies this file next to the verifier (tests/seeds.py)."""+from __future__ import annotations++import hashlib+import re+import secrets++SCHEMA = "ro-hidden-seeds/1" # the commitment of one seed+SET_SCHEMA = "ro-hidden-seeds/2" # the registered digest of a partitioned set+PRIVATE = "ro-hidden-seeds-private/2"+PUBLIC = "ro-hidden-seeds-public/2"+SEED_RANGE = (100000, 999999) # six digits: an int32 for any simulator+HIDDEN = -1 # the seed as written in the records of a hidden-seed match+HEX = re.compile(r"^[0-9a-f]{64}$")+CELL = re.compile(r"^[a-z0-9][a-z0-9_-]*(/L\d+)?$") # a format name of sport.toml, "/L<level>"+KEEP = {"step", "k", "steps", "t_sim"}+COMMITMENTS = "seed_commitments.json" # sports/<sport>/<this>: the public part (public())+++def commitment(sport: str, seed: int, salt: str) -> str:+ return hashlib.sha256(f"{SCHEMA}|{sport}|{int(seed)}|{salt}".encode()).hexdigest()+++def set_sha256(sport: str, cells: dict) -> str:+ """The registered digest of a seed set: its sport and every cell's commitments, cells in sorted order."""+ text = SET_SCHEMA + "\n" + sport + "\n"+ for c in sorted(cells):+ text += f"[{c}]\n" + "".join(x + "\n" for x in cells[c])+ return hashlib.sha256(text.encode()).hexdigest()+++def cell_of(fmt: str, level, cells) -> str | None:+ """The cell of a match: "<format>/L<level>" when the set has it, else "<format>" when it has that, else None."""+ if level is not None and f"{fmt}/L{int(level)}" in cells:+ return f"{fmt}/L{int(level)}"+ return fmt if fmt in cells else None+++def new(sport: str, counts: dict, avoid=(), created: str = "") -> dict:+ """A fresh private set: counts = {cell: n}; every seed distinct across cells and none of `avoid`."""+ if not counts or any(int(n) < 1 or not CELL.match(c) for c, n in counts.items()):+ raise ValueError("cells: {\"<format>\" or \"<format>/L<level>\": count >= 1}")+ lo, hi = SEED_RANGE+ used, cells = {int(x) for x in avoid}, {}+ for c in sorted(counts):+ cells[c] = []+ while len(cells[c]) < int(counts[c]):+ s = lo + secrets.randbelow(hi - lo + 1)+ if s not in used:+ used.add(s)+ cells[c].append({"seed": s, "salt": secrets.token_hex(16)})+ return {"schema": PRIVATE, "sport": sport, "created": created, "cells": cells}+++def from_seeds(sport: str, cells: dict, created: str = "") -> dict:+ """A private set of given seeds ({cell: [int, ...]}) with fresh salts."""+ out = {c: [{"seed": int(s), "salt": secrets.token_hex(16)} for s in v] for c, v in cells.items()}+ p = {"schema": PRIVATE, "sport": sport, "created": created, "cells": out}+ check_private(p)+ return p+++def check_private(p: dict) -> None:+ if p.get("schema") != PRIVATE or not p.get("sport") or not p.get("cells"):+ raise ValueError(f"not a private seed set (schema {PRIVATE}, sport, cells)")+ seen = set()+ for c, entries in p["cells"].items():+ if not CELL.match(c) or not entries:+ raise ValueError(f"bad cell {c!r}")+ for e in entries:+ if not isinstance(e.get("seed"), int) or not re.fullmatch(r"[0-9a-f]{32}", str(e.get("salt", ""))):+ raise ValueError(f"bad entry in {c}: seed int, salt 32 hex")+ if e["seed"] in seen:+ raise ValueError(f"seed {e['seed']} twice (cells never share a seed)")+ seen.add(e["seed"])+++def public(p: dict) -> dict:+ """The public part of a private set: what goes into the repository."""+ check_private(p)+ cells = {c: [commitment(p["sport"], e["seed"], e["salt"]) for e in v] for c, v in sorted(p["cells"].items())}+ return {"schema": PUBLIC, "sport": p["sport"], "counts": {c: len(v) for c, v in cells.items()},+ "sha256": set_sha256(p["sport"], cells), "cells": cells}+++def registered(sport: str, reg: dict) -> dict:+ """The cells of a registration {sha256, counts, cells}, after checking that they are the registered ones (their+ digest and counts); ValueError otherwise."""+ cells = reg.get("cells") or {}+ counts = reg.get("counts") or {}+ if set(cells) != set(counts) or not cells:+ raise ValueError("hidden seeds: the cells of the commitments and of the counts differ")+ flat = [x for v in cells.values() for x in v]+ if not all(isinstance(x, str) and HEX.match(x) for x in flat) or len(set(flat)) != len(flat):+ raise ValueError("hidden seeds: commitments must be distinct sha256 hex digests")+ for c, v in cells.items():+ if len(v) != int(counts[c]):+ raise ValueError(f"hidden seeds: cell {c} has {len(v)} commitments, count {counts[c]}")+ if set_sha256(sport, cells) != reg.get("sha256"):+ raise ValueError("hidden seeds: the commitments do not hash to the registered sha256")+ return cells+++def index(sport: str, fmt: str, level, commit: str | None, reg: dict) -> int | None:+ """The position of a match's commitment in the cell of its format and level, None if it is not there (or the+ registration is inconsistent: then nothing is a member)."""+ if not commit:+ return None+ try:+ cells = registered(sport, reg)+ except (ValueError, TypeError):+ return None+ cell = cell_of(fmt, level, cells)+ if cell is None or commit not in cells[cell]:+ return None+ return cells[cell].index(commit)+++def resolve(p: dict, cell: str, i: int, reg: dict | None = None) -> tuple[int, str]:+ """(seed, salt) of entry i of a cell of a private set; with a registration, also checks that the set is the+ registered one."""+ check_private(p)+ if cell not in p["cells"]:+ raise KeyError(f"no cell {cell!r} (cells: {', '.join(sorted(p['cells']))})")+ if not 0 <= i < len(p["cells"][cell]):+ raise IndexError(f"cell {cell} has {len(p['cells'][cell])} seeds (0..{len(p['cells'][cell]) - 1}); asked {i}")+ if reg is not None and public(p)["sha256"] != reg.get("sha256"):+ raise ValueError("this private seed set is not the registered one (sha256 differs)")+ e = p["cells"][cell][i]+ return int(e["seed"]), str(e["salt"])+++def scrub(obj, seed: int, salt: str = ""):+ """A copy of obj (JSON-like) without the seed: values under a key named "seed" or "*_seed" become HIDDEN, and so+ does any integer equal to the seed or any string equal to it or to the salt. For a hidden-seed match."""+ seed = int(seed)++ def go(x, key=""):+ if (key == "seed" or key.endswith("_seed")) and not isinstance(x, (dict, list, tuple)):+ return HIDDEN+ if key in KEEP: # the core's step counters: never the seed, may reach six digits+ return x+ if isinstance(x, dict):+ return {k: go(v, str(k)) for k, v in x.items()}+ if isinstance(x, (list, tuple)):+ return [go(v) for v in x]+ if isinstance(x, bool):+ return x+ if isinstance(x, int) and x == seed:+ return HIDDEN+ if isinstance(x, float) and x == seed:+ return float(HIDDEN)+ if isinstance(x, str) and (x == str(seed) or (salt and x == salt)):+ return str(HIDDEN)+ return x+ return go(obj)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/serve.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/serve.pynew file mode 100644index 0000000000..55d60c8b95--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/serve.py@@ -0,0 +1,54 @@+"""Entry point of a generated task's sim service: python3 -m core.serve (cwd = the directory holding core/).++Environment: RO_PLUGIN (path of the sport's plugin.py), RO_SPORT, RO_FORMAT, RO_SEATS (e.g. "A,B"), RO_SIDES (e.g.+"A=home,B=home,C=away,D=away"; default: every seat its own side), RO_SEED, RO_SEED_SALT+(a hidden official seed's salt, core 0.2.14: recorded in final.json seed_proof for the verifier), RO_FIRST, RO_SLOWDOWN (realtime), RO_LEVEL+(single), RO_PARAMS (JSON), RO_RENDERER (the players' image renderer), RCB_ACTION_LEVEL, RCB_PLAY, RCB_DATA,+SEAT_HOSTS. The runner's own names (DUEL_SEED, FIRST_PLAYER, ...) are mapped onto these by the task's compose file.+"""+from __future__ import annotations++import json+import os+import signal+import threading+from pathlib import Path++from .episode import load_plugin+from .http import make_server+from .realtime import RealtimeService+from .sport import MatchConfig+from .turn import TurnService+++def config_from_env() -> MatchConfig:+ e = os.environ.get+ level, slow = e("RO_LEVEL"), e("RO_SLOWDOWN")+ sides = dict(x.split("=", 1) for x in e("RO_SIDES", "").split(",") if "=" in x) or None+ return MatchConfig(sport=e("RO_SPORT", ""), format=e("RO_FORMAT", "duel"),+ seats=tuple(e("RO_SEATS", "A,B").split(",")), seed=int(e("RO_SEED", "1")),+ first=e("RO_FIRST") or None, slowdown=float(slow) if slow else None,+ level=int(level) if level else None, action_level=e("RCB_ACTION_LEVEL", "high"),+ play=e("RCB_PLAY", "program"), params=json.loads(e("RO_PARAMS", "{}")), sides=sides,+ renderer=e("RO_RENDERER") or None)+++def main():+ plugin = os.path.abspath(os.environ["RO_PLUGIN"])+ sport = load_plugin(plugin)+ cfg = config_from_env()+ if cfg.action_level not in ("high", "low") or cfg.play not in ("program", "direct"):+ raise ValueError("RCB_ACTION_LEVEL must be high or low, RCB_PLAY program or direct")+ data = Path(os.environ.get("RCB_DATA", "/data"))+ svc = (RealtimeService if sport.protocol == "realtime" else TurnService)(sport, plugin, cfg, data)+ hosts = dict(x.split("=", 1) for x in os.environ.get("SEAT_HOSTS", "").split(",") if "=" in x)+ signal.signal(signal.SIGUSR1, lambda *a: threading.Thread(target=svc.collect, daemon=True).start())+ svc.write_final()+ (data / "server.pid").write_text(str(os.getpid()))+ threading.Thread(target=svc.loop, daemon=True).start()+ print(f"{sport.name} {cfg.format} service ready ({svc.protocol_id})", flush=True)+ make_server(svc, cfg.seats, hosts, int(os.environ.get("RCB_PORT", "8000"))).serve_forever()+++if __name__ == "__main__":+ main()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/service.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/service.pynew file mode 100644index 0000000000..3befc74ecc--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/service.py@@ -0,0 +1,527 @@+"""What both protocols share: the match, seats and sides, the episode, worker processes, observations (whitelist,+cameras through the task's renderer, the team channel), the end of a match (fresh-process replay and its comparison)+and final.json (common validity fields + the sport's own fields)."""+from __future__ import annotations++import base64+import json+import os+import subprocess+import sys+import threading+import time+from pathlib import Path++from . import VERSION+from . import score as score_mod+from . import seeds as seeds_mod+from . import spec as spec_mod+from .channel import TeamChannel+from .diaglog import Acts, safe+from .episode import Episode, source_sha+from .observe import CameraWorker, filter_fields, players_scene, reply_job+from .outcome import decide+from .sport import Refused+from .seats import Seat, validity_fields+from .spectator import Broadcast+from .sport import MatchBase+from .workers import ProcessWorker++ROOT = Path(__file__).resolve().parent+FORFEIT_REASONS = ("ready_timeout", "clock", "abandoned", "no_show")+CAMERA_KIND = "camera" # the core's own render worker: the sport's cameras drawn by the task's renderer+# final.json compatibility (the readers of Season 1: live_board, the site extractors, regrade_transient, broadcast):+# every sport field (Match.final_fields(), also kept under "sport_fields") is lifted to the top level unless a core+# field has that name, and "score" is the by-side score unless the sport sets its own. A migrating sport keeps its+# legacy field names in final_fields(); a reader that needs a sport field whose name a core field took (e.g. a+# legacy "scores" table) reads sport_fields first (live_board does).+COMPAT = "v0.1-toplevel-aliases"+++def own_hook(obj, name) -> bool:+ """Does the sport's Match override MatchBase's default of `name`?"""+ f = getattr(type(obj), name, None)+ return f is not None and f is not getattr(MatchBase, name, None)+++def public_spec(sport, cfg, seat, m, layer, decl) -> dict:+ """The sport's part of /spec: the action layer's commands, the camera definitions with their intrinsics, the+ rule constants of sport.toml [spec] and the tiebreak text, plus anything Sport.spec() adds."""+ out = {}+ schema = layer.schema(m, seat) if hasattr(layer, "schema") else {}+ if schema:+ out["actions"] = schema+ cams = m.cameras(seat) if own_hook(m, "cameras") else []+ if cams:+ from renderers.base import CameraDef+ out["cameras"] = [dict(c, **CameraDef.from_dict(c).intrinsics()) for c in cams]+ out.update(decl.get("spec") or {})+ if (decl.get("tiebreaks") or {}).get("text"):+ out["tiebreaks"] = decl["tiebreaks"]["text"]+ f = getattr(sport, "spec", None)+ if f is not None:+ out.update(f(cfg, seat, m))+ return out+++class Service:+ protocol = ""++ def __init__(self, sport, plugin: str, cfg, data: Path, clock_s: float | None = None):+ self.sport, self.plugin, self.cfg, self.data = sport, plugin, cfg, Path(data)+ self.data.mkdir(parents=True, exist_ok=True)+ self.decl = spec_mod.load(plugin)+ self.allowed = spec_mod.whitelist(self.decl)+ self.m = sport.build(cfg)+ self.layer = sport.action_layer(cfg.action_level)+ self.seats = {s: Seat(s, self.data, clock_s, cfg.side_of(s)) for s in cfg.seats}+ self.cond = threading.Condition(threading.RLock())+ self.t0 = time.monotonic()+ self.phase, self.reason, self.forfeiting = "prepare", None, None+ self.retired: list[str] = []+ self.errors, self.reviews, self.replay = [], [], {}+ self.finalizing = self.finalized = False+ self.channel = TeamChannel(cfg, self.decl.get("team_channel"))+ self.columns = int((self.decl.get("observation") or {}).get("columns", 2))+ self.source_sha = source_sha(ROOT, *sport.source_dirs, *self.extra_source_dirs())+ self.versions = {"protocol": self.protocol_id, "core": VERSION, "sport": sport.revision,+ "players": {s: os.environ.get(f"RO_PLAYER_CONFIG_{s}", "") for s in cfg.seats}}+ salt = os.environ.get("RO_SEED_SALT", "") # a hidden official seed (core/seeds.py, core 0.2.14)+ self.hidden = ({"seed": int(cfg.seed), "salt": salt,+ "commitment": seeds_mod.commitment(sport.name, cfg.seed, salt)} if salt else None)+ self.ep = Episode(self.data / "episode.jsonl")+ self.diag = safe(self.ep.write) # diagnostic rows (core/diaglog.py, core 0.2.25): never replayed+ self.acts = Acts(cfg.seats)+ self.ep.write("header", cfg=self.cfg_json(), sport=sport.name, revision=sport.revision, protocol=self.protocol,+ source_sha=self.source_sha, versions=self.versions,+ player_modes={s: st.mode for s, st in self.seats.items()},+ **({"seed_hidden": {"commitment": self.hidden["commitment"]}} if self.hidden else {}),+ **self.header_extra())+ self.workers = {}+ self.cameras = own_hook(self.m, "cameras") and not own_hook(self.m, "camera_job")+ self.renderer_name = cfg.renderer+ self.camera = None # in-process CameraWorker (turn protocol, or no render worker)+ self.render_lock = threading.Lock() # in-process drawing: one at a time (it runs off the world lock)+ self.replies = own_hook(self.m, "reply_views") and self.cameras # reply images (core 0.2.8)+ for kind in getattr(sport, "workers", ()):+ for s in cfg.seats:+ k = CAMERA_KIND if (kind == "render" and self.cameras) else kind+ self.workers[kind, s] = ProcessWorker(plugin, k, s, cfg.to_json())+ self.video_info: dict = {}+ self.bc = Broadcast(sport, cfg, self.m, self.decl, slowdown=cfg.slowdown) # spectators only+ self.bc.clean = self.public++ def cfg_json(self) -> dict:+ """The match configuration as the records show it: a hidden seed is written as -1 (core/seeds.py)."""+ d = self.cfg.to_json()+ if self.hidden:+ d["seed"] = seeds_mod.HIDDEN+ return d++ def public(self, obj):+ """What leaves the sim service (replies, final.json, the broadcast log): without a hidden seed or its salt+ (core/seeds.py scrub; core 0.2.14). Unchanged otherwise."""+ if not self.hidden:+ return obj+ return seeds_mod.scrub(obj, self.hidden["seed"], self.hidden["salt"])++ def extra_source_dirs(self):+ """The renderer code is part of the match only when it draws the players' images."""+ return []++ # ------------------------------------------------------------------ helpers+ def camera_job(self, seat, query=None):+ """Under the lock: the job that draws `seat`'s images, and the metadata for the reply."""+ if not self.cameras:+ return self.m.camera_job(seat)+ cams = self.m.cameras(seat, query)+ if not cams:+ return None, {}+ return {"state": self.m.render_state(), "cams": cams, "columns": self.columns}, {}++ def draw(self, seat, job):+ """Off the lock: render a camera job, an observation or reply images (in the seat's render worker if the+ sport has one, where a second job of the seat queues; in-process jobs are drawn one at a time)."""+ if job is None or self.finalized: # core 0.2.26: after finalization the render workers are closed+ return None+ if ("render", seat) in self.workers:+ try:+ return self.workers["render", seat].call(job, wait=True)+ except (BrokenPipeError, EOFError, ConnectionError, OSError):+ if self.finalized: # closed while this request ran: no images, never an error+ return None+ raise+ with self.render_lock:+ if self.cameras:+ if self.camera is None:+ self.camera = CameraWorker(players_scene(self.sport, self.plugin, self.cfg),+ self.renderer_name)+ t = time.monotonic()+ out = self.camera.draw_job(job)+ out["worker_s"] = time.monotonic() - t+ return out+ return self.sport.worker_call(None, "render", job)++ def reply_job(self, seat, cmd, info):+ """With the lock held, right after Match.apply(seat, cmd) returned `info`: the job that draws the images of+ the action's result for its reply (Match.reply_views, core 0.2.8), or None."""+ if not self.replies:+ return None+ return reply_job(self.m, self.m.reply_views(seat, cmd, info), self.columns)++ def reply_images(self, seat, job) -> dict:+ """Off the lock: draw a reply job -> the reply's `observation` (image_png_b64 + tiles, as /observe)."""+ out = self.draw(seat, job) or {}+ obs = {"of": "the result of this action", "render_wall_s": round(out.get("worker_s", 0.0), 3)}+ if out.get("png"):+ obs["image_png_b64"] = base64.b64encode(out["png"]).decode()+ for k in ("tiles", "note"):+ if out.get(k):+ obs[k] = out[k]+ with self.cond: # information only (not replayed): what the seat was shown+ st = self.seats[seat]+ st.count("reply_images")+ st.sample("reply_render_s", obs["render_wall_s"])+ self.ep.write("reply_images", seat=seat, k=self.m.k, tiles=len(obs.get("tiles") or []),+ png_bytes=len(out.get("png") or b""), render_wall_s=obs["render_wall_s"])+ return obs++ def observation(self, seat, query=None, since=None) -> dict:+ """With the lock held: the sport's whitelisted observation (+ the team channel: the teammates' messages after+ the client's read mark `since`, else the recent ones, and the side's newest seq; reading never consumes)."""+ obs, bad = filter_fields(self.m.observe(seat, query), self.allowed)+ if bad:+ self.errors.append({"where": "observation", "error": f"fields outside the whitelist: {bad}"})+ if self.channel.enabled:+ obs["team_messages"], obs["team_seq"] = self.channel.messages(seat, self.m.k, self.m.dt or 1.0, since)+ self.delivered(seat, obs["team_messages"])+ return obs++ def delivered(self, seat, rows):+ """With the lock held: log the teammates' messages `seat` gets for the first time (team_delivered)."""+ for d in self.channel.deliver(seat, rows, self.m.k):+ self.diag("team_delivered", **d)++ def team_since(self, body):+ """The client's team-channel read mark in a request body (`team_since`), None when absent (400 if invalid)."""+ return self.channel.since_arg((body or {}).get("team_since"))++ def team(self, seat, body):+ """POST /<seat>/team {"since": n}: the teammates' messages after seq n (read-only; never consumes)."""+ with self.cond:+ code, out = self.channel.page(seat, self.m.k, (body or {}).get("since"))+ if code == 200:+ self.delivered(seat, out["messages"])+ return code, out++ def say(self, seat, body):+ with self.cond:+ if self.phase == "over":+ return 409, {"error": "the match is over"}+ code, out = self.channel.say(seat, body.get("text"), self.m.k, self.m.dt or 1.0)+ if code == 200:+ self.ep.write("team", seat=seat, k=self.m.k, seq=out["sent"]["seq"], text=body.get("text"))+ return code, out++ def refused_invalid(self, seat, exc):+ """With the lock held: a malformed action (core.sport.parse_action) -- the player's own error, counted and+ logged (not replayed), never a technical failure."""+ st = self.seats[seat]+ st.count("refused_invalid")+ if "refused" in st.stats:+ st.count("refused")+ self.ep.write("refused_invalid", seat=seat, k=self.m.k, error=str(exc)[:200], cause=exc.cause or None)++ def query_guard(self, seat, query, fn):+ """With the lock held: run fn (it reads the sport's observation / cameras with the player's query). With a+ query, any exception is the player's error (Refused, HTTP 400; the sport refuses what it cannot read);+ without one it is a technical failure as before."""+ if query is None:+ return fn()+ try:+ return fn()+ except Refused:+ raise+ except Exception as exc: # noqa: BLE001+ err = Refused("invalid observation query (see /spec)")+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"+ self.ep.write("refused_query", seat=seat, k=self.m.k, cause=err.cause)+ raise err from exc++ def failure(self, where, exc):+ """A request's technical failure: an error of the trial (not valid) and the end of the match. After the match+ is finalized (core 0.2.26) the trial is decided: a late request's failure is only logged, never an error (a+ player that observes after the end once voided a finished, replayed match)."""+ if self.finalized:+ print(f"after finalization, {where}: {type(exc).__name__}: {str(exc)[:200]}", file=sys.stderr, flush=True)+ return+ with self.cond:+ self.errors.append({"where": where, "error": str(exc)[:300]})+ self.ep.write("error", where=where, error=str(exc)[:300])+ self.end("technical_error")++ def forfeit(self, seat, why):+ """With the lock held: a core decision, logged for the replay (and recorded in the world if it wants)."""+ self.forfeiting = seat+ self.ep.write("forfeit", k=self.m.k, seat=seat, why=why)+ self.m.forfeit(seat, why)++ def active_sides(self):+ return [s for s in self.cfg.side_list() if s not in self.retired]++ def lose(self, seat, why) -> bool:+ """With the lock held: `seat` loses (review time, clock, abandonment). With more than two sides the sport may+ let the match go on without that side (Match.retire); then True, else the match ends."""+ side = self.cfg.side_of(seat)+ if len(self.active_sides()) > 2 and self.m.retire(side, why):+ self.retired.append(side)+ for s in self.cfg.seats_of(side):+ self.seats[s].retired = True+ self.ep.write("retire", k=self.m.k, seat=seat, side=side, why=why)+ self.cond.notify_all()+ return True+ self.end(why, seat)+ return False++ def start_window(self) -> float:+ return float(os.environ.get("START_TIMEOUT_S", "1800"))++ def start_rule(self) -> dict:+ """The start window as /spec states it (both protocols)."""+ if len(self.cfg.side_list()) == 1:+ return {"window_s": self.start_window(),+ "rule": "the window opens when the match service starts; if you have not started when it closes, "+ "or your session ends before you start, you lose the match (no_show)"}+ return {"window_s": self.start_window(),+ "rule": "the match begins when every seat has started; the window opens with the first start; a side "+ "that has not started when it closes, or when every player session has ended, loses the match "+ "(no_show); if no side starts, the match does not count"}++ def absent_sides(self) -> list:+ """With the lock held: the sides (not retired) of which some seat has not started, in seat order."""+ absent = []+ for s in self.cfg.seats:+ side = self.cfg.side_of(s)+ if not self.seats[s].joined and side not in self.retired and side not in absent:+ absent.append(side)+ return absent++ def close_start_window(self, at="start_timeout") -> bool:+ """With the lock held, when the start window ran out in prepare (core rule 5, docs/framework_zh.md §9; core+ 0.2.2), or at the collect before the start (Service.no_show_at_collect, core 0.2.7; `at` names the logged+ row). A side is absent if any of its seats has not started. With two or more sides and at least one side+ present, every absent side loses ("no_show", a valid forfeit): with two sides the present side wins; with more,+ an absent side retires if the sport lets the others play on (Match.retire), else the match ends there. If no+ side is present the match is incomplete (a technical failure, no winner). A single-side format (whose window+ opens when the service starts) is a valid loss ("no_show", success 0). True = the match goes on with the+ present sides, who have all started."""+ absent = self.absent_sides()+ present = [x for x in self.active_sides() if x not in absent]+ self.ep.write(at, started={s: st.joined for s, st in self.seats.items()}, absent=absent)+ if not absent:+ return True+ if len(self.cfg.side_list()) == 1: # a single player (or team) who never started: a valid loss+ self.lose(next(s for s in self.cfg.seats if not self.seats[s].joined), "no_show")+ return False+ if not present:+ self.end("incomplete")+ return False+ for side in absent:+ seat = next(s for s in self.cfg.seats_of(side) if not self.seats[s].joined)+ if not self.lose(seat, "no_show"):+ return False+ return True++ def no_show_at_collect(self) -> bool:+ """With the lock held, at the collect (every player session has ended) before the match has started: the+ session end is a no-show, decided at once instead of when the start window closes (core rule 5,+ docs/framework_zh.md §9; core 0.2.7). Every side that has not started loses ("no_show", a valid forfeit;+ Service.close_start_window): a single side (alone or against a scripted opponent) has a valid loss (success 0);+ with two sides the present side wins; with more, the absent sides retire or the match ends as at the window.+ If no side has started (with two or more sides) nothing is decided here: the match does not count, as before+ (the caller ends it unfinished). True = the match ended; False = not before the start, no side present, or+ present sides would play on (more than two sides; the caller ends the match unfinished)."""+ if self.phase != "prepare" or self.in_play():+ return False+ if len(self.cfg.side_list()) > 1 and not [x for x in self.active_sides() if x not in self.absent_sides()]:+ return False+ return not self.close_start_window("collect_before_start")++ def in_play(self) -> bool:+ """With the lock held: the match has started (play has begun, or every seat has started and play is about to+ begin) and is not over."""+ if self.phase == "prepare":+ return all(st.joined for st in self.seats.values())+ return self.phase != "over"++ def abandon_single(self) -> bool:+ """With the lock held, at the collect (the verifier collects once every player session has ended): a single+ side (alone or against a scripted opponent) whose match has started and is not over loses, "abandoned", a+ valid loss (success 0), in both protocols (core rule 6, docs/framework_zh.md §9; core 0.2.6). Ending the+ session early (the player thinks it is done, gives up, hits the agent time limit or runs out of context) is the+ player's own problem; API and infrastructure failures are Harbor agent errors, rerun, not handled here. Before+ the start the session end is a no-show (Service.no_show_at_collect, core rule 5, core 0.2.7). True = the side+ lost."""+ if len(self.cfg.side_list()) != 1 or not self.in_play():+ return False+ self.lose(self.cfg.seats[0], "abandoned")+ return True++ def end(self, reason, forfeiting=None):+ with self.cond:+ if self.finalizing:+ return+ if forfeiting is not None:+ self.forfeit(forfeiting, reason)+ self.on_end()+ self.phase, self.reason, self.finalizing = "over", reason, True+ self.ep.write("end", k=self.m.k, reason=reason)+ self.bc.frame(force=True)+ self.bc.event("end", reason=reason)+ self.cond.notify_all()+ threading.Thread(target=self.finalize, daemon=True).start()++ def on_end(self):+ pass++ def finalize(self):+ try:+ subprocess.run([sys.executable, "-m", "core.episode", self.plugin, str(self.data)], check=True,+ timeout=float(os.environ.get("RO_REPLAY_TIMEOUT_S", "600")), cwd=ROOT.parent,+ stdout=subprocess.DEVNULL)+ self.replay = json.loads((self.data / "replay_check.json").read_text())+ except Exception as exc: # noqa: BLE001+ self.errors.append({"where": "replay", "error": str(exc)[:300]})+ with self.cond:+ self.finalized = True+ self.write_final()+ self.cond.notify_all()+ for w in self.workers.values():+ busy = w.lock.acquire(timeout=60) # a reply image may still be drawn after the last action+ w.close()+ if busy:+ w.lock.release()+ if os.environ.get("RCB_RENDER_VIDEO", "0") == "1": # after graded-ready: spectators only, never an error+ try:+ subprocess.run([sys.executable, "-m", "core.spectator", self.plugin, str(self.data)], check=True,+ timeout=float(os.environ.get("RCB_VIDEO_TIMEOUT_S", "300")), cwd=ROOT.parent,+ stdout=subprocess.DEVNULL)+ self.video_info = json.loads((self.data / "video.json").read_text())+ except Exception as exc: # noqa: BLE001+ self.video_info = {"video": False, "why": str(exc)[:200]}+ with self.cond:+ self.write_final()++ def outcome(self):+ return decide(self.m, self.forfeiting, self.reason, self.cfg.side_list(), self.cfg.side_of, self.retired)++ def continuous(self) -> dict | None:+ """With the lock held: the continuous score of every side (sport.toml [score], core/score.py; core 0.2.14). A+ side that forfeited or retired gets the declared forfeit value. A sport error here is a technical failure.+ None before the match is over (final.json is also written at the start and while it runs)."""+ if self.phase != "over":+ return None+ gone = list(self.retired)+ if self.forfeiting is not None and self.reason in FORFEIT_REASONS:+ gone.append(self.cfg.side_of(self.forfeiting))+ try:+ return score_mod.compute(self.m, self.decl, self.cfg.side_list(), gone)+ except Exception as exc: # noqa: BLE001+ if not any(e.get("where") == "continuous_score" for e in self.errors):+ self.errors.append({"where": "continuous_score", "error": str(exc)[:300]})+ return None++ def seed_proof(self) -> dict | None:+ """A hidden official seed's record (core/seeds.py; core 0.2.14): the commitment of the seed and the salt the+ runner handed over (RO_SEED, RO_SEED_SALT: sim service only), and the index the runner names (RO_SEED_INDEX,+ information only). Neither the seed nor the salt is written; the verifier finds the commitment in the+ registered cell of the match's format and level."""+ if not self.hidden:+ return None+ idx = os.environ.get("RO_SEED_INDEX", "")+ return {"commitment": self.hidden["commitment"], "index": int(idx) if idx.lstrip("-").isdigit() else None}++ def write_final(self):+ with self.cond:+ out = self.outcome()+ sha, cmds = self.m.state_digest(), self.ep.commands_sha()+ r = self.replay+ replay_ok = bool(r and r.get("state_sha") == sha and r.get("scores") == self.m.scores()+ and r.get("winner") == out.winner and r.get("commands_sha") == cmds+ and r.get("source_sha") == self.source_sha and r.get("k") == self.m.k)+ v = validity_fields(self.seats, self.need_meter)+ single = len(self.cfg.side_list()) == 1+ complete = self.reason == "match_over" or (self.reason in FORFEIT_REASONS and+ (out.winner is not None or single))+ valid = bool(self.finalized and complete and replay_ok and not self.errors+ and not any(v["meter_error"].values()) and not any(v["proxy_error"].values()))+ cont = self.continuous()+ valid = valid and not self.errors+ sport = self.m.final_fields()+ seats = {s: dict(st.stats) for s, st in self.seats.items()}+ for s, extra in (sport.pop("seats", None) or {}).items():+ seats.setdefault(s, {}).update(extra)+ final = {"sport": self.sport.name, "protocol": self.protocol, "revision": self.sport.revision,+ "versions": self.versions, "source_sha": self.source_sha, "cfg": self.cfg_json(),+ "seed": self.cfg_json()["seed"], "first": self.cfg.first, "action_level": self.cfg.action_level,+ "play": self.cfg.play, "format": self.cfg.format,+ "sides": {s: self.cfg.side_of(s) for s in self.cfg.seats}, "phase": self.phase,+ "reason": self.reason, "forfeiting": self.forfeiting, "retired": list(self.retired),+ "scores": self.m.scores(), "match_winner": out.winner, "decided_by": out.decided_by,+ "ranking": out.ranking, "solo": out.solo,+ "winner": out.winner if valid else None, "state_sha": sha, "commands_sha": cmds,+ "steps": self.m.k, "deterministic": replay_ok, "replay_scores": r.get("scores"),+ "finalized": self.finalized, "graded_ready": self.finalized, "valid_trial": valid,+ "technical_failure": not valid, "errors": self.errors, "seats": seats,+ "joined": {s: st.joined for s, st in self.seats.items()}, "reviews": self.reviews,+ "renderer": self.renderer_used(), "team_messages": len(self.channel.log),+ "video": bool(self.video_info.get("video")), "video_info": self.video_info, "elapsed_s": round(time.monotonic() - self.t0, 1), **v, **self.extra_final(),+ "continuous": cont, "seed_proof": self.seed_proof(),+ "sport_fields": sport}+ compat = {k: v for k, v in sport.items() if k not in final} # see COMPAT below+ if "score" not in final and "score" not in compat:+ compat["score"] = final["scores"]+ final.update(compat)+ final["compat"] = {"schema": COMPAT, "lifted": sorted(compat)}+ tmp = self.data / "final.json.tmp"+ if self.hidden: # the sport's fields (a sport may record its seed): scrubbed+ for k in {"sport_fields", "seats", "video_info", "errors", *compat}:+ if k in final:+ final[k] = self.public(final[k])+ tmp.write_text(json.dumps(final, default=float))+ tmp.replace(self.data / "final.json")++ def renderer_used(self):+ if not self.cameras:+ return "sport" # the sport draws its own images (a stage-0 wrapper)+ import renderers+ return self.renderer_name or renderers.DEFAULT++ def need_meter(self, seat) -> bool:+ return seat.mode == "model" and seat.joined++ def extra_final(self) -> dict:+ return {}++ def header_extra(self) -> dict:+ """Protocol-specific fields of the episode header (realtime: its timing, core 0.2.23)."""+ return {}++ def spec(self, seat, body=None):+ out = {"seat": seat, "side": self.cfg.side_of(seat), "protocol": self.protocol_id,+ "revision": self.sport.revision, "versions": self.versions, "action_level": self.cfg.action_level,+ "play": self.cfg.play, "format": self.cfg.format, **self.spec_core(),+ **public_spec(self.sport, self.cfg, seat, self.m, self.layer, self.decl)}+ if self.channel.enabled:+ out["team_channel"] = {"say": "POST /<seat>/say {'text': ...}", "max_bytes": self.channel.max_bytes,+ "min_interval_s": self.channel.min_interval_s,+ "max_messages": self.channel.max_messages,+ "read": ("observe / status show `team_messages` (from, seq, k, text) and `team_seq` "+ "(the newest seq); reading never consumes: send team_since = the "+ "largest seq you have (observe / wait body, status ?team_since=N) to get "+ "only newer ones, else you get the recent ones (the last "+ f"{self.channel.recent_s:g} game seconds, at most "+ f"{self.channel.recent_max}); POST /<seat>/team {{'since': n}} pages "+ "through the log"),+ "teammates": [s for s in self.cfg.seats_of(self.cfg.side_of(seat)) if s != seat]}+ return 200, outdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/spec.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/spec.pynew file mode 100644index 0000000000..a93e3fdcf4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/spec.py@@ -0,0 +1,32 @@+"""The sport's declarations (sport.toml next to its plugin.py, docs/framework_zh.md §4.2): data, read by the core+(observation whitelist, team channel, success line, timing), the generator, the checks and the documentation."""+from __future__ import annotations++import os+import tomllib+from pathlib import Path+++def load(plugin_path: str | os.PathLike) -> dict:+ p = Path(plugin_path)+ p = p / "sport.toml" if p.is_dir() else p.with_name("sport.toml")+ if not p.exists():+ return {}+ return tomllib.loads(p.read_text())+++def whitelist(decl: dict) -> set[str] | None:+ fields = (decl.get("observation") or {}).get("fields")+ return set(fields) if fields is not None else None+++def reaction_delay(decl: dict) -> int:+ """sport.toml [timing] reaction_delay_steps (core 0.2.18): the sport's declared reaction delay D in control+ steps, the same for every seat. In real time an act takes effect at step max(the next control-step boundary, s + D),+ where s is the step of the latest world state the service sent to the seat (any reply's `now`); the act is+ lowered at that step. The screening harness (tools/screen/play.py) plays with the same D. Not declared: 0, every+ act takes effect at the next control-step boundary (the rule before 0.2.18)."""+ v = (decl.get("timing") or {}).get("reaction_delay_steps", 0)+ if isinstance(v, bool) or not isinstance(v, int) or v < 0:+ raise ValueError(f"[timing] reaction_delay_steps must be an integer >= 0 (control steps), not {v!r}")+ return vdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/spectator.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/spectator.pynew file mode 100644index 0000000000..804621c1de--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/spectator.py@@ -0,0 +1,179 @@+"""What spectators get (docs/framework_zh.md §3.1, §4.3): the broadcast log and the replay video. Neither is ever read+back by the match, the replay or the grader; any failure here only switches the spectator output off.++Broadcast log (/data/broadcast.jsonl, RCB_BROADCAST=1): the unchanged legacy writer (broadcast_log.py, copied next+to core/ as spectator/broadcast_log.py by the generator) with the same lines as every legacy sport: a header, a frame+{"k", "q": qpos, ...extra} every `every` control steps (realtime) or after every action (turn), and the events run,+action, unit_over, end. A frame is Match.broadcast_frame() ({"q": [...], ...extra}) when the sport defines it, else+the qpos of Match.render_state().++Replay video (/data/replay.mp4, RCB_RENDER_VIDEO=1): after the match is graded-ready, a fresh process replays the+episode and draws the spectator camera with the spectator renderer (RO_VIDEO_RENDERER, default the players'+renderer; any renderer of renderers/ can re-render later from the episode). The camera: sport.toml+[broadcast] camera (a camera definition), else the first camera of the first seat. Frames of a non-default+renderer carry its label. python -m core.video is this module's video part: python -m core.spectator PLUGIN DIR.+The video is written as replay.part.mp4 and renamed when complete (core 0.2.13): replay.mp4 exists only after a+finished render, which is what the grader's video_rendered reads.++The spectator scene (core 0.2.4): the sport's presentation scene when it declares one (sports/<sport>/presentation/,+renderers/presentation: the match scene with fine visual meshes on the same bodies, same kinematics) and its assets+are present, else the match scene; RO_VIDEO_SCENE=match forces the match scene. A presentation scene is in the+simulator directory only when the sport declares it for its players' images (core 0.2.9: then a task's video shows+the players' scene, untagged: it is the competition picture); otherwise a task's video is the match scene and+re-renders from a checkout get the presentation. Every frame drawn from a spectators-only presentation scene carries+the presentation tag (renderer rule 6), whatever the renderer.+The players' images never use it (observe.CameraWorker).++A sport's own spectator scene (core 0.2.28): when the sport defines Sport.spectator_scene(cfg), the video draws that+scene (no presentation dressing) with Match.spectator_state() (default render_state()) - e.g. bodies the players'+scene leaves out (e.g. the vehicles, as mocap bodies, over a course scene without them). The players'+images and the replayed match never use either.+"""+from __future__ import annotations++import importlib.util+import json+import os+import sys+from pathlib import Path++from . import spec as spec_mod+from .sport import FINISHED, MatchBase, MatchConfig++ROOT = Path(__file__).resolve().parent+WRITER = ROOT.parent / "spectator" / "broadcast_log.py"+++def frame_of(m) -> dict | None:+ """The spectator frame of a match now: Match.broadcast_frame() if the sport defines it, else render_state's qpos."""+ if getattr(type(m), "broadcast_frame", None) is not MatchBase.broadcast_frame:+ return m.broadcast_frame()+ st = m.render_state() or {}+ return {"q": list(st["qpos"])} if "qpos" in st else None+++class Broadcast:+ def __init__(self, sport, cfg, m, decl, **header):+ self.m, self.log = m, None+ self.clean = lambda x: x # the service's scrub of a hidden seed (core/seeds.py)+ if os.environ.get("RCB_BROADCAST", "1") != "1" or not WRITER.exists():+ return+ try:+ spec = importlib.util.spec_from_file_location("ro_broadcast_log", WRITER)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ every = int((decl.get("broadcast") or {}).get("every", 2 if sport.protocol == "realtime" else 1))+ self.log = mod.BroadcastLog(every=every, path=os.path.join(os.environ.get("RCB_DATA", "/data"),+ "broadcast.jsonl"),+ sport=sport.name, mode=cfg.format, protocol=sport.protocol, dt=m.dt,+ seats=list(cfg.seats), sides={s: cfg.side_of(s) for s in cfg.seats}, **header)+ except Exception: # noqa: BLE001 (spectator output only)+ self.log = None++ def frame(self, force: bool = False):+ if self.log is None:+ return+ try:+ fr = frame_of(self.m)+ if fr is not None:+ fr = self.clean(dict(fr))+ self.log.frame(self.m.k, fr.pop("q", ()), force=force, **fr)+ except Exception: # noqa: BLE001+ self.log = None++ def event(self, ev: str, **fields):+ if self.log is not None:+ self.log.event(ev, self.m.k, **self.clean(fields))+++# ------------------------------------------------------------------------------------------------ the replay video+def video_camera(sport, cfg, m, decl) -> dict | None:+ cam = (decl.get("broadcast") or {}).get("camera")+ if cam:+ return dict(cam)+ cams = m.cameras(cfg.seats[0], None) if hasattr(m, "cameras") else []+ return dict(cams[0]) if cams else None+++def spectator_scene(sport, plugin: str, cfg):+ """(scene, what): the scene spectators see, what = "match" | "presentation" | "match (presentation unavailable:+ ...)". Spectator output only: a failure here falls back to the match scene."""+ if hasattr(sport, "spectator_scene") and os.environ.get("RO_VIDEO_SCENE", "presentation") != "match":+ try:+ return sport.spectator_scene(cfg), "spectator"+ except Exception as exc: # noqa: BLE001 (spectator output only: the match scene)+ return sport.scene(cfg), f"match (spectator scene unavailable: {exc})"+ base = sport.scene(cfg)+ if os.environ.get("RO_VIDEO_SCENE", "presentation") == "match":+ return base, "match"+ if not (Path(plugin).resolve().parent / "presentation" / "presentation.toml").is_file():+ return base, "match" # no presentation (in a task: unless declared for the players)+ try:+ from renderers import presentation+ scene = presentation.for_plugin(plugin, base)+ except Exception as exc: # noqa: BLE001 (missing assets, no tomllib, ...: the match scene)+ return base, f"match (presentation unavailable: {exc})"+ return (scene, "presentation") if scene is not None else (base, "match")+++def render_video(plugin: str, data: Path, fps: int = 10, hold_s: float = 1.0) -> dict:+ """Replay data/episode.jsonl and draw the spectator camera -> data/replay.mp4 (+ video.json)."""+ from .episode import header_cfg, load_plugin, read_rows, replay+ sport = load_plugin(plugin)+ decl = spec_mod.load(plugin)+ rows = read_rows(Path(data) / "episode.jsonl")+ cfg = header_cfg(next(r for r in rows if r["ev"] == "header"))+ m0 = sport.build(cfg)+ cam = video_camera(sport, cfg, m0, decl)+ if cam is None or not hasattr(sport, "scene"):+ return {"video": False, "why": "the sport defines no camera or scene for spectators"}+ import imageio.v2 as imageio+ import renderers+ from renderers.base import CameraDef+ name = os.environ.get("RO_VIDEO_RENDERER") or cfg.renderer or (decl.get("observation") or {}).get("renderer") \+ or renderers.DEFAULT+ scene, scene_what = spectator_scene(sport, plugin, cfg)+ R = renderers.load(name)(scene)+ cd = CameraDef.from_dict(cam)+ every = max(1, int(round(1.0 / (fps * m0.dt)))) if sport.protocol == "realtime" and m0.dt else 1+ repeat = max(1, int(round(fps * hold_s))) if sport.protocol == "turn" else 1+ out = Path(data) / "replay.mp4"+ part = out.with_suffix(".part.mp4") # renamed once complete: a killed render leaves no replay.mp4+ w = imageio.get_writer(str(part), fps=fps, codec="libx264", quality=7, macro_block_size=8)+ n = 0+ from renderers.label import frame_label+ tag = frame_label(R, scene) # None: the default renderer on the match scene (no tag)+ stamp = None+ if tag is not None:+ from renderers.label import stamp as stamp_fn+ stamp = stamp_fn++ def draw(match, *_):+ nonlocal n+ if sport.protocol == "realtime" and match.k % every and match.phase().state != FINISHED:+ return+ own = scene_what == "spectator" and hasattr(match, "spectator_state")+ img = R.render(match.spectator_state() if own else match.render_state(), [cd])[0]+ if stamp is not None:+ img = stamp(img, tag)+ for _ in range(repeat):+ w.append_data(img)+ n += 1++ try:+ replay(sport, rows, observer=draw)+ finally:+ w.close()+ part.replace(out)+ info = {"video": n > 0, "frames": n, "fps": fps, "renderer": name, "camera": cam["name"] if "name" in cam else "",+ "scene": scene_what, "label": tag}+ (Path(data) / "video.json").write_text(json.dumps(info))+ return info+++def main(argv):+ print(json.dumps(render_video(argv[0], Path(argv[1]))))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/sport.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/sport.pynew file mode 100644index 0000000000..02401a2a78--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/sport.py@@ -0,0 +1,464 @@+"""Contract ② (docs/framework_zh.md §4.2): the one interface between the core and a sport (sports/<sport>/).++A sport's plugin module exports SPORT. The core calls only the functions below and never names a sport; a sport never+imports another sport. A sport answers four questions, one group of functions each (10 required):++ world Sport.build(cfg) -> Match Match.step() -> events Match.state_digest() -> hex+ actions Match.schema(seat) Match.apply(seat, low_cmd) -> info+ optional high-level plugin: Sport.action_layer(level) -> ActionLayer whose lower() turns a high-level+ command into a low-level one (the episode log holds LOW-LEVEL commands only)+ referee Match.phase() -> Phase Match.scores() -> {side: n} Match.tiebreaks() -> [(name, rule)]+ optional: to_move(), forfeit(), resume(), retire(), ranking()+ observation Match.observe(seat, query) -> dict (own body + referee information, whitelisted in sport.toml)+ Match.cameras(seat, query) -> [camera definitions] (drawn by the task's renderer, renderers/)++Optional hooks have defaults in MatchBase; none of them is required by every sport, and the core never branches on a+sport. Stage-0 hooks (all optional): sides != seats (MatchConfig.sides, Match.entities: one act in flight per entity),+N sides with a classification (Match.ranking) and in-match retirement (Match.retire), a delayed effect+(ActionLayer.delay_steps), observation parameters (the `query` of observe/cameras), a team channel (core/channel.py,+declared in sport.toml) and a scored single format without an opponent (tiebreaks() == []).++Reply images (core 0.2.8, optional): Match.reply_views(seat, cmd, info) names the cameras (and optionally a short+strip of frames) that show the result of an action; the core snapshots them under the lock right after the action+took effect, draws them off the lock with the task's renderer (the path of the observation images) and attaches them+to the action's reply as `observation` (image_png_b64 + tiles, as /observe). In the turn protocol the core also tells+the sport whose review is due (Match.awaiting_review), so that a sport serving images only on turn can hold them+back from the other seats while the actor reviews.++Presentation (core 0.2.4, optional, spectators only): sports/<sport>/presentation/presentation.toml dresses the scene+of Sport.scene(cfg) for spectator renderers (renderers/presentation; e.g. fine visual meshes on a robot's bodies,+same kinematics). It is not part of the simulator directory and never reaches the players' images, unless the sport+declares `players` there (core 0.2.9): then the generator bundles it (and the models' files) into the simulator and+the players' images are drawn from it (core/observe.players_scene; a sport drawing its own images uses+renderers.players_model).+"""+from __future__ import annotations++import hashlib+import json+import math+from dataclasses import asdict, dataclass, field, fields+from typing import Any, Callable, Protocol+++@dataclass(frozen=True)+class MatchConfig:+ sport: str+ format: str # single | duel | team | multi (the sport declares which it supports)+ seats: tuple[str, ...] # e.g. ("A", "B"); the HTTP addresses /<seat>/<endpoint>+ seed: int+ first: str | None = None # the side that starts (serves / throws first; the rules say what that means)+ slowdown: float | None = None # realtime only+ level: int | None = None # scripted opponent level (single)+ action_level: str = "high" # high | low+ play: str = "program" # program | direct+ params: dict = field(default_factory=dict)+ sides: dict | None = None # seat -> side; default: every seat is its own side+ renderer: str | None = None # the renderer of the players' images (renderers/; None = the default)++ def side_of(self, seat: str) -> str:+ return (self.sides or {}).get(seat, seat)++ def side_list(self) -> list[str]:+ out: list[str] = []+ for s in self.seats:+ if self.side_of(s) not in out:+ out.append(self.side_of(s))+ return out++ def seats_of(self, side: str) -> list[str]:+ return [s for s in self.seats if self.side_of(s) == side]++ def to_json(self) -> dict:+ d = asdict(self)+ d["seats"] = list(self.seats)+ return d++ @staticmethod+ def from_json(d: dict) -> "MatchConfig":+ known = {f.name for f in fields(MatchConfig)}+ return MatchConfig(**{**{k: v for k, v in d.items() if k in known}, "seats": tuple(d["seats"])})+++PLAYING, UNIT_OVER, FINISHED = "playing", "unit_over", "finished"+++@dataclass+class Phase:+ state: str # PLAYING | UNIT_OVER | FINISHED+ review: tuple[str, ...] = () # seats that review before play resumes (realtime: usually all seats)+ reason: str = ""+++class Refused(Exception):+ """An action the core must refuse: HTTP `code` (400 bad body, 409 wrong time) with `message`."""++ def __init__(self, message: str, code: int = 400):+ super().__init__(message)+ self.code = code+ self.cause = "" # parse_action: the hidden exception (logs only)+++Tiebreak = tuple[str, Callable[["Match"], "str | None"]] # (name, rule) -> winning side or None (undecided)+++class Match(Protocol):+ k: int # [R] control steps (realtime) / actions (turn) so far+ dt: float # [R realtime] control step, seconds++ # world+ def step(self) -> list[dict]: ... # [R realtime] advance one control step; events+ def state_digest(self) -> str: ... # [R] hex digest of everything that affects the score+ # actions+ def schema(self, seat: str) -> dict: ... # [R] the low-level command types and ranges (/spec)+ def apply(self, seat: str, cmd: dict) -> dict: ... # [R] a LOW-LEVEL command takes effect now; info+ # referee+ def phase(self) -> Phase: ... # [R]+ def scores(self) -> dict[str, float]: ... # [R] by side (informational: tiebreaks decide)+ def tiebreaks(self) -> list[Tiebreak]: ... # [R] rulebook -> extra play -> last resort; [] = solo+ # observation+ def observe(self, seat: str, query: dict | None = None) -> dict: ... # [R] own body + referee information+ def cameras(self, seat: str, query: dict | None = None) -> list[dict]: ... # [R] camera definitions (renderers/)+++class MatchBase:+ """Defaults of every optional hook (a sport subclasses this and overrides what it needs)."""+ k = 0+ dt = 0.0+ awaiting_review = None # turn protocol, set by the core: the seat whose review+ # is due now (None: nobody's); never part of the digest++ # referee+ def resume(self) -> None: # leaving a review: frozen-time work (next serve ...)+ pass++ def to_move(self): # turn protocol: the seat whose turn it is+ return None++ def forfeit(self, seat, why) -> bool: # record a core decision inside the world (True)+ return False++ def retire(self, side, why) -> bool: # N sides: True = the match goes on without `side`+ return False++ def ranking(self): # N sides: the classification, best first+ return None++ def unit(self) -> int: # index of the current unit (acts of an old unit drop)+ return 0++ # actions+ def schema(self, seat) -> dict:+ return {}++ def entities(self, seat) -> tuple[str, ...]: # what a seat commands; one act in flight per entity+ return ()++ # observation+ def cameras(self, seat, query=None) -> list[dict]:+ return []++ def render_state(self) -> dict: # what a renderer needs to draw the scene now+ return {}++ def camera_job(self, seat): # a sport that draws its own images: (job, meta)+ return None, {}++ def reply_views(self, seat, cmd, info) -> dict | None:+ """The images of an action's result for its reply (core 0.2.8), or None. Called under the lock right after+ Match.apply(seat, cmd) returned `info` (realtime: only for an act without a delayed effect); it must not change+ the match, and what it returns must follow from the match state and (seat, cmd, info) alone, so that a replay+ can draw the same images (python -m core.episode PLUGIN DIR --reply N).+ {"frames": [{"cameras": [camera definitions, as cameras()],+ "state": render state (optional; default: render_state() now),+ "label": short text (optional, e.g. "-200 ms"; shown in the tiles)}, ...],+ "order": "frame" (default: frame after frame) | "camera" (camera after camera: one strip per camera),+ "columns": tiles per row (default: sport.toml [observation] columns),+ "note": one line for the player (optional)}+ Drawn like the observation images: the task's renderer, the match scene (never a presentation scene),+ sport.toml [observation] frame_budget_ms for the whole reply image."""+ return None++ def final_fields(self) -> dict: # sport fields for final.json+ return {}++ def continuous_score(self): # sport.toml [score] from = "hook": {side: number},+ return None # larger is better (core/score.py, core 0.2.14)++ def broadcast_frame(self): # spectator frame (never read back)+ return None+++class ActionLayer(Protocol):+ level: str # "high" | "low"+ worker: str | None # Sport worker kind that runs prepare(), or None+ delay_steps: int # realtime: the effect is delay_steps after lowering++ def parse(self, seat: str, body: dict, match: Match, ctx: dict) -> dict: ...+ # validate a request body (raise Refused); ctx = core facts at the request (e.g. both chess clocks), which the+ # plugin may copy into the command so that replay sees them. Realtime: parse runs off the world lock and+ # Match.apply later, at the effect step, where the core checks again only that the unit (Match.unit) is the same,+ # so apply re-checks whatever else may have changed meanwhile (the phase, whose turn, a body's state) and returns+ # {"rejected": why} (counted) for a command that no longer holds+ def snapshot(self, seat: str, cmd: dict, match: Match, ordinal: int) -> Any: ... # under the lock, for prepare+ def prepare(self, job: Any) -> Any: ... # off the lock (in `worker` if set); expensive planning+ def lower(self, seat: str, cmd: dict, prepared: Any, match: Match) -> tuple[dict, dict]: ...+ # at the effect boundary, cheap: -> (low-level command for Match.apply, info for the reply)+ def reply(self, seat: str, cmd: dict, info: dict, match: Match) -> dict: ...+++class LowLayer:+ """The identity layer: the request body, validated by `validate(seat, body, match, ctx) -> cmd`, is the command."""+ level = "low"+ worker = None+ delay_steps = 0++ def __init__(self, validate):+ self._validate = validate++ def schema(self, match, seat): # what /spec shows of this layer's commands+ return match.schema(seat)++ def parse(self, seat, body, match, ctx):+ return self._validate(seat, body, match, ctx)++ def snapshot(self, seat, cmd, match, ordinal):+ return None++ def prepare(self, job):+ return None++ def lower(self, seat, cmd, prepared, match):+ return cmd, {}++ def reply(self, seat, cmd, info, match):+ return info+++def check_command(schema: dict, body: dict) -> dict:+ """Validate a request body against a Match.schema() and return the clean command (raises Refused).++ schema = {TYPE: {FIELD: {"type": "number"|"integer"|"boolean"|"enum"|"vector", "min", "max", "values", "len",+ "unit", "doc", "default"}}}; the command is {"type": TYPE, FIELD: value, ...}."""+ if not isinstance(body, dict):+ raise Refused("the action must be a JSON object")+ kind = body.get("type")+ if kind not in schema:+ raise Refused(f"unknown action type {kind!r}; one of {sorted(schema)}")+ out: dict = {"type": kind}+ spec = schema[kind]+ extra = sorted(set(body) - set(spec) - {"type", "entity"})+ if extra:+ raise Refused(f"unknown field(s) {extra} for {kind}")+ for name, f in spec.items():+ if name not in body:+ if "default" in f:+ out[name] = f["default"]+ continue+ raise Refused(f"{kind} needs {name}")+ out[name] = _value(name, f, body[name])+ if "entity" in body:+ out["entity"] = str(body["entity"])+ return out+++def _value(name, f, v):+ t = f.get("type", "number")+ if t == "boolean":+ if not isinstance(v, bool):+ raise Refused(f"{name} must be true or false")+ return v+ if t == "enum":+ if v not in f["values"]:+ raise Refused(f"{name} must be one of {f['values']}")+ return v+ if t == "vector":+ if not isinstance(v, list) or len(v) != f["len"]:+ raise Refused(f"{name} must be a list of {f['len']} numbers")+ return [_number(f"{name}[{i}]", f, x) for i, x in enumerate(v)]+ x = _number(name, f, v)+ if t == "integer":+ if x != int(x):+ raise Refused(f"{name} must be an integer")+ return int(x)+ return x+++def _number(name, f, v):+ if isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, int) and v.bit_length() > 60) or \+ not math.isfinite(v):+ raise Refused(f"{name} must be a finite number")+ lo, hi = f.get("min", -math.inf), f.get("max", math.inf)+ if not lo <= v <= hi:+ raise Refused(f"{name} must be in [{lo}, {hi}]")+ return round(float(v), f.get("digits", 6))+++# ------------------------------------------------------------------ request validation (core 0.2.11)+# Every request body is checked before an endpoint reads it (check_body), and every act body against the action+# layer's published schema before the layer parses it (check_action). A body that fails, or that makes the layer's+# parse raise ANY exception, is the player's own error: refused (HTTP 400, counted), never a technical failure.+BODY_MAX_DEPTH = 10 # nesting of lists / objects (the body object is depth 1)+BODY_MAX_ITEMS = 4096 # elements of one list, keys of one object+BODY_MAX_STR = 8192 # characters of one string (keys included)+BODY_MAX_ABS = 1e15 # |number|: no action of any sport needs more (and a huge integer overflows a float)+TYPE_MAX_STR = 64 # characters of the action type+++def check_body(value, depth: int = 1) -> None:+ """Generic sanity of a decoded JSON request body (raises Refused): finite, bounded numbers; bounded strings, list+ lengths and nesting."""+ if depth > BODY_MAX_DEPTH:+ raise Refused(f"the request is nested deeper than {BODY_MAX_DEPTH} levels")+ if value is None or isinstance(value, bool):+ return+ if isinstance(value, str):+ if len(value) > BODY_MAX_STR:+ raise Refused(f"strings are limited to {BODY_MAX_STR} characters")+ return+ if isinstance(value, int):+ if value.bit_length() > 60 or abs(value) > BODY_MAX_ABS:+ raise Refused(f"numbers are limited to +-{BODY_MAX_ABS:g}")+ return+ if isinstance(value, float):+ if not math.isfinite(value) or abs(value) > BODY_MAX_ABS:+ raise Refused(f"numbers must be finite and within +-{BODY_MAX_ABS:g}")+ return+ if isinstance(value, (list, dict)):+ if len(value) > BODY_MAX_ITEMS:+ raise Refused(f"lists and objects are limited to {BODY_MAX_ITEMS} items")+ for k in value if isinstance(value, dict) else ():+ if not isinstance(k, str) or len(k) > BODY_MAX_STR:+ raise Refused("object keys must be strings")+ for x in value.values() if isinstance(value, dict) else value:+ check_body(x, depth + 1)+ return+ raise Refused("unsupported JSON value")+++def _is_num(v) -> bool:+ return not isinstance(v, bool) and isinstance(v, (int, float))+++def _lens(spec_len) -> set | None:+ """A field's declared length: an int, or a text such as "1 or 2" (None: not declared)."""+ if isinstance(spec_len, int) and not isinstance(spec_len, bool):+ return {spec_len}+ if isinstance(spec_len, str):+ return {int(x) for x in spec_len.replace(",", " ").split() if x.isdigit()} or None+ return None+++def _check_field(kind: str, name: str, f, v) -> None:+ """The shape of one declared field (ranges and meaning stay with the layer's parse)."""+ if not isinstance(f, dict):+ return+ t, where = f.get("type", "number"), f"{kind}.{name}"+ if t in ("number", "integer"):+ if not _is_num(v):+ raise Refused(f"{where} must be a number")+ elif t == "boolean":+ if not isinstance(v, bool):+ raise Refused(f"{where} must be true or false")+ elif t == "enum":+ if isinstance(v, (list, dict)):+ raise Refused(f"{where} must be one of {f.get('values')}")+ elif t == "vector":+ lens = _lens(f.get("len"))+ if not isinstance(v, list) or (lens and len(v) not in lens) or not all(_is_num(x) for x in v):+ raise Refused(f"{where} must be a list of {f.get('len', 'some')} numbers")+ elif t == "rows":+ lens, top = _lens(f.get("len")), f.get("max_rows")+ if not isinstance(v, list) or (isinstance(top, int) and len(v) > top) or not all(+ isinstance(r, list) and (not lens or len(r) in lens) and all(_is_num(x) for x in r) for r in v):+ raise Refused(f"{where} must be a list of rows of {f.get('len', 'some')} numbers"+ + (f", at most {top} rows" if isinstance(top, int) else ""))+ elif t == "list":+ if not isinstance(v, list):+ raise Refused(f"{where} must be a list")+ elif t == "object":+ if not isinstance(v, dict):+ raise Refused(f"{where} must be an object")+ keys = f.get("keys")+ if isinstance(keys, (list, tuple)) and set(v) - set(keys):+ raise Refused(f"{where}: unknown key(s) {sorted(set(v) - set(keys))[:8]}; the keys are {list(keys)}")+++def check_action(schema, body) -> None:+ """An act body against the action layer's published schema, before the layer parses it (raises Refused). The+ type, if given, must be a short string; for a type the schema names, each declared field that is present must+ have its shape (number, boolean, scalar enum value, vector / rows lengths, list, object keys). Unknown types and+ fields, ranges and defaults stay with the layer's parse (a layer may take an implicit type)."""+ if not isinstance(body, dict):+ raise Refused("the action must be a JSON object")+ kind = body.get("type")+ if kind is not None and (not isinstance(kind, str) or len(kind) > TYPE_MAX_STR):+ raise Refused(f"type must be a string of at most {TYPE_MAX_STR} characters")+ spec = schema.get(kind) if isinstance(schema, dict) and kind is not None else None+ if isinstance(spec, dict):+ for name, f in spec.items():+ if name in body:+ _check_field(kind, name, f, body[name])+++def parse_action(layer, seat: str, body, match, ctx: dict):+ """What the core runs for every act (and core.local for built-in players): check_body, check_action against the+ layer's schema (what /spec shows), then layer.parse. ANY exception on the way is the player's own error: Refused+ (HTTP 400); a malformed action never ends a match as a technical failure. The exception's text is not shown to+ the player; the caller may log it (`Refused.cause`). A seat without entities (Match.entities) may not name one+ (core 0.2.13): realtime acts are one in flight per (seat, entity)."""+ try:+ check_body(body)+ check_action(layer.schema(match, seat) if hasattr(layer, "schema") else {}, body)+ if "entity" in body and not match.entities(seat):+ raise Refused("unknown field entity: this seat commands no entities")+ return layer.parse(seat, body, match, ctx)+ except Refused:+ raise+ except Exception as exc: # noqa: BLE001+ err = Refused("invalid action: the action layer could not read it (see /spec for the command schema)")+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"+ raise err from exc+++class SchemaLayer(LowLayer):+ """The default low level: the body is checked against Match.schema(seat); `ctx_keys` copies core facts (e.g. the+ chess clocks) into the command so that the replay sees them."""++ def __init__(self, ctx_keys: tuple[str, ...] = ()):+ super().__init__(None)+ self.ctx_keys = ctx_keys++ def parse(self, seat, body, match, ctx):+ cmd = check_command(match.schema(seat), body)+ ents = tuple(match.entities(seat))+ if ents and cmd.get("entity", ents[0]) not in ents:+ raise Refused(f"entity must be one of {list(ents)}")+ if ents:+ cmd.setdefault("entity", ents[0])+ for k in self.ctx_keys:+ cmd[k] = ctx.get(k)+ return cmd+++class Sport(Protocol):+ name: str+ protocol: str # "realtime" | "turn"+ revision: str # bump on any change that alters play+ source_dirs: list[str] # whose files enter source_sha (the plugin dir; the core adds itself)++ def build(self, cfg: MatchConfig) -> Match: ...+ def action_layer(self, level: str) -> ActionLayer: ...+ def spec(self, cfg: MatchConfig, seat: str, match: Match) -> dict: ...+ # optional: the scene for renderers, worker processes (render / plan), built-in players+ def scene(self, cfg: MatchConfig): ... # renderers.base.Scene (needed when cameras() is used);+ # the MATCH scene: the base of the presentation scene+ # (sports/<s>/presentation) and the players' images+ # unless that declares `players`+ def worker_init(self, kind: str, seat: str, cfg: MatchConfig) -> Any: ...+ def worker_call(self, obj: Any, kind: str, job: Any) -> dict: ...+ def players(self) -> dict: ... # {name: factory(spec, seat, seed) -> built-in player}+++def sha_json(value) -> str:+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), default=float).encode()).hexdigest()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/testkit.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/testkit.pynew file mode 100644index 0000000000..9c96c43f51--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/testkit.py@@ -0,0 +1,648 @@+"""The generic test suite every sport passes (tools/check stages 2 and 4; docs/framework_zh.md §9 sport rules). It+loads the sport like the core does and plays in-process matches of the sport's built-in players (core/local.py).++ python3 -m core.testkit tests PLUGIN [--json OUT] stage 2: the generic tests + the sport's exploit tests+ python3 -m core.testkit fairness PLUGIN [--json OUT] stage 4: first-order and seat advantage of built-ins++Tests (each one result row {name, ok, detail}):+ determinism the same match twice in-process gives the same digest; its episode replays in a fresh process+ (python -m core.episode) to the same digest, scores and winner, within replay_timeout(decl)+ (core 0.2.17: sport.toml [timing] replay_timeout_s when it is above 1800 s, else 1800 s)+ no_draw every finished match of every format with two or more sides has a winner; the tiebreak names+ are sport.toml [tiebreaks] order+ mirror_symmetry sport.toml [fairness] mirror = "exact": swapping seats and the first order swaps the result and+ a player sees exactly the same observations+ whitelist no observation field outside sport.toml [observation] fields in any match; the core drops an+ injected field and records the error+ observe_is_pure observe / cameras / render_state / reply_views never change the state digest+ refuses_bad malformed or out-of-range actions are refused (HTTP 400) and change nothing+ fuzz_actions every format and action level: hostile bodies (huge integers, NaN / inf, wrong types, nested+ junk, oversize strings and lists) through the core's parse_action are refused, raise nothing but+ Refused and change nothing; junk observation queries change nothing (core 0.2.11)+ frame_budget the task renderer draws one observation within [observation] frame_budget_ms; a sport with+ reply images (Match.reply_views) also draws the first action's reply image within it+ exploit:<id> every [[exploits]] entry names a test in tests/test_*.py, and that test passes+ solo_quit every single-side format: a session that ends mid-match (the core's forfeit "abandoned" after+ some play, core 0.2.6) is a loss with no winner, and its episode replays in a fresh process to the+ same digest and decision+ prestart_no_show every format of one or two sides: a side that never started (the core's forfeit "no_show" at+ step 0, at the start window or at a collect before the start, core 0.2.7) replays to a loss: no+ winner for a single side, the other side's win in a duel, with no play (k = 0); the sport's+ forfeit hook may end its world (core 0.2.12: the core decides a forfeit first, whatever the phase)+ seed_private information (core 0.2.14): where the sport itself shows the seed (observe, /spec, final fields);+ the core scrubs them in hidden-seed matches+ continuous_score sport.toml [score] (core 0.2.14): well formed; the values of every no_draw match are finite, within+ its range and not below the forfeit value; a side that never started gets the forfeit value+"""+from __future__ import annotations++import importlib.util+import json+import math+import os+import subprocess+import sys+import tempfile+import time+import traceback+from pathlib import Path++from . import local+from . import score as score_mod+from . import spec as spec_mod+from .episode import load_plugin+from .observe import filter_fields, players_scene+from .service import own_hook+from .sport import FINISHED, MatchConfig, Refused, check_body, parse_action++ROOT = Path(__file__).resolve().parent+REPLAY_TIMEOUT_S = 1800 # the fresh-process replay of a test match, unless the sport declares a longer one+++def replay_timeout(decl) -> float:+ """The limit of the tests' fresh-process replays (determinism, solo_quit), core 0.2.17: sport.toml [timing]+ replay_timeout_s when it is longer than REPLAY_TIMEOUT_S (a long match, e.g. 600 s of play, replays in more than+ 1800 s), else REPLAY_TIMEOUT_S. Never shorter than the 1800 s of cores <= 0.2.16: the task's own limit (default+ 600 s, tools/sportlib.py post_match_timeouts) does not tighten the check."""+ t = (decl.get("timing") or {}).get("replay_timeout_s")+ return max(float(REPLAY_TIMEOUT_S), float(t)) if t else float(REPLAY_TIMEOUT_S)+++def fresh_replay(plugin, data, decl) -> tuple[dict, str]:+ """Replay the episode in `data` in a fresh process (python -m core.episode): (replay_check.json or {}, stderr)."""+ limit = replay_timeout(decl)+ try:+ p = subprocess.run([sys.executable, "-m", "core.episode", plugin, data], cwd=ROOT.parent,+ capture_output=True, text=True, timeout=limit)+ except subprocess.TimeoutExpired:+ return {}, f"the fresh-process replay took more than {limit:.0f} s (sport.toml [timing] replay_timeout_s)"+ return (json.loads((Path(data) / "replay_check.json").read_text()) if p.returncode == 0 else {}), p.stderr+++def configs(decl, sport, seeds=(1, 2, 3)):+ """One MatchConfig per (format, action level, seed, first side) the sport declares."""+ levels = (decl.get("modes") or {}).get("action_levels", ["high"])+ for fmt, f in (decl.get("formats") or {}).items():+ firsts = f.get("first") or [f["seats"][0]]+ for level in levels:+ for seed in seeds:+ for first in firsts:+ yield MatchConfig(sport=sport.name, format=fmt, seats=tuple(f["seats"]), seed=seed, first=first,+ action_level=level, sides=f.get("sides"))+++class Recorder:+ """Wraps a built-in player and keeps what it saw (the state part of each view)."""++ def __init__(self, inner):+ self.inner, self.seen = inner, []++ def act(self, view):+ self.seen.append({k: v for k, v in view["state"].items() if k != "seat"})+ return self.inner.act(view)+++def row(name, ok, detail=""):+ return {"name": name, "ok": bool(ok), "detail": detail if isinstance(detail, str) else json.dumps(detail)[:600]}+++def t_determinism(sport, plugin, decl):+ out = []+ cfg = next(configs(decl, sport, seeds=(7,)))+ names = {s: "reference" for s in cfg.seats}+ with tempfile.TemporaryDirectory() as tmp:+ a = local.play(sport, cfg, local.make_players(sport, cfg, names, plugin=plugin), data=tmp, plugin=plugin)+ b = local.play(sport, cfg, local.make_players(sport, cfg, names, plugin=plugin), plugin=plugin)+ out.append(row("determinism:in_process", a["digest"] == b["digest"] and a["scores"] == b["scores"],+ {"a": a["digest"][:16], "b": b["digest"][:16]}))+ rc, err = fresh_replay(plugin, tmp, decl)+ ok = rc.get("state_sha") == a["digest"] and rc.get("scores") == a["scores"] and rc.get("winner") == a["winner"]+ out.append(row("determinism:fresh_process_replay", ok, rc and {k: rc[k] for k in ("scores", "winner", "k")}+ or err[-400:]))+ return out+++def t_no_draw_and_whitelist(sport, plugin, decl, n=4):+ order = (decl.get("tiebreaks") or {}).get("order")+ bad, leaks, played, names_ok, cont = [], set(), 0, True, []+ checks = (decl.get("players") or {}).get("check", ["random"])+ for cfg in configs(decl, sport, seeds=tuple(range(1, n + 1))):+ for pol in checks + ["reference"]:+ names = {s: (pol if i % 2 == 0 else "reference") for i, s in enumerate(cfg.seats)}+ r = local.play(sport, cfg, local.make_players(sport, cfg, names, plugin=plugin), plugin=plugin)+ played += 1+ leaks |= set(r["observation_leaks"])+ if r.get("continuous"):+ cont.append(r["continuous"]["by_side"])+ if len(cfg.side_list()) >= 2 and r["finished"] and r["winner"] is None:+ bad.append({"cfg": cfg.to_json(), "scores": r["scores"]})+ if not r["finished"]:+ bad.append({"cfg": cfg.to_json(), "unfinished": True})+ m = sport.build(cfg)+ if order is not None and len(cfg.side_list()) >= 2 and [x for x, _ in m.tiebreaks()] != order:+ names_ok = False+ out = [row("no_draw", not bad, bad[:3] or f"{played} matches, every one decided"),+ row("tiebreaks_declared", names_ok and order is not None or not any(+ len(f["seats"]) > 1 for f in decl.get("formats", {}).values()),+ f"sport.toml [tiebreaks] order = {order}"),+ row("whitelist:no_leak", not leaks, sorted(leaks) or "every observation within the whitelist")]+ sd = score_mod.declaration(decl)+ if sd is not None:+ vals = [v for by in cont for v in by.values()]+ lo, hi = (sd.get("range") or [-math.inf, math.inf])+ out.append(row("continuous_score:values", vals and all(lo <= v <= hi for v in vals)+ and all(sd["forfeit"] <= v for v in vals),+ f"{len(vals)} values in [{min(vals, default=None)}, {max(vals, default=None)}], range "+ f"{sd.get('range')}, forfeit {sd['forfeit']} (must be the worst)"))+ cfg = next(configs(decl, sport))+ m = sport.build(cfg)+ allowed = spec_mod.whitelist(decl)+ obs = dict(m.observe(cfg.seats[0], None), _secret_state=[1, 2, 3])+ kept, dropped = filter_fields(obs, allowed)+ out.append(row("whitelist:declared", allowed is not None, "sport.toml [observation] fields"))+ out.append(row("whitelist:enforced", "_secret_state" not in kept and dropped == ["_secret_state"], dropped))+ return out+++def t_mirror(sport, plugin, decl, seeds=(1, 2, 3, 4)):+ if (decl.get("fairness") or {}).get("mirror") != "exact":+ return [row("mirror_symmetry", True, "skipped: [fairness] mirror is not \"exact\" (the fairness check covers it)")]+ out = []+ for fmt, f in decl.get("formats", {}).items():+ seats = f["seats"]+ if len(seats) != 2:+ continue+ for level in (decl.get("modes") or {}).get("action_levels", ["high"]):+ for seed in seeds:+ res = []+ for swap in (False, True):+ cfg = MatchConfig(sport=sport.name, format=fmt, seats=tuple(seats), seed=seed,+ first=seats[1] if swap else seats[0], action_level=level)+ pol = ["reference", "random"][::-1] if swap else ["reference", "random"]+ ps = {s: Recorder(local.make_players(sport, cfg, {s: n}, plugin=plugin, seed=seed)[s])+ for s, n in zip(seats, pol)}+ r = local.play(sport, cfg, ps, plugin=plugin)+ res.append((r, ps))+ (r1, p1), (r2, p2) = res+ a, b = seats+ swapped = r1["scores"] == {a: r2["scores"][b], b: r2["scores"][a]} and \+ ({a: b, b: a}.get(r1["winner"]) == r2["winner"])+ same_view = p1[a].seen == p2[b].seen and p1[b].seen == p2[a].seen+ out.append(row(f"mirror_symmetry:{fmt}:{level}:seed{seed}", swapped and same_view,+ {"scores": [r1["scores"], r2["scores"]], "same_observations": same_view}))+ return out or [row("mirror_symmetry", True, "no two-seat format")]+++def t_pure(sport, plugin, decl):+ cfg = next(c for c in configs(decl, sport) if len(c.seats) >= 1)+ m = sport.build(cfg)+ ps = local.make_players(sport, cfg, {s: "reference" for s in cfg.seats}, plugin=plugin)+ layer = sport.action_layer(cfg.action_level)+ views = local.Views(sport, cfg, m, decl, True, plugin)+ bad = []+ for _ in range(4):+ if m.phase().state == FINISHED:+ break+ seat = m.to_move() or cfg.seats[0]+ d0 = m.state_digest()+ for s in cfg.seats:+ m.observe(s, None)+ m.cameras(s, None)+ m.render_state()+ v = views.view(seat, {})+ if m.state_digest() != d0:+ bad.append("observe/cameras/render_state changed the digest")+ if sport.protocol == "turn":+ low, _ = layer.lower(seat, layer.parse(seat, ps[seat].act(v), m, {"clock_left_s": {}}), None, m)+ info = m.apply(seat, low) or {}+ d1 = m.state_digest()+ m.reply_views(seat, low, info)+ if m.state_digest() != d1:+ bad.append("reply_views changed the digest")+ else:+ m.step()+ return [row("observe_is_pure", not bad, bad or "digest unchanged by observations")]+++def bad_bodies(schema: dict):+ kind, fields = next(iter(schema.items()))+ good = {k: (f.get("min", 0) + f.get("max", 0)) / 2 if f.get("type", "number") == "number" else f.get("default")+ for k, f in fields.items()}+ yield {"type": "no-such-action"}+ yield {"type": kind}+ for k, f in fields.items():+ if f.get("type", "number") in ("number", "integer"):+ for v in (float("nan"), "1", f.get("max", 1e9) + 1e6 if "max" in f else None):+ if v is not None:+ yield {"type": kind, **good, k: v}+ yield {"type": kind, **good, "unexpected_field": 1}+++def t_refuses(sport, plugin, decl):+ out = []+ for level in (decl.get("modes") or {}).get("action_levels", ["high"]):+ cfg = next(c for c in configs(decl, sport) if c.action_level == level)+ m = sport.build(cfg)+ layer = sport.action_layer(level)+ seat = m.to_move() or cfg.seats[0]+ schema = layer.schema(m, seat) if hasattr(layer, "schema") else {}+ if not schema:+ out.append(row(f"refuses_bad:{level}", True, "skipped: the layer publishes no schema"))+ continue+ d0, leaked = m.state_digest(), []+ for body in bad_bodies(schema):+ try:+ layer.parse(seat, body, m, {"clock_left_s": {}})+ leaked.append(body)+ except Refused:+ pass+ out.append(row(f"refuses_bad:{level}", not leaked and m.state_digest() == d0,+ [str(b) for b in leaked][:3] or "every malformed action refused, nothing changed"))+ return out+++FUZZ_ALWAYS_BAD = { # the core refuses these in any field of any action (core 0.2.11)+ "inf": float("inf"), "-inf": float("-inf"), "nan": float("nan"), "hugeint": 10 ** 400, "-hugeint": -10 ** 400,+ "int2^70": 2 ** 70, "1e300": 1e300, "deep": json.loads("[" * 30 + "]" * 30), "longstr": "x" * 20000,+ "longlist": [0.1] * 5000}+FUZZ_WRONG_TYPE = {"null": None, "true": True, "str": "x", "list": [1, 2, 3], "nested": [[1], [2]], "dict": {"a": 1},+ "empty_list": [], "dict_nested": {"a": {"b": [1, {"c": None}]}}}+FUZZ_QUERIES = ({"camera": float("inf")}, {"camera": {"a": 1}}, {"camera": 10 ** 400}, {"aim": "x"}, {"aim": [1]},+ {"x": [[1]]}, {"view": None}, {"camera": "x" * 5000})+++def fuzz_bodies(schema: dict):+ """(name, body, must_refuse): malformed act bodies for every action type and field of a layer's schema."""+ for junk in ([], "x", 5, None, [{"type": "x"}]):+ yield f"body={junk!r}", junk, True+ for v in (None, [], {}, ["x"], 10 ** 400, float("nan"), "x" * 5000, True, 3):+ yield f"type={str(v)[:12]}", {"type": v}, v is not None+ for kind, fields in (schema or {}).items():+ fields = fields if isinstance(fields, dict) else {}+ good = {}+ for k, f in fields.items():+ f = f if isinstance(f, dict) else {}+ if f.get("type", "number") in ("number", "integer"):+ lo, hi = f.get("min", 0), f.get("max", 0)+ good[k] = (lo + hi) / 2 if all(isinstance(x, (int, float)) for x in (lo, hi)) else 0+ elif "default" in f:+ good[k] = f["default"]+ for k in [*fields, "type", "entity", "unexpected_field"]:+ for name, v in FUZZ_ALWAYS_BAD.items():+ yield f"{kind}.{k}={name}", {"type": kind, **good, k: v}, True+ for name, v in FUZZ_WRONG_TYPE.items():+ yield f"{kind}.{k}={name}", {"type": kind, **good, k: v}, k == "type" and v is not None+++def t_fuzz(sport, plugin, decl):+ """Malformed actions and observation queries, through the core's own path (core.sport.parse_action, the same+ function the HTTP service runs): every always-bad body is refused, nothing raises anything but Refused, nothing+ changes the state digest. Every format and action level."""+ out, seen = [], set()+ for cfg in configs(decl, sport, seeds=(1,)):+ if (cfg.format, cfg.action_level) in seen:+ continue+ seen.add((cfg.format, cfg.action_level))+ m = sport.build(cfg)+ layer = sport.action_layer(cfg.action_level)+ seat = m.to_move() or cfg.seats[0]+ schema = layer.schema(m, seat) if hasattr(layer, "schema") else {}+ d0, bad, n = m.state_digest(), [], 0+ for name, body, must in fuzz_bodies(schema):+ n += 1+ try:+ parse_action(layer, seat, body, m, {"clock_left_s": {s: 600.0 for s in cfg.seats}})+ if must:+ bad.append(f"{name}: accepted")+ except Refused:+ pass+ except Exception as exc: # noqa: BLE001+ bad.append(f"{name}: {type(exc).__name__} escaped parse_action")+ for q in FUZZ_QUERIES: # the core: check_body, then any exception with a query is a refusal+ n += 1+ try:+ check_body({"query": q})+ m.observe(seat, q)+ m.cameras(seat, q)+ except Exception: # noqa: BLE001+ pass+ if m.state_digest() != d0:+ bad.append("the state digest changed")+ out.append(row(f"fuzz_actions:{cfg.format}:{cfg.action_level}", not bad,+ bad[:4] or f"{n} malformed bodies and queries refused, nothing changed"))+ return out+++def t_budget(sport, plugin, decl):+ obs = decl.get("observation") or {}+ budget = obs.get("frame_budget_ms")+ cfg = next(configs(decl, sport))+ m = sport.build(cfg)+ pres = Path(plugin).resolve().parent / "presentation"+ players = None+ if (pres / "presentation.toml").is_file():+ from renderers import presentation+ players = presentation.players_meshes(pres)+ if not own_hook(m, "cameras") or own_hook(m, "camera_job"):+ if players is None:+ return [row("frame_budget", True, "skipped: the sport draws its own images (a wrapper)")]+ return [_own_budget(sport, cfg, m, decl, plugin, budget, players)]+ from renderers import budget as B+ import renderers+ from renderers.base import CameraDef+ name = obs.get("renderer") or renderers.DEFAULT+ cams = [CameraDef.from_dict(c) for c in m.cameras(cfg.seats[0], None)]+ ok, ms = B.check_budget(renderers.load(name), players_scene(sport, plugin, cfg), m.render_state(), cams,+ budget_ms=budget or 1e9)+ what = f", players' presentation scene ({players} meshes)" if players else ""+ out = [row("frame_budget", budget is not None and ok,+ f"{name}{what}: {ms:.1f} ms per observation, budget {budget} ms")]+ if own_hook(m, "reply_views"):+ out.append(t_reply_budget(sport, plugin, decl, cfg, name, budget))+ return out+++def t_reply_budget(sport, plugin, decl, cfg, name, budget):+ """The first action's reply image (Match.reply_views, core 0.2.8), drawn as the service draws it (the core's+ camera worker), within [observation] frame_budget_ms (median of 3 after one warm-up)."""+ from .observe import CameraWorker, reply_job+ m = sport.build(cfg)+ layer = sport.action_layer(cfg.action_level)+ ps = local.make_players(sport, cfg, {s: "reference" for s in cfg.seats}, plugin=plugin)+ views = local.Views(sport, cfg, m, decl, True, plugin)+ job = None+ for _ in range(50): # the first action that has reply images+ if m.phase().state == FINISHED:+ break+ seat = m.to_move() or cfg.seats[0]+ if sport.protocol != "turn":+ m.step()+ continue+ low, _ = layer.lower(seat, layer.parse(seat, ps[seat].act(views.view(seat, {})), m, {"clock_left_s": {}}),+ None, m)+ info = m.apply(seat, low) or {}+ job = reply_job(m, m.reply_views(seat, low, info), int((decl.get("observation") or {}).get("columns", 2)))+ if job is not None:+ break+ if job is None:+ return row("reply_budget", False, "Match.reply_views gave no image for the first actions of the reference")+ w = CameraWorker(players_scene(sport, plugin, cfg), name)+ w.draw_job(job)+ times = []+ for _ in range(3):+ t = time.perf_counter()+ img = w.draw_job(job)+ times.append((time.perf_counter() - t) * 1000.0)+ ms = sorted(times)[1]+ ok = budget is not None and ms <= float(budget)+ return row("reply_budget", ok, f"{name}: {ms:.1f} ms per reply image ({len(img['tiles'])} tiles), budget {budget} ms")+++def _own_budget(sport, cfg, m, decl, plugin, budget, players, n: int = 5, between: int = 30):+ """A sport that draws its own images from its players' presentation scene: the median wall time of its own+ observation path (Views.view) from a fresh world, `between` control steps apart early in play (a realtime world+ may freeze between rallies: only observations whose image changed count), after a warm-up."""+ m = sport.build(cfg)+ views = local.Views(sport, cfg, m, decl, True, plugin)+ seat = cfg.seats[0]++ def run(k):+ if sport.protocol == "realtime":+ for _ in range(k):+ if m.phase().state == FINISHED:+ break+ m.step()+ last = views.view(seat, {})["observation"].get("image_png_b64")+ times, tries = [], 0+ while len(times) < n and tries < 4 * n:+ tries += 1+ run(between)+ t = time.perf_counter()+ img = views.view(seat, {})["observation"].get("image_png_b64")+ ms = (time.perf_counter() - t) * 1000.0+ if img != last or sport.protocol != "realtime":+ times.append(ms)+ last = img+ if not times:+ return row("frame_budget", False, "no observation with a new image to time")+ ms = sorted(times)[len(times) // 2]+ return row("frame_budget", budget is not None and ms <= float(budget),+ f"the sport's own images from its players' presentation scene ({players} meshes): {ms:.1f} ms per "+ f"observation (median of {len(times)} with a new image), budget {budget} ms")+++def t_exploits(sport, plugin, decl):+ out = []+ tests_dir = Path(plugin).parent / "tests"+ funcs = {}+ for p in sorted(tests_dir.glob("test_*.py")):+ spec = importlib.util.spec_from_file_location(f"sport_test_{p.stem}", p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ funcs.update({k: v for k, v in vars(mod).items() if k.startswith("test_") and callable(v)})+ for ex in decl.get("exploits", []):+ f = funcs.get(ex.get("test", ""))+ if f is None:+ out.append(row(f"exploit:{ex.get('id')}", False, f"no test {ex.get('test')!r} in tests/test_*.py"))+ continue+ try:+ f()+ out.append(row(f"exploit:{ex['id']}", True, ex.get("text", "")))+ except Exception: # noqa: BLE001+ out.append(row(f"exploit:{ex['id']}", False, traceback.format_exc()[-500:]))+ if not decl.get("exploits"):+ out.append(row("exploit_list", False, "sport.toml has no [[exploits]]"))+ return out+++class Idle:+ """A built-in player that never acts (the realtime world runs on without it)."""++ def act(self, view):+ return None+++def t_solo_quit(sport, plugin, decl, steps=40):+ """core 0.2.6 (core rule 6): the collect of a started single-side match writes a forfeit row "abandoned" at the+ current step; the sport's forfeit hook and the fresh-process replay must agree on a loss without a winner."""+ from .episode import read_rows, replay+ out = []+ for fmt, f in (decl.get("formats") or {}).items():+ if len({(f.get("sides") or {}).get(s, s) for s in f["seats"]}) != 1:+ continue+ cfg = next(c for c in configs(decl, sport, seeds=(1,)) if c.format == fmt)+ with tempfile.TemporaryDirectory() as tmp:+ r = local.play(sport, cfg, {s: Idle() for s in cfg.seats}, data=tmp, render=False, plugin=plugin,+ max_actions=0, max_steps=steps)+ ep = Path(tmp) / "episode.jsonl"+ rows = [x for x in read_rows(ep) if x["ev"] != "end"]+ rows += [{"ev": "forfeit", "k": r["k"], "seat": cfg.seats[0], "why": "abandoned"},+ {"ev": "end", "k": r["k"], "reason": "abandoned"}]+ ep.write_text("".join(json.dumps(x, default=float) + "\n" for x in rows))+ mine = replay(sport, rows)+ rc, err = fresh_replay(plugin, tmp, decl)+ ok = (not r["finished"] and mine["winner"] is None and mine["decided_by"] == "forfeit:abandoned"+ and rc.get("state_sha") == mine["state_sha"] and rc.get("winner") is None+ and rc.get("decided_by") == "forfeit:abandoned" and rc.get("k") == r["k"])+ out.append(row(f"solo_quit:{fmt}", ok, {"k": r["k"], "finished_before": r["finished"],+ "decided_by": mine["decided_by"], "replay": rc.get("decided_by")}+ if rc else err[-400:]))+ return out+++def t_prestart_no_show(sport, plugin, decl):+ """core 0.2.7 (core rule 5): a side that never started loses before any play ("no_show" at step 0, when the start+ window closes or at a collect before the start). For every format of one or two sides, the episode the core then+ writes (header, the forfeit row of the first seat of the last side, end) must replay to that decision: a single+ side's loss without a winner, or the other side's win, at step 0. Whether the world then reports itself finished+ is the sport's own business (Match.forfeit records the decision inside the world; a sport may end it there,+ game over, winner set): the core decides a forfeit before it looks at the phase (core.outcome.decide), and the+ service's validity reads the end reason, not the phase (core 0.2.12)."""+ from .episode import replay+ out = []+ for fmt, f in (decl.get("formats") or {}).items():+ cfg = next(c for c in configs(decl, sport, seeds=(1,)) if c.format == fmt)+ sides = list(cfg.side_list())+ if len(sides) > 2:+ continue+ seat = next(s for s in cfg.seats if cfg.side_of(s) == sides[-1])+ rows = [{"ev": "header", "cfg": cfg.to_json(), "sport": sport.name, "protocol": sport.protocol},+ {"ev": "forfeit", "k": 0, "seat": seat, "why": "no_show"}, {"ev": "end", "k": 0, "reason": "no_show"}]+ r = replay(sport, rows)+ want = sides[0] if len(sides) == 2 else None+ ok = r["winner"] == want and r["decided_by"] == "forfeit:no_show" and r["k"] == 0+ out.append(row(f"prestart_no_show:{fmt}", ok, {"absent": seat, "winner": r["winner"], "want": want,+ "decided_by": r["decided_by"], "k": r["k"],+ "finished": r["finished"]}))+ return out+++def t_continuous(sport, plugin, decl):+ """core 0.2.14 (sport.toml [score], core/score.py): the declaration is well formed, and a side that never started+ gets the forfeit value while the other side's value is a finite number (the definition copes with no play)."""+ from .episode import replay+ sd = score_mod.declaration(decl)+ if sd is None:+ return [row("continuous_score", True, "not declared (sport.toml [score]); tools/check warns")]+ bad = score_mod.problems(decl, own_hook(sport.build(next(configs(decl, sport, seeds=(1,)))), "continuous_score"))+ out = [row("continuous_score:declared", not bad, "; ".join(bad) or f"{sd['name']} (from {sd['from']})")]+ for fmt, f in (decl.get("formats") or {}).items():+ cfg = next(c for c in configs(decl, sport, seeds=(1,)) if c.format == fmt)+ sides = list(cfg.side_list())+ if len(sides) > 2:+ continue+ seat = next(s for s in cfg.seats if cfg.side_of(s) == sides[-1])+ rows = [{"ev": "header", "cfg": cfg.to_json(), "sport": sport.name, "protocol": sport.protocol},+ {"ev": "forfeit", "k": 0, "seat": seat, "why": "no_show"}, {"ev": "end", "k": 0, "reason": "no_show"}]+ try:+ by = replay(sport, rows, decl=decl)["continuous"]+ ok = by[sides[-1]] == sd["forfeit"] and all(math.isfinite(v) for v in by.values())+ except Exception as exc: # noqa: BLE001+ by, ok = f"{type(exc).__name__}: {exc}"[:300], False+ out.append(row(f"continuous_score:no_show:{fmt}", ok, {"by_side": by, "forfeit": sd["forfeit"]}))+ return out+++def t_seed_private(sport, plugin, decl, seed=987123):+ """core 0.2.14 (core/seeds.py): where the sport itself shows a match's seed (observation, /spec, final fields). For+ information: in a hidden-seed match the core scrubs all three, but a sport should not show the seed at all."""+ import re+ cfg = next(configs(decl, sport, seeds=(seed,)))+ m = sport.build(cfg)+ pat = re.compile(rf"(?<![\d.]){seed}(?![\d.])|\"\w*seed\"")+ where = [name for name, fn in (("observe", lambda: [m.observe(s, None) for s in cfg.seats]),+ ("spec", lambda: local.seat_spec(sport, cfg, cfg.seats[0], m, plugin)),+ ("final_fields", m.final_fields))+ if pat.search(json.dumps(fn(), default=str))]+ return [row("seed_private", True, f"the sport shows the seed in {where} (scrubbed in hidden-seed matches)"+ if where else "the sport shows the seed nowhere")]+++def tests(plugin):+ sport, decl = load_plugin(plugin), spec_mod.load(plugin)+ out = []+ for f in (t_determinism, t_no_draw_and_whitelist, t_mirror, t_pure, t_refuses, t_fuzz, t_budget, t_exploits,+ t_solo_quit, t_prestart_no_show, t_continuous, t_seed_private):+ t = time.time()+ try:+ rows = f(sport, plugin, decl)+ except Exception: # noqa: BLE001+ rows = [row(f.__name__[2:], False, traceback.format_exc()[-800:])]+ for r in rows:+ r["s"] = round(time.time() - t, 1)+ out += rows+ return out+++def advantage(wins: int, games: int, fair: float, lim: float) -> dict:+ """A side's (or a seat's) advantage in percentage points with its 95% confidence interval (normal approximation of+ the win rate). The rule (sport rule 6): FAIL only if the whole interval lies beyond +-lim (a real advantage);+ WARN if the interval is wider than +-lim (too few matches to tell)."""+ p = wins / games if games else fair+ adv = 100.0 * (p - fair)+ h = 196.0 * math.sqrt(max(p * (1 - p), 1e-9) / games) if games else 100.0+ return {"advantage_pp": round(adv, 2), "ci95_pp": round(h, 2), "lo": adv - h, "hi": adv + h,+ "fail": adv - h > lim or adv + h < -lim, "wide": h > lim}+++def fairness(plugin, matches=None):+ """Built-in players on every seat, both first orders, N seeds each: the advantage of the side that starts and of the+ first seat, each with its 95% confidence interval (advantage()); the seeds are fixed, so the check is+ reproducible. A format plays with its declared sides, and the fair share is one over their number (core 0.2.13:+ a team format is two sides, not one side per seat). Turn-based sports (cheap to play) must also play enough+ matches: an interval wider than +-lim FAILS there; realtime sports only WARN (decided 2026-10-06). An explicit+ `matches` (tools/check --quick) only warns."""+ sport, decl = load_plugin(plugin), spec_mod.load(plugin)+ fc = decl.get("fairness") or {}+ pol, lim = fc.get("policy", "reference"), fc.get("max_advantage_pp", 5)+ n = int(matches or fc.get("matches_per_order", 100))+ out = []+ for fmt, f in decl.get("formats", {}).items():+ seats = f["seats"]+ if len(seats) < 2:+ continue+ level = (decl.get("modes") or {}).get("action_levels", ["high"])[0]+ firsts = f.get("first") or seats+ first_wins = seat_wins = games = 0+ for first in firsts:+ for seed in range(1, n + 1):+ cfg = MatchConfig(sport=sport.name, format=fmt, seats=tuple(seats), seed=seed, first=first,+ action_level=level, sides=f.get("sides"))+ r = local.play(sport, cfg, local.make_players(sport, cfg, {s: pol for s in seats}, plugin=plugin),+ plugin=plugin)+ games += 1+ first_wins += r["winner"] == cfg.side_of(first)+ seat_wins += r["winner"] == cfg.side_of(seats[0])+ k = len(set(MatchConfig(sport.name, fmt, tuple(seats), 1, sides=f.get("sides")).side_list()))+ verdicts = {}+ for what, wins in (("first_side", first_wins), ("seat_" + seats[0], seat_wins)):+ verdicts[what] = advantage(wins, games, 1.0 / k, lim)+ wide = any(v["wide"] for v in verdicts.values())+ strict = sport.protocol == "turn" and matches is None+ fail = any(v["fail"] for v in verdicts.values()) or (strict and wide)+ warn = wide and not strict+ r = row(f"fairness:{fmt}", not fail, {"policy": pol, "N": games, "per_order": n, "max_pp": lim,+ **{w: {x: v[x] for x in ("advantage_pp", "ci95_pp")}+ for w, v in verdicts.items()}})+ r["warn"] = warn and not fail+ if r["warn"]:+ r["detail"] += f" -- WARN: the 95% CI is wider than +-{lim} pp; play more matches ([fairness] matches_per_order)"+ if strict and wide and not any(v["fail"] for v in verdicts.values()):+ r["detail"] += f" -- FAIL: turn-based sport, the 95% CI is wider than +-{lim} pp; raise [fairness] matches_per_order"+ out.append(r)+ return out or [row("fairness", True, "no format with two or more sides")]+++def main(argv):+ cmd, plugin = argv[0], os.path.abspath(argv[1])+ res = tests(plugin) if cmd == "tests" else fairness(+ plugin, int(argv[argv.index("--matches") + 1]) if "--matches" in argv else None)+ if "--json" in argv:+ Path(argv[argv.index("--json") + 1]).write_text(json.dumps(res, indent=1))+ for r in res:+ print(f"{('WARN' if r.get('warn') else 'ok ') if r['ok'] else 'FAIL'} {r['name']}: {r['detail']}")+ return 0 if all(r["ok"] for r in res) else 1+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture/plugin.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture/plugin.pynew file mode 100644index 0000000000..b6b40886bc--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture/plugin.py@@ -0,0 +1,108 @@+"""A synthetic realtime world for the core's tests: every entity has a position on a line and a commanded velocity;+a unit ends every UNIT steps (all seats review), the match after UNITS units; a side's score is the sum of its+entities' positions; more than two sides are ranked by score (retired sides last). No physics, no images."""+import os++from core.sport import FINISHED, PLAYING, UNIT_OVER, MatchBase, Phase, Refused, SchemaLayer, sha_json++UNIT, UNITS, ENTITIES = 30, 3, ("e0", "e1")+++class World(MatchBase):+ dt = 0.01++ def __init__(self, cfg):+ self.cfg, self.k, self.u, self.frozen = cfg, 0, 0, False+ self.pos = {f"{s}.{e}": 0.0 for s in cfg.seats for e in ENTITIES}+ self.vel = dict.fromkeys(self.pos, 0.0)+ self.out: list[str] = []++ def schema(self, seat):+ return {"move": {"v": {"type": "number", "min": -1, "max": 1}}}++ def entities(self, seat):+ return ENTITIES++ def apply(self, seat, cmd):+ self.vel[f"{seat}.{cmd['entity']}"] = cmd["v"]+ return {}++ def step(self):+ for key, v in self.vel.items():+ if key.split(".")[0] not in self.retired_seats():+ self.pos[key] = round(self.pos[key] + v, 6)+ self.k += 1+ if self.k % UNIT == 0:+ self.frozen = True+ return [{"kind": "unit_end", "unit": self.u}] # an event (core 0.2.25 logs it as an `event` row)+ return []++ def retired_seats(self):+ return [s for s in self.cfg.seats if self.cfg.side_of(s) in self.out]++ def phase(self):+ if self.k >= UNIT * UNITS:+ return Phase(FINISHED, reason="match_over")+ if self.frozen:+ return Phase(UNIT_OVER, review=tuple(self.cfg.seats), reason="unit")+ return Phase(PLAYING)++ def resume(self):+ self.frozen, self.u = False, self.u + 1++ def unit(self):+ return self.u++ def retire(self, side, why):+ self.out.append(side)+ return True++ def scores(self):+ out = {}+ for s in self.cfg.seats:+ out[self.cfg.side_of(s)] = round(out.get(self.cfg.side_of(s), 0.0) + sum(+ self.pos[f"{s}.{e}"] for e in ENTITIES), 6)+ return out++ def ranking(self):+ sc = self.scores()+ return sorted(sc, key=lambda s: (s in self.out, -sc[s], s))++ def tiebreaks(self):+ if len(self.cfg.side_list()) < 2:+ return [] # one side: solo+ a, b = self.cfg.side_list()[:2]+ return [("score", lambda m: None if m.scores()[a] == m.scores()[b] else+ (a if m.scores()[a] > m.scores()[b] else b)), ("first_side", lambda m: a)]++ def state_digest(self):+ return sha_json({"k": self.k, "pos": self.pos, "out": self.out})++ def observe(self, seat, query=None):+ if query is not None and query.get("view") not in ("near", "far"):+ raise Refused("query.view must be near or far")+ mine = {e: self.pos[f"{seat}.{e}"] for e in ENTITIES}+ extra = {"view": query["view"]} if query else {}+ if query and query["view"] == "far":+ extra["secret_state"] = self.pos # not whitelisted: the core must drop it and record an error+ return {"unit": self.u, "pos": mine, **extra}+++class Layer(SchemaLayer):+ def __init__(self, delay):+ super().__init__()+ self.delay_steps = delay+++class Fixture:+ name, protocol, revision, workers = "fixture", "realtime", "fixture-1", ()+ source_dirs = [os.path.dirname(os.path.abspath(__file__))]++ def build(self, cfg):+ return World(cfg)++ def action_layer(self, level):+ return Layer(int(os.environ.get("FIXTURE_DELAY", "0")))+++SPORT = Fixture()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture/sport.toml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture/sport.tomlnew file mode 100644index 0000000000..eee97c6f64--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture/sport.toml@@ -0,0 +1,17 @@+# The core's realtime test fixture (core/tests/test_core.py): a synthetic world with no physics, written against the+# interface only, that exercises the stage-0 hooks a real sport may use: several seats per side and two entities per+# seat, N sides with a ranking and retirement, a delayed effect, observation queries and the team channel.+[sport]+name = "fixture"+protocol = "realtime"+revision = "fixture-1"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"++[observation]+fields = ["unit", "pos", "view"]++[team_channel]+max_bytes = 40+min_interval_s = 0.2+max_messages = 50diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_images/plugin.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_images/plugin.pynew file mode 100644index 0000000000..0339fecfeb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_images/plugin.py@@ -0,0 +1,103 @@+"""A synthetic turn-protocol game with images for the core's reply-image tests (core 0.2.8): two sides move in turn,+each move v in [0, 1] adds v to the mover's score and puts the mover's block at x = v (TURNS moves each). The scene+is a floor and two mocap blocks; cameras() serves the top view to the seat on turn only, and not while another seat's+review is due (Match.awaiting_review); reply_views() shows the move's result: two frames (the block before and after+the move), camera order."""+import os++from core.sport import FINISHED, PLAYING, LowLayer, MatchBase, Phase, Refused, sha_json++TURNS = 2+XML = ('<mujoco><visual><headlight ambient=".5 .5 .5"/></visual><worldbody><geom type="plane" size="5 5 .1" '+ 'rgba=".3 .5 .3 1"/><body mocap="true" pos="0 0 .1"><geom type="box" size=".1 .1 .1" rgba="1 0 0 1"/></body>'+ '<body mocap="true" pos="0 1 .1"><geom type="box" size=".1 .1 .1" rgba="0 0 1 1"/></body></worldbody></mujoco>')+TOP = {"name": "top", "pos": [0.5, 0.5, 4], "lookat": [0.5, 0.5, 0], "up": [1, 0, 0], "fovy_deg": 50, "width": 80,+ "height": 60}+++class Game(MatchBase):+ def __init__(self, cfg):+ self.cfg, self.k = cfg, 0+ self.order = list(cfg.seats) if cfg.first in (None, cfg.seats[0]) else list(cfg.seats)[::-1]+ self.score = dict.fromkeys(cfg.seats, 0.0)+ self.x = dict.fromkeys(cfg.seats, 0.0)+ self.moves = dict.fromkeys(cfg.seats, 0)+ self.before = None # the mover's block before its last move++ def schema(self, seat):+ return {"add": {"v": {"type": "number", "min": 0, "max": 1}}}++ def apply(self, seat, cmd):+ self.before = dict(self.x)+ self.score[seat] = round(self.score[seat] + cmd["v"], 6)+ self.x[seat] = cmd["v"]+ self.moves[seat] += 1+ self.k += 1+ return {"moved": seat}++ def to_move(self):+ if self.phase().state == FINISHED:+ return None+ return min(self.order, key=lambda s: (self.moves[s], self.order.index(s)))++ def phase(self):+ return Phase(FINISHED, reason="match_over") if all(n >= TURNS for n in self.moves.values()) else Phase(PLAYING)++ def scores(self):+ return dict(self.score)++ def tiebreaks(self):+ a, b = self.order[:2]+ return [("score", lambda m: None if m.score[a] == m.score[b] else (a if m.score[a] > m.score[b] else b)),+ ("first", lambda m: a)]++ def state_digest(self):+ return sha_json({"k": self.k, "score": self.score, "x": self.x})++ def observe(self, seat, query=None):+ return {"unit": self.k, "pos": self.x[seat]}++ def cameras(self, seat, query=None):+ if seat != self.to_move() or self.awaiting_review not in (None, seat):+ return []+ return [TOP]++ def state_of(self, x):+ s = list(self.cfg.seats)+ return {"qpos": [], "mocap_pos": [[x[s[0]], 0.0, 0.1], [x[s[1]], 1.0, 0.1]],+ "mocap_quat": [[1, 0, 0, 0], [1, 0, 0, 0]]}++ def render_state(self):+ return self.state_of(self.x)++ def reply_views(self, seat, cmd, info):+ return {"frames": [{"cameras": [TOP], "state": self.state_of(self.before), "label": "before"},+ {"cameras": [TOP], "label": "after"}], "note": "your block before and after the move"}+++def validate(seat, body, match, ctx):+ try:+ v = float(body.get("v"))+ except (TypeError, ValueError):+ raise Refused("v must be a number") from None+ if not 0 <= v <= 1:+ raise Refused("v must be in [0, 1]")+ return {"type": "add", "v": v}+++class Fixture:+ name, protocol, revision, workers = "fixture_images", "turn", "fixture-images-1", ()+ source_dirs = [os.path.dirname(os.path.abspath(__file__))]++ def build(self, cfg):+ return Game(cfg)++ def action_layer(self, level):+ return LowLayer(validate)++ def scene(self, cfg):+ from renderers.base import Scene+ return Scene(xml=XML)+++SPORT = Fixture()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_images/sport.toml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_images/sport.tomlnew file mode 100644index 0000000000..b1237e9197--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_images/sport.toml@@ -0,0 +1,13 @@+# The core's reply-image test fixture (core/tests/test_core.py, core 0.2.8): the turn fixture's game with a tiny+# MuJoCo scene: each move puts the mover's block at x = v; cameras for the seat on turn; reply images of the move.+[sport]+name = "fixture_images"+protocol = "turn"+revision = "fixture-images-1"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"++[observation]+fields = ["unit", "pos"]+columns = 2+reply_images = "the top camera after the move"diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_turn/plugin.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_turn/plugin.pynew file mode 100644index 0000000000..4fbe331bcb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_turn/plugin.py@@ -0,0 +1,106 @@+"""A synthetic turn-protocol game for the core's tests: the sides move in turn (the first side first), each move adds+v in [0, 1] to the mover's side score; the match ends when every side still in has made TURNS moves. Two sides are+decided by score, then the first side; more sides are ranked by score (retired sides last). The built-in player adds+0.5 on every turn (the fairness check, core/testkit.py). No physics, no images."""+import os++from core.sport import FINISHED, PLAYING, LowLayer, MatchBase, Phase, Refused, sha_json++TURNS = 2+++class Game(MatchBase):+ def __init__(self, cfg):+ self.cfg, self.k = cfg, 0+ sides = cfg.side_list()+ first = cfg.side_of(cfg.first) if cfg.first in cfg.seats else (cfg.first or sides[0])+ i = sides.index(first) if first in sides else 0+ self.order = sides[i:] + sides[:i]+ self.score = dict.fromkeys(sides, 0.0)+ self.moves = dict.fromkeys(sides, 0)+ self.out: list[str] = []++ def schema(self, seat):+ return {"add": {"v": {"type": "number", "min": 0, "max": 1}}}++ def apply(self, seat, cmd):+ side = self.cfg.side_of(seat)+ self.score[side] = round(self.score[side] + cmd["v"], 6)+ self.moves[side] += 1+ self.k += 1+ return {}++ def live(self):+ return [s for s in self.order if s not in self.out]++ def to_move(self):+ if self.phase().state == FINISHED:+ return None+ side = min(self.live(), key=lambda s: (self.moves[s], self.order.index(s)))+ return self.cfg.seats_of(side)[0]++ def phase(self):+ if all(self.moves[s] >= TURNS for s in self.live()):+ return Phase(FINISHED, reason="match_over")+ return Phase(PLAYING)++ def retire(self, side, why):+ self.out.append(side)+ return True++ def scores(self):+ return dict(self.score)++ def ranking(self):+ return sorted(self.score, key=lambda s: (s in self.out, -self.score[s], self.order.index(s)))++ def tiebreaks(self):+ if len(self.order) < 2:+ return [] # one side: solo+ a, b = self.order[:2]+ return [("score", lambda m: None if m.score[a] == m.score[b] else (a if m.score[a] > m.score[b] else b)),+ ("first_side", lambda m: a)]++ def state_digest(self):+ return sha_json({"k": self.k, "score": self.score, "moves": self.moves, "out": self.out})++ def final_fields(self): # a sport that records its seed (core/seeds.py scrub test)+ return {"seed": self.cfg.seed, "draws": [self.cfg.seed, 1]}++ def observe(self, seat, query=None):+ return {"unit": self.k, "pos": self.score[self.cfg.side_of(seat)]}+++def validate(seat, body, match, ctx):+ try:+ v = float(body.get("v"))+ except (TypeError, ValueError):+ raise Refused("v must be a number") from None+ if not 0 <= v <= 1:+ raise Refused("v must be in [0, 1]")+ return {"type": "add", "v": v}+++class Steady:+ def __init__(self, spec, seat, seed):+ pass++ def act(self, view):+ return {"type": "add", "v": 0.5}+++class Fixture:+ name, protocol, revision, workers = "fixture_turn", "turn", "fixture-turn-1", ()+ source_dirs = [os.path.dirname(os.path.abspath(__file__))]++ def build(self, cfg):+ return Game(cfg)++ def action_layer(self, level):+ return LowLayer(validate)++ def players(self):+ return {"reference": Steady}+++SPORT = Fixture()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_turn/sport.toml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_turn/sport.tomlnew file mode 100644index 0000000000..9a1e51bb07--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/fixture_turn/sport.toml@@ -0,0 +1,24 @@+# The core's turn-protocol test fixture (core/tests/test_core.py): a synthetic game with no physics, written against+# the interface only: the sides take turns adding a number to their score; N sides with a ranking and retirement;+# a team format whose sides are not its seats (the fairness check, core/testkit.py).+[sport]+name = "fixture_turn"+protocol = "turn"+revision = "fixture-turn-1"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"++[observation]+fields = ["unit", "pos"]++[formats.team]+seats = ["A1", "A2", "B1", "B2"]+sides = { A1 = "A", A2 = "A", B1 = "B", B2 = "B" }+first = ["A", "B"]++[score] # core 0.2.14: the continuous score (core/score.py), checked through the turn tests+name = "score_share"+text = "the side's share of all points scored"+from = "share"+forfeit = 0.0+range = [0, 1]diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/test_core.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/test_core.pynew file mode 100644index 0000000000..aee2e901ad--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/test_core.py@@ -0,0 +1,2044 @@+"""Unit tests of the core's stage-0 hooks on the synthetic realtime fixture (core/tests/fixture), of the start window+(no-show rule, at the window and at a collect before the start, both protocols; turn fixture core/tests/fixture_turn) and of the outcome and grading rules. Standard library + numpy; run in the sim image:+ docker run --rm -v $PWD:/w -w /w ghcr.io/mll-lab-nu/eai-olympiad:0.1.0 \\+ python3 core/tests/test_core.py+"""+from __future__ import annotations++import json+import os+import shutil+import sys+import tempfile+import threading+import time+import traceback+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+os.environ.update(READY_TIMEOUT_S="1.5", START_TIMEOUT_S="5", BARRIER_LEAD_S="0.05")++from core.episode import load_plugin # noqa: E402+from core.grading import grade, line_ok # noqa: E402+from core.outcome import decide # noqa: E402+from core.realtime import RealtimeService # noqa: E402+from core.sport import FINISHED, PLAYING, MatchConfig, Phase, Refused # noqa: E402+from core.turn import TurnService # noqa: E402++PLUGIN = str(Path(__file__).resolve().parent / "fixture" / "plugin.py")+SPORT = load_plugin(PLUGIN)+PLUGIN_TURN = str(Path(__file__).resolve().parent / "fixture_turn" / "plugin.py")+SPORT_TURN = load_plugin(PLUGIN_TURN)+++def service(seats, sides=None, fmt="team"):+ for s in seats:+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format=fmt, seats=tuple(seats), seed=1, slowdown=1.0, sides=sides)+ svc = RealtimeService(SPORT, PLUGIN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ return svc, svc.routes(True)+++def turn_service(seats, sides=None, fmt="duel"):+ for s in seats:+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture_turn", format=fmt, seats=tuple(seats), seed=1, first=seats[0], sides=sides,+ action_level="low")+ svc = TurnService(SPORT_TURN, PLUGIN_TURN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ return svc, svc.routes(True)+++def play_turn(svc, post, seat, v=0.5):+ """One seat's turn loop: start, then on its turn act (v) and review, until the end."""+ post["start"](seat, {})+ while svc.phase != "over":+ st = post["wait"](seat, {"timeout_s": 1})[1]["state"]+ if st["done"] or not st["your_turn"]:+ continue+ if st["awaiting_review"]:+ post["ready"](seat, {"why": "w", "plan": "p"})+ else:+ post["act"](seat, {"v": v})+++def play(svc, post, seat, review=True, act=None):+ """One seat's loop: start, then act (act(seat, post) each round) and review at every unit end until the end."""+ post["start"](seat, {})+ while svc.phase != "over":+ if svc.phase == "review":+ if review and not svc.seats[seat].ready and seat in svc.due():+ post["ready"](seat, {"why": "w", "plan": "p"})+ time.sleep(0.01)+ continue+ if svc.phase == "running" and act:+ act(seat, post)+ time.sleep(0.01)+++def finish(svc, timeout=60):+ t = time.time()+ while not svc.finalized and time.time() - t < timeout:+ time.sleep(0.1)+ return json.loads((svc.data / "final.json").read_text())+++def run_all(svc, post, seats, **kw):+ th = [threading.Thread(target=play, args=(svc, post, s), kwargs=kw.get(s, {}), daemon=True) for s in seats]+ for t in th:+ t.start()+ return finish(svc)+++def test_seats_sides_entities_and_team_channel():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ svc, post = service(list(sides), sides)+ th = [threading.Thread(target=post["start"], args=(s, {}), daemon=True) for s in sides]+ for t in th:+ t.start()+ while svc.phase != "running":+ time.sleep(0.01)+ lock = svc.seats["A1"].act_lock("e0")+ lock.acquire() # an act of A1's entity e0 is in flight+ try:+ assert post["act"]("A1", {"type": "move", "v": 0.5, "entity": "e0"})[0] == 429+ code, out = post["act"]("A1", {"type": "move", "v": 0.5, "entity": "e1"}) # another entity: accepted+ assert code == 200, out+ finally:+ lock.release()+ try:+ post["act"]("A1", {"type": "move", "v": 0.5, "entity": "e9"})+ raise AssertionError("unknown entity accepted")+ except Refused:+ pass+ assert post["say"]("A1", {"text": "x" * 41})[0] == 400 # longer than max_bytes+ assert post["say"]("A1", {"text": "press high"})[0] == 200+ assert post["say"]("A1", {"text": "again"})[0] == 429 # min_interval_s in game time+ time.sleep(0.05)+ get = svc.routes(False)+ a2 = get["status"]("A2", {})[1]+ b1 = get["status"]("B1", {})[1]+ assert [m["text"] for m in a2["team_messages"]] == ["press high"] and a2["team_messages"][0]["from"] == "A1"+ assert a2["team_messages"][0]["seq"] == 1 and a2["team_seq"] == 1+ assert b1["team_messages"] == [] and b1["team_seq"] == 0 # never shown to the other side+ # core 0.2.20: reading never consumes: a second client of the same seat (the agent's own status, a monitor)+ # sees the same message; a read mark gives only newer ones; the sender never gets its own message back+ again = get["status"]("A2", {})[1]+ assert [m["text"] for m in again["team_messages"]] == ["press high"]+ assert get["status"]("A2", {"team_since": 1})[1]["team_messages"] == []+ assert get["status"]("A1", {})[1]["team_messages"] == [] and get["status"]("A1", {})[1]["team_seq"] == 1+ assert post["team"]("A2", {"since": 0})[1]["messages"][0]["text"] == "press high"+ assert post["team"]("B1", {})[1]["messages"] == []+ for bad in (-1, 1.5, "x", [1], True):+ try:+ get["status"]("A2", {"team_since": bad})+ raise AssertionError(f"read mark {bad!r} accepted")+ except Refused:+ pass+ th = [threading.Thread(target=play, args=(svc, post, s), daemon=True) for s in sides]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["match_winner"] == "home" and fin["sides"]["A2"] == "home" and fin["team_messages"] == 1+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "team" and r["text"] == "press high" for r in rows)+ cmds = [r for r in rows if r["ev"] == "cmd"]+ assert cmds and cmds[0]["cmd"]["entity"] == "e1"+++def test_n_sides_ranking_and_retirement():+ svc, post = service(["A", "B", "C"], fmt="multi")++ def mover(v):+ return lambda seat, p: p["act"](seat, {"type": "move", "v": v, "entity": "e0"})+ fin = run_all(svc, post, ["A", "B", "C"], A={"act": mover(0.2)}, B={"act": mover(0.1)},+ C={"act": mover(0.9), "review": False}) # C never reviews: it retires, A and B play on+ assert fin["retired"] == ["C"] and fin["reason"] == "match_over", fin+ assert fin["ranking"] == ["A", "B", "C"] and fin["match_winner"] == "A"+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "retire" and r["side"] == "C" for r in rows)+ r = {"cfg": fin["cfg"], **fin}+ out = grade(r, json.loads((svc.data / "replay_check.json").read_text()), {}, lambda d: {})+ assert out["A_place"] == 1 and out["C_place"] == 3 and out["A_won"] == 1 and out["success"] == 1+++def test_delayed_effect_is_logged_at_its_step():+ os.environ["FIXTURE_DELAY"] = "3"+ try:+ svc, post = service(["A", "B"], fmt="duel")+ got = []++ def act(seat, p):+ if seat == "A" and not got:+ got.append(p["act"](seat, {"type": "move", "v": 0.3, "entity": "e0"}))+ fin = run_all(svc, post, ["A", "B"], A={"act": act})+ finally:+ os.environ.pop("FIXTURE_DELAY")+ code, out = got[0]+ assert code == 200, out+ eff = out["took_effect"]+ assert eff["effect_step"] == eff["step"] + 3+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ cmd = next(r for r in rows if r["ev"] == "cmd" and r["seat"] == "A")+ assert cmd["k"] == eff["effect_step"]+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ rc = fin["reaction"] # core 0.2.23: the layer's delay is part of the report+ assert rc["effect_delay_steps"] == 3 and rc["by_seat"]["A"]["acts"] == 1 and rc["replayed"] is True, rc+ assert rc["by_seat"]["A"]["delay_steps"]["max"] == cmd["k"] - cmd["seen"] >= 3, (rc, cmd)+++def fixture_with_reaction_delay(D):+ """A copy of the realtime fixture whose sport.toml declares [timing] reaction_delay_steps = D (core 0.2.18)."""+ import shutil+ d = Path(tempfile.mkdtemp(prefix="core-test-react-")) / "fixture"+ shutil.copytree(Path(PLUGIN).parent, d, ignore=shutil.ignore_patterns("__pycache__"))+ (d / "sport.toml").write_text((d / "sport.toml").read_text() + f"\n[timing]\nreaction_delay_steps = {D}\n")+ return str(d / "plugin.py")+++def test_reaction_delay_rule():+ """core 0.2.18: with a declared reaction delay D an act takes effect at max(the next boundary, s + D), s = the+ step of the latest world state the seat was sent (an observation or any reply's `now`); the effect step is+ logged and replayed (deterministic); the same D for every seat; /spec shows it."""+ from core import spec as spec_mod+ assert spec_mod.reaction_delay({}) == 0 and spec_mod.reaction_delay({"timing": {"reaction_delay_steps": 3}}) == 3+ for bad in (-1, 2.0, True, "2"):+ try:+ spec_mod.reaction_delay({"timing": {"reaction_delay_steps": bad}})+ raise AssertionError(f"accepted {bad!r}")+ except ValueError:+ pass+ D, plugin = 4, fixture_with_reaction_delay(4)+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=5.0) # 50 ms per step+ svc = RealtimeService(load_plugin(plugin), plugin, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ assert svc.spec("A")[1]["timing"]["reaction_delay_steps"] == D+ got = []++ def act(seat, p):+ if len(got) >= 6 or svc.phase != "running":+ return+ code, ob = p["observe"](seat, {})+ if code != 200 or ob["now"]["phase"] != "running":+ return+ code, out = p["act"](seat, {"type": "move", "v": 0.1, "entity": "e0"})+ if code != 200:+ return+ got.append(("observe", ob["now"]["step"], out["took_effect"]))+ code, out2 = p["act"](seat, {"type": "move", "v": 0.2, "entity": "e0"}) # answers the act reply's `now`+ if code == 200:+ got.append(("act", out["now"]["step"], out2["took_effect"]))+ fin = run_all(svc, post, ["A", "B"], A={"act": act})+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert len(got) >= 4, got+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ ks = [r["k"] for r in rows if r["ev"] == "cmd" and r["seat"] == "A"]+ for kind, seen, eff in got:+ assert eff["seen_step"] == seen and eff["reaction_delay_steps"] == D, (kind, seen, eff)+ assert eff["step"] >= seen + D, (kind, seen, eff) # never earlier than s + D+ assert eff["step"] in ks, (eff, ks) # the logged (replayed) step is the effect step+ exact = sum(eff["step"] == seen + D for _, seen, eff in got)+ assert exact >= len(got) - 1, got # a fast program gets exactly D (50 ms per step)+++def test_reaction_delay_undeclared_unchanged():+ """No declaration: D = 0 in /spec, an act takes effect at the next control-step boundary, its reply as before."""+ svc, post = service(["A", "B"], fmt="duel")+ assert svc.react == 0 and svc.spec("A")[1]["timing"]["reaction_delay_steps"] == 0+ got = []++ def act(seat, p):+ if not got and svc.phase == "running":+ code, ob = p["observe"](seat, {})+ code, out = p["act"](seat, {"type": "move", "v": 0.3, "entity": "e0"})+ if code == 200:+ got.append((ob["now"]["step"], out["took_effect"]))+ fin = run_all(svc, post, ["A", "B"], A={"act": act})+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ seen, eff = got[0]+ assert "seen_step" not in eff and "reaction_delay_steps" not in eff and eff["step"] < seen + 4, got+++def test_reaction_delay_local_play_deterministic():+ """core/local.py plays by the same rule: an act answers the observation at k and takes effect at k + D; two runs+ give the same state digest, the episode replays to it in a fresh replay, and without the declaration the+ commands are where they were before (at the observation step)."""+ from core import local+ from core.episode import read_rows, replay++ class Mover:+ def __init__(self):+ self.n = 0++ def act(self, view):+ self.n += 1+ return {"type": "move", "entity": "e0", "v": round(0.1 * (self.n % 7) - 0.3, 3)}++ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=1.0)+ out = {}+ for name, plugin in (("D3", fixture_with_reaction_delay(3)), ("D3 again", fixture_with_reaction_delay(3)),+ ("none", PLUGIN)):+ d = Path(tempfile.mkdtemp(prefix="core-test-"))+ r = local.play(SPORT, cfg, {"A": Mover(), "B": Mover()}, data=d, render=False, plugin=plugin)+ rows = read_rows(d / "episode.jsonl")+ rep = replay(SPORT, rows)+ assert rep["state_sha"] == r["digest"] and rep["scores"] == r["scores"], (name, rep, r)+ out[name] = (r["digest"], [x["k"] for x in rows if x["ev"] == "cmd"])+ assert out["D3"] == out["D3 again"]+ assert out["D3"][1] and all(k % 5 == 3 for k in out["D3"][1]), out["D3"][1][:10]+ assert out["none"][1] and all(k % 5 == 0 for k in out["none"][1]) and out["none"][0] != out["D3"][0]+++def reaction_match(plugin, slow_s=0.35, slowdown=5.0, n=8):+ """A duel on the fixture at 50 ms per step: seat A is a fast player (acts right after each observation), seat B a+ slow one (thinks slow_s wall seconds between its observation and its act). Returns final.json, replay_check.json,+ the episode rows and what each act's reply said."""+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=slowdown)+ svc = RealtimeService(load_plugin(plugin), plugin, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ got = {"A": [], "B": []}++ def player(think):+ def act(seat, p):+ if len(got[seat]) >= n or svc.phase != "running":+ return+ code, ob = p["observe"](seat, {})+ if code != 200 or ob["now"]["phase"] != "running":+ return+ time.sleep(think)+ code, out = p["act"](seat, {"type": "move", "v": 0.1, "entity": "e0"})+ if code == 200:+ got[seat].append((ob["now"]["step"], out["took_effect"]))+ return act+ os.environ["READY_TIMEOUT_S"] = "5" # a loaded host: the slow seat still reviews in time+ try:+ fin = run_all(svc, post, ["A", "B"], A={"act": player(0.0)}, B={"act": player(slow_s)})+ finally:+ os.environ["READY_TIMEOUT_S"] = "1.5"+ assert fin["valid_trial"], {k: fin.get(k) for k in ("reason", "phase", "finalized", "deterministic", "errors")}+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ return fin, json.loads((svc.data / "replay_check.json").read_text()), rows, got+++def check_reaction_report(fin, rep, rows, D):+ """final.json `reaction` = the rows' numbers = the replay's, and grading never sees it."""+ from core.episode import reaction_report+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ r = fin["reaction"]+ assert r["policy"] == "report_only" and r["reaction_delay_steps"] == D and r["replayed"] is True, r+ assert rep["reaction"]["by_seat"] == r["by_seat"], (rep["reaction"], r)+ head = next(x for x in rows if x["ev"] == "header")+ assert head["timing"] == {"reaction_delay_steps": D, "effect_delay_steps": 0}, head+ assert reaction_report(rows, ("A", "B"), D)["by_seat"] == r["by_seat"]+ for seat in ("A", "B"):+ lags = sorted(x["k"] - x["seen"] for x in rows if x["ev"] == "cmd" and x["seat"] == seat+ and x.get("seen") is not None)+ b = r["by_seat"][seat]+ assert b["acts"] == len(lags) > 0 and b["within_d"] == sum(d <= D for d in lags), (seat, b, lags)+ assert b["share"] == round(b["within_d"] / b["acts"], 6) and b["delay_steps"]["max"] == lags[-1], b+ out = grade({"cfg": fin["cfg"], **fin}, rep, {}, lambda d: {})+ assert not any("reaction" in k or "within" in k for k in out), sorted(out)+ return r["by_seat"]+++def test_reaction_report_declared_delay():+ """core 0.2.23 (report only): with D declared, a fast player's acts all take effect within D (exactly D), a slow+ player's (0.35 s of thinking = 7 steps at 50 ms) none; final.json gives the counts, the share and the delay's+ median / p90 / max per seat, the fresh-process replay recomputes the same numbers, grading ignores them."""+ D = 2+ fin, rep, rows, got = reaction_match(fixture_with_reaction_delay(D))+ by = check_reaction_report(fin, rep, rows, D)+ a, b = by["A"], by["B"]+ assert a["within_d"] >= a["acts"] - 1 and a["delay_steps"]["median"] == D, a # D exactly when fast+ assert b["within_d"] == 0 and b["share"] == 0 and b["delay_steps"]["median"] >= D + 3, b+ for seen, eff in got["B"]: # the replies agree with the report+ assert eff["seen_step"] == seen and eff["step"] - seen > D, (seen, eff)+++def test_reaction_report_without_declared_delay():+ """D = 0 (not declared): within D means the next control-step boundary after the seen state; the slow player is+ never within it; the act replies are unchanged (no seen_step), the report is in final.json and the replay."""+ fin, rep, rows, got = reaction_match(PLUGIN)+ by = check_reaction_report(fin, rep, rows, 0)+ assert by["B"]["within_d"] == 0 and by["B"]["delay_steps"]["median"] >= 4, by["B"]+ assert by["A"]["delay_steps"]["median"] <= 1, by["A"]+ assert all("seen_step" not in eff for _, eff in got["A"] + got["B"])+++def test_reaction_report_rule_and_old_episodes():+ """reaction_report on rows: the layer's fixed effect delay counts as part of D; ticks (no `seen`) are not acts; an+ act whose seat had been sent no world state is `unseen`; an episode before 0.2.23 gives empty seats."""+ from core.episode import reaction_report+ rows = [{"ev": "cmd", "k": 10, "seat": "A", "cmd": {}, "seen": 7}, {"ev": "cmd", "k": 11, "seat": "A", "cmd": {}},+ {"ev": "cmd", "k": 20, "seat": "A", "cmd": {}, "seen": 14}, {"ev": "cmd", "k": 21, "seat": "B", "cmd": {},+ "seen": None}]+ r = reaction_report(rows, ("A", "B"), 2, 1)["by_seat"]+ assert r["A"] == {"acts": 2, "within_d": 1, "share": 0.5, "delay_steps": {"median": 4.5, "p90": 6, "max": 6},+ "unseen": 0}, r+ assert r["B"] == {"acts": 0, "within_d": 0, "share": None, "delay_steps": None, "unseen": 1}, r+ old = reaction_report([{"ev": "cmd", "k": 3, "seat": "A", "cmd": {}}], ("A",), 0)["by_seat"]+ assert old == {"A": {"acts": 0, "within_d": 0, "share": None, "delay_steps": None, "unseen": 0}}, old+++def test_local_play_team_channel_of_builtin_players():+ """core 0.2.21: a built-in player's optional message(view) goes on the team channel in local play as POST /say+ would (the channel's limits; a refused message is dropped), reaches its teammates' views (team_messages) and never+ the other side, is a `team` row of the episode, and changes nothing the replay sees."""+ from core import local+ from core.episode import read_rows, replay++ class Talker:+ def __init__(self, seat):+ self.seat, self.heard, self.n = seat, [], 0++ def act(self, view):+ self.heard += [(m["from"], m["text"]) for m in view["state"].get("team_messages") or []]+ self.n += 1+ return {"type": "move", "entity": "e0", "v": 0.1}++ def message(self, view):+ return f"{self.seat} {self.n}" if self.seat.endswith("1") else None++ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ cfg = MatchConfig(sport="fixture", format="team", seats=tuple(sides), seed=1, slowdown=1.0, sides=sides)+ d = Path(tempfile.mkdtemp(prefix="core-test-"))+ players = {s: Talker(s) for s in sides}+ r = local.play(SPORT, cfg, players, data=d, render=False, plugin=PLUGIN)+ rows = read_rows(d / "episode.jsonl")+ team = [x for x in rows if x["ev"] == "team"]+ assert team and {x["seat"] for x in team} == {"A1", "B1"}, team[:3]+ ks = [x["k"] for x in team if x["seat"] == "A1"]+ assert all(b - a >= 0.2 / SPORT.build(cfg).dt - 1e-9 for a, b in zip(ks, ks[1:])), ks[:5] # min_interval_s+ assert players["A2"].heard and all(f == "A1" for f, _ in players["A2"].heard)+ assert players["B2"].heard and all(f == "B1" for f, _ in players["B2"].heard)+ assert not players["A1"].heard and not players["B1"].heard # never their own, never the others'+ rep = replay(SPORT, rows)+ assert rep["state_sha"] == r["digest"] and rep["scores"] == r["scores"]+++def test_preview_format_is_never_official():+ """core 0.2.21: a format declared preview ([formats.<f>] preview = true, in the contract's formats) is never an+ official configuration, whatever its seed, level and first player; the same match in a non-preview format is."""+ from core.grading import official+ d = {"format": "tm", "seed": 202, "first": "A", "slowdown": 10.0, "play": "program",+ "cfg": {"seats": ["A1", "A2"], "level": 2}, "sides": {"A1": "A", "A2": "A"}}+ contract = {"official": {"seeds": [202], "levels": [2, 3], "first_any": True},+ "formats": {"tm": {"seats": ["A1", "A2"], "opponent": True, "preview": True}}}+ assert not official(d, contract)+ contract["formats"]["tm"].pop("preview")+ assert official(d, contract)+++def test_observation_query_and_runtime_whitelist():+ svc, post = service(["A", "B"], fmt="duel")+ th = [threading.Thread(target=post["start"], args=(s, {}), daemon=True) for s in "AB"]+ for t in th:+ t.start()+ while svc.phase != "running":+ time.sleep(0.01)+ code, out = post["observe"]("A", {"query": {"view": "near"}})+ assert code == 200 and out["now"]["view"] == "near"+ for bad in ({"query": {"view": "sideways"}}, {"query": "near"}):+ try:+ post["observe"]("A", bad)+ raise AssertionError(f"query {bad} accepted")+ except Refused:+ pass+ code, out = post["observe"]("A", {"query": {"view": "far"}}) # the sport leaks a field: dropped + error+ assert code == 200 and "secret_state" not in out["now"]+ assert any(e["where"] == "observation" for e in svc.errors)+ svc.end("collected")+ fin = finish(svc)+ assert not fin["valid_trial"]+++class start_window:+ """START_TIMEOUT_S for one test."""+ def __init__(self, s):+ self.s = s++ def __enter__(self):+ self.old, os.environ["START_TIMEOUT_S"] = os.environ.get("START_TIMEOUT_S"), str(self.s)++ def __exit__(self, *a):+ os.environ["START_TIMEOUT_S"] = self.old+++def graded(svc, fin):+ return grade(fin, json.loads((svc.data / "replay_check.json").read_text()), {}, lambda d: {})+++def check_no_show(svc, fin, absent="B", winner="A"):+ """The side that never started lost by forfeit, the trial is valid and replays; the grader agrees."""+ assert fin["reason"] == "no_show" and fin["forfeiting"] == absent, fin+ assert fin["match_winner"] == winner and fin["winner"] == winner and fin["decided_by"] == "forfeit:no_show"+ assert fin["valid_trial"] and fin["deterministic"] and not fin["technical_failure"], fin["errors"]+ assert fin["joined"][absent] is False and fin["steps"] == 0+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "forfeit" and r["seat"] == absent and r["why"] == "no_show" for r in rows)+ out = graded(svc, fin)+ assert out["valid_trial"] == 1 and out["success"] == 1 and out["no_show"] == 1, out+ assert out[f"{winner}_won"] == 1 and out[f"{absent}_won"] == 0 and out[f"{absent}_no_show"] == 1+ assert out[f"{winner}_no_show"] == 0+++def test_no_show_realtime_duel_present_side_wins():+ with start_window(1):+ svc, post = service(["A", "B"], fmt="duel")+ threading.Thread(target=post["start"], args=("A", {}), daemon=True).start() # B never starts+ fin = finish(svc)+ assert svc.spec("A")[1]["start"]["window_s"] == 1.0+ check_no_show(svc, fin)+++def test_no_show_turn_duel_present_side_wins():+ with start_window(1):+ svc, post = turn_service(["A", "B"])+ assert post["start"]("B", {})[0] == 200 # A never starts+ fin = finish(svc)+ check_no_show(svc, fin, absent="A", winner="B")+ assert "start" in svc.spec("B")[1]+++def test_no_show_turn_duel_late_start_refused():+ with start_window(1):+ svc, post = turn_service(["A", "B"])+ post["start"]("A", {})+ fin = finish(svc)+ assert post["start"]("B", {})[0] == 409 # the window has closed+ check_no_show(svc, fin)+++def test_no_show_nobody_started_is_invalid():+ for make, reason in ((lambda: service(["A", "B"], fmt="duel"), "collected"),+ (lambda: turn_service(["A", "B"]), "incomplete")):+ svc, post = make()+ time.sleep(0.6)+ svc.collect() # the session ends, nobody started+ fin = finish(svc)+ assert fin["reason"] == reason and fin["winner"] is None and fin["match_winner"] is None, fin+ assert not fin["valid_trial"] and fin["forfeiting"] is None+ out = graded(svc, fin)+ assert out["valid_trial"] == 0 and out["success"] == 0 and out["no_show"] == 0+++def test_no_show_every_side_absent_after_the_window_is_invalid():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ with start_window(1): # one home seat started: no side complete when the window closes+ svc, post = service(list(sides), sides)+ threading.Thread(target=post["start"], args=("A1", {}), daemon=True).start()+ fin = finish(svc)+ assert fin["reason"] == "incomplete" and fin["winner"] is None and not fin["valid_trial"], fin+ with start_window(1):+ svc, post = turn_service(list(sides), sides, fmt="team")+ post["start"]("B2", {})+ fin = finish(svc)+ assert fin["reason"] == "incomplete" and fin["winner"] is None and not fin["valid_trial"], fin+++def test_no_show_team_side_with_a_missing_seat_loses():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ with start_window(1):+ svc, post = turn_service(list(sides), sides, fmt="team")+ for s in ("A1", "B1", "B2"): # A2 never starts+ post["start"](s, {})+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["forfeiting"] == "A2" and fin["match_winner"] == "away", fin+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++def check_single_no_show(svc, fin):+ """A single side that never started: a valid loss by forfeit (no_show), replayed; success 0."""+ assert fin["reason"] == "no_show" and fin["forfeiting"] == "A" and fin["winner"] is None, fin+ assert fin["valid_trial"] and fin["deterministic"] and fin["decided_by"] == "forfeit:no_show", fin["errors"]+ assert fin["joined"]["A"] is False and fin["steps"] == 0, fin+ out = graded(svc, fin)+ assert out["valid_trial"] == 1 and out["success"] == 0 and out["no_show"] == 1 and out["A_no_show"] == 1, out+ assert out["A_won"] == 0 and out["abandoned"] == 0, out+++def test_no_show_single_player_valid_loss():+ """One side: the window opens at the service start; not started when it closes = a valid loss (no_show, success+ 0). A session that ends before the window closes is the same valid loss, decided at the collect (core 0.2.7)."""+ for make in (lambda: service(["A"], fmt="single"), lambda: turn_service(["A"], fmt="single")):+ with start_window(1):+ svc, post = make()+ fin = finish(svc)+ check_single_no_show(svc, fin)+ assert fin["elapsed_s"] >= 0.9, fin["elapsed_s"]+++# ---------------------------------------------- a session that ends before its side started (core 0.2.7, core rule 5)+def collect_rows(svc):+ return [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()+ if json.loads(x)["ev"] == "collect_before_start"]+++def test_prestart_single_collected_before_the_window_is_no_show():+ """The single side's session ends inside the start window (5 s here) without a start: no_show at once, a valid+ loss (cores 0.2.2-0.2.6: an unfinished, invalid match, "collected" / "incomplete")."""+ for make in (lambda: service(["A"], fmt="single"), lambda: turn_service(["A"], fmt="single")):+ svc, post = make()+ time.sleep(0.3)+ t = time.time()+ svc.collect()+ fin = finish(svc)+ check_single_no_show(svc, fin)+ assert time.time() - t < 4, "decided at the collect, not when the window closes"+ assert collect_rows(svc) and collect_rows(svc)[0]["absent"] == ["A"]+++def test_prestart_duel_collected_before_the_window_absent_side_loses():+ """Two sides, one started, the other never; the sessions end inside the window: the absent side loses (no_show,+ valid), the present side wins, as when the window closes (core rule 5)."""+ svc, post = service(["A", "B"], fmt="duel")+ threading.Thread(target=post["start"], args=("A", {}), daemon=True).start() # B never starts+ t = time.time()+ while not svc.seats["A"].joined and time.time() - t < 5:+ time.sleep(0.01)+ svc.collect()+ fin = finish(svc)+ check_no_show(svc, fin)+ svc, post = turn_service(["A", "B"])+ assert post["start"]("B", {})[0] == 200 # A never starts+ svc.collect()+ fin = finish(svc)+ check_no_show(svc, fin, absent="A", winner="B")+ assert collect_rows(svc)[0]["absent"] == ["A"]+++def test_prestart_no_show_check_accepts_a_forfeit_hook_that_ends_the_world():+ """core 0.2.21: the generic check prestart_no_show (core/testkit.py) asks for the forfeit's decision at step 0,+ not for an unfinished world. A sport whose forfeit hook ends its world (the game over, the winner set) is+ decided the same way (the forfeit comes first in core.outcome.decide); cores 0.2.7-0.2.11 failed it."""+ from core import testkit+ cfg = MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")+ game = type(SPORT_TURN.build(cfg))+ decl = {"formats": {"single": {"seats": ["A"]}, "duel": {"seats": ["A", "B"], "first": ["A", "B"]}},+ "modes": {"action_levels": ["low"]}}+ plain = testkit.t_prestart_no_show(SPORT_TURN, PLUGIN_TURN, decl)+ phase = game.phase++ def forfeit(self, seat, why):+ self.ended = why+ return True+ game.forfeit = forfeit+ game.phase = lambda self: Phase(FINISHED, reason=self.ended) if getattr(self, "ended", None) else phase(self)+ try:+ ended = testkit.t_prestart_no_show(SPORT_TURN, PLUGIN_TURN, decl)+ finally:+ del game.forfeit+ game.phase = phase+ for rows, finished in ((plain, False), (ended, True)):+ assert [r["name"] for r in rows] == ["prestart_no_show:single", "prestart_no_show:duel"], rows+ assert all(r["ok"] for r in rows), rows+ assert all(json.loads(r["detail"])["finished"] is finished for r in rows), rows+++def test_prestart_team_side_with_a_missing_seat_loses_at_the_collect():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ svc, post = turn_service(list(sides), sides, fmt="team")+ for s in ("A1", "B1", "B2"): # A2 never starts+ post["start"](s, {})+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["forfeiting"] == "A2" and fin["match_winner"] == "away", fin+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ out = graded(svc, fin)+ assert out["A2_no_show"] == 1 and out["A1_no_show"] == 0 and out["B1_won"] == 1 and out["A1_won"] == 0, out+++def test_prestart_no_side_present_at_the_collect_does_not_count():+ """No side complete (one home seat started): the collect leaves the match unfinished, as before core 0.2.7."""+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ for make, reason in ((lambda: service(list(sides), sides), "collected"),+ (lambda: turn_service(list(sides), sides, fmt="team"), "incomplete")):+ svc, post = make()+ threading.Thread(target=post["start"], args=("A1", {}), daemon=True).start()+ t = time.time()+ while not svc.seats["A1"].joined and time.time() - t < 5:+ time.sleep(0.01)+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == reason and fin["forfeiting"] is None and fin["winner"] is None, fin+ assert not fin["valid_trial"] and graded(svc, fin)["no_show"] == 0 and not collect_rows(svc), fin+++def test_prestart_n_sides_collect():+ """Three sides: one absent at the collect retires (the sport allows it) and the match, never begun, ends+ unfinished; two absent: the first retires, the second forfeits and the present side wins (as at the window)."""+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ for s in ("B", "C"):+ post["start"](s, {})+ svc.collect()+ fin = finish(svc)+ assert fin["retired"] == ["A"] and fin["reason"] == "incomplete" and not fin["valid_trial"], fin+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ post["start"]("C", {})+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["match_winner"] == "C" and fin["retired"] == ["A"], fin+ assert fin["ranking"] == ["C", "B", "A"] and fin["valid_trial"], fin+++def test_no_show_n_sides_absent_side_retires_others_play():+ with start_window(1):+ svc, post = service(["A", "B", "C"], fmt="multi")++ def mover(v):+ return lambda seat, p: p["act"](seat, {"type": "move", "v": v, "entity": "e0"})+ fin = run_all(svc, post, ["A", "B"], A={"act": mover(0.2)}, B={"act": mover(0.1)}) # C never starts+ assert fin["retired"] == ["C"] and fin["reason"] == "match_over", fin+ assert fin["ranking"] == ["A", "B", "C"] and fin["valid_trial"] and fin["deterministic"], \+ {k: fin[k] for k in ("ranking", "valid_trial", "deterministic", "finalized", "scores", "replay_scores", "steps")}+ with start_window(1):+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("B", .9), ("C", .1))]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["retired"] == ["A"] and fin["reason"] == "match_over", fin+ assert fin["ranking"] == ["B", "C", "A"] and fin["match_winner"] == "B", fin+ assert fin["valid_trial"] and fin["deterministic"], {k: fin[k] for k in ("finalized", "scores", "replay_scores")}+ with start_window(1): # two of three absent: the first retires, the second forfeits+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ post["start"]("C", {})+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["match_winner"] == "C" and fin["retired"] == ["A"], fin+ assert fin["ranking"] == ["C", "B", "A"] and fin["valid_trial"], fin+++def test_turn_duel_plays_to_the_end():+ svc, post = turn_service(["A", "B"])+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("A", .3), ("B", .6))]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["reason"] == "match_over" and fin["match_winner"] == "B" and fin["valid_trial"], fin+ assert fin["deterministic"], fin["errors"]+++class Stub:+ def __init__(self, sc, finished=True, rules=None, rank=None):+ self.sc, self.fin, self.rules, self.rank = sc, finished, rules, rank++ def scores(self):+ return self.sc++ def phase(self):+ return Phase(FINISHED if self.fin else PLAYING)++ def tiebreaks(self):+ return self.rules if self.rules is not None else [("last", lambda m: "B")]++ def ranking(self):+ return self.rank+++def test_outcome_rules():+ assert decide(Stub({"A": 30}, rules=[]), sides=["A"]).solo # solo: no winner+ assert decide(Stub({"A": 30}, rules=[]), sides=["A"]).winner is None+ assert decide(Stub({"A": 1, "B": 1}), sides=["A", "B"]).winner == "B" # last tiebreak decides+ assert decide(Stub({"A": 1, "B": 1}), "A", "clock", ["A", "B"]).winner == "B"+ o = decide(Stub({"A": 1, "B": 3, "C": 2}, rank=["B", "C", "A"]), sides=["A", "B", "C"])+ assert o.winner == "B" and o.ranking == ["B", "C", "A"]+ try:+ decide(Stub({"A": 1, "B": 1}, rules=[("x", lambda m: None)]), sides=["A", "B"])+ raise AssertionError("a draw was accepted")+ except RuntimeError:+ pass+ assert decide(Stub({"A": 1, "B": 1}, finished=False), sides=["A", "B"]).winner is None+++def test_grading_success_rules():+ assert line_ok(30, {"score_at_least": 30}) and not line_ok(29, {"score_at_least": 30})+ assert line_ok(3, {"score_at_most": 4})+ base = {"cfg": {"seats": ["A"]}, "sides": {"A": "A"}, "deterministic": True, "state_sha": "s", "scores": {"A": 31},+ "match_winner": None, "commands_sha": "c", "source_sha": "x", "steps": 5, "reason": "match_over",+ "valid_trial": True, "finalized": True, "errors": [], "meter_error": {}, "proxy_error": {}, "solo": True,+ "transient_api_errors": {}, "unrecovered_api_errors": {}, "player_modes": {"A": "oracle"},+ "format": "single", "play": "program"}+ rc = {"state_sha": "s", "scores": {"A": 31}, "winner": None, "commands_sha": "c", "source_sha": "x", "k": 5}+ contract = {"formats": {"single": {"success": {"score_at_least": 30}}}}+ assert grade(base, rc, contract, lambda d: {})["success"] == 1+ low = dict(base, scores={"A": 20})+ assert grade(low, dict(rc, scores={"A": 20}), contract, lambda d: {})["success"] == 0+ opp = dict(base, solo=False, match_winner="opponent") # single vs a scripted opponent+ assert grade(opp, dict(rc, winner="opponent"), contract, lambda d: {})["success"] == 0+ opp = dict(base, solo=False, match_winner="A")+ assert grade(opp, dict(rc, winner="A"), contract, lambda d: {})["success"] == 1+++def test_launch_seat_env_second_account_and_route():+ from core.launch import PROXY, seat_env+ env = {"KEY_ACCOUNT": "t1", "KEY_ACCOUNT_2": "t2", "THINK_OPENAI_ROUTE": "openrouter",+ "RO_SEAT_SELECT_A": "KEY_ACCOUNT=KEY_ACCOUNT_2", "RO_SEAT_SELECT_B": "",+ "RO_SEAT_ENV_THINK_OPENAI_ROUTE_B": "azure", "RO_SEAT_ENV_THINK_OPENAI_ROUTE_A": ""}+ a, b = seat_env("A", env, ["A", "B"]), seat_env("B", env, ["A", "B"])+ assert a["KEY_ACCOUNT"] == "t2" and b["KEY_ACCOUNT"] == "t1"+ assert a["THINK_OPENAI_ROUTE"] == "openrouter" and b["THINK_OPENAI_ROUTE"] == "azure"+ assert a["THINK_USAGE_FILE"].endswith("think_usage_A.json") and a["THINK_CLIENT_HOST"] == "seat_a"+ assert PROXY.parts[-2:] == ("metering", "think_proxy.py") # where tools/sportlib.py puts the proxy+++def test_launch_seat_env_holds_no_other_seats_variables():+ """After the mapping a proxy has no RO_SEAT_* and no other seat's per-seat variable; a seat on route chatgpt keeps+ only the credentials given to it alone (no task-wide key)."""+ from core.launch import seat_env+ env = {"SUB_TOKEN": "", "TASK_KEY": "task-key", "THINK_OPENAI_ROUTE": "azure", "SUB_TOKEN_A": "raw-a",+ "PLAYER_MODE_A": "model", "PLAYER_MODE_B": "model", "RO_SEAT_SELECT_A": "", "RO_SEAT_SELECT_B": ""}+ for s, tok, route in (("A", "secret-a", "chatgpt"), ("B", "secret-b", "chatgpt"), ("C", "", "azure")):+ env.update({f"RO_SEAT_ENV_SUB_TOKEN_{s}": tok, f"RO_SEAT_ENV_TASK_KEY_{s}": "",+ f"RO_SEAT_ENV_THINK_OPENAI_ROUTE_{s}": route, f"RO_SEAT_ENV_THINK_MODEL_{s}": f"model-{s}"})+ a, b, c = (seat_env(s, env, ["A", "B", "C"]) for s in "ABC")+ for e, own, others in ((a, "secret-a", ("secret-b",)), (b, "secret-b", ("secret-a", "raw-a")),+ (c, None, ("secret-a", "secret-b", "raw-a"))):+ assert not [k for k in e if k.startswith(("RO_SEAT_ENV_", "RO_SEAT_SELECT_"))], sorted(e)+ assert not [k for k, v in e.items() for x in others if x in v], sorted(e.items())+ assert e.get("SUB_TOKEN") == (own if own else "")+ assert "TASK_KEY" not in a and "TASK_KEY" not in b and c["TASK_KEY"] == "task-key" # route chatgpt: no task key+ assert (a["THINK_MODEL"], b["THINK_MODEL"], c["THINK_MODEL"]) == ("model-A", "model-B", "model-C")+ assert "PLAYER_MODE_B" not in a and "PLAYER_MODE_A" not in b and "SUB_TOKEN_A" in a+++# ------------------------------------------------------------------ the spectator scene (core 0.2.4, renderer rule 6)+_ARM = ('<mujoco><worldbody><light pos="0 0 3" dir="0 0 -1"/><body name="arm" pos="0 0 .2"><joint axis="0 0 1"/>'+ '<geom name="arm_c" type="box" size=".05 .05 .2" rgba=".8 .2 .2 1"/></body></worldbody></mujoco>')+_MODEL = ('<mujoco><asset><mesh name="m" file="tetra.obj"/></asset><worldbody>'+ '<body name="arm"><geom type="mesh" mesh="m" rgba=".1 .3 .9 1" contype="0" conaffinity="0" group="2"/>'+ '</body></worldbody></mujoco>')+++def test_spectator_scene_is_the_presentation_scene_and_players_keep_the_match_scene():+ from core.observe import CameraWorker+ from core.spectator import spectator_scene+ from renderers.base import Scene++ class Sport:+ def scene(self, cfg):+ return Scene(xml=_ARM)++ cfg = MatchConfig(sport="x", format="single", seats=("A",), seed=1)+ with tempfile.TemporaryDirectory() as tmp:+ plugin = Path(tmp) / "plugin.py"+ sc, what = spectator_scene(Sport(), str(plugin), cfg) # no presentation/: the match scene+ assert what == "match" and not sc.is_presentation+ d = Path(tmp) / "presentation"+ d.mkdir()+ (d / "arm.xml").write_text(_MODEL)+ (d / "tetra.obj").write_text("v -.1 -.1 0\nv .1 -.1 0\nv 0 .1 0\nv 0 0 .4\nf 1 3 2\nf 1 2 4\nf 2 3 4\nf 3 1 4\n")+ (d / "presentation.toml").write_text('[presentation]\nversion = 1\n[[presentation.robot]]\n'+ 'model = "./arm.xml"\nbodies = "arm"\nbody = "arm"\n')+ sc, what = spectator_scene(Sport(), str(plugin), cfg)+ assert what == "presentation" and sc.is_presentation and "_vis:arm:0" in sc.xml+ os.environ["RO_VIDEO_SCENE"] = "match"+ try:+ sc2, what2 = spectator_scene(Sport(), str(plugin), cfg)+ finally:+ del os.environ["RO_VIDEO_SCENE"]+ assert what2 == "match" and not sc2.is_presentation+ (d / "presentation.toml").write_text('[presentation]\nversion = 1\n[[presentation.robot]]\n'+ 'model = "not_in_the_manifest"\nbodies = "arm"\nbody = "arm"\n')+ sc3, what3 = spectator_scene(Sport(), str(plugin), cfg) # a broken presentation: the match scene+ assert what3.startswith("match (presentation unavailable") and not sc3.is_presentation+ try:+ CameraWorker(sc, None)+ raise AssertionError("players' images must refuse a presentation scene")+ except ValueError:+ pass++++def test_players_scene_is_the_presentation_scene_only_when_declared():+ """core 0.2.9, renderer rule 6: a presentation.toml with `players` = the players' images use it (CameraWorker+ accepts it, the same kinematics checked); without, the match scene."""+ from core.observe import CameraWorker, players_scene+ from core.spectator import spectator_scene+ from renderers.base import CameraDef, Scene+ from renderers.label import frame_label++ class Sport:+ def scene(self, cfg):+ return Scene(xml=_ARM)++ cfg = MatchConfig(sport="x", format="single", seats=("A",), seed=1)+ cam = CameraDef("c", pos=(1.2, -1.2, 0.8), lookat=(0, 0, 0.2), width=64, height=48).to_dict()+ with tempfile.TemporaryDirectory() as tmp:+ plugin = Path(tmp) / "plugin.py"+ assert not players_scene(Sport(), str(plugin), cfg).is_presentation # no presentation/+ d = Path(tmp) / "presentation"+ d.mkdir()+ (d / "arm.xml").write_text(_MODEL)+ (d / "tetra.obj").write_text("v -.1 -.1 0\nv .1 -.1 0\nv 0 .1 0\nv 0 0 .4\nf 1 3 2\nf 1 2 4\nf 2 3 4\nf 3 1 4\n")+ decl = '[presentation]\nversion = 2\n[[presentation.robot]]\nmodel = "./arm.xml"\nbodies = "arm"\nbody = "arm"\n'+ (d / "presentation.toml").write_text(decl)+ sc = players_scene(Sport(), str(plugin), cfg)+ assert not sc.is_presentation # spectators only+ (d / "presentation.toml").write_text(decl.replace("version = 2\n", 'version = 2\nplayers = "full"\n'))+ sc = players_scene(Sport(), str(plugin), cfg)+ assert sc.is_presentation and sc.players and "_vis:arm:0" in sc.xml+ w = CameraWorker(sc, None)+ fine = w.draw({"qpos": [0.3]}, [cam])+ plain = CameraWorker(Scene(xml=_ARM), None).draw({"qpos": [0.3]}, [cam])+ assert fine["png"] != plain["png"] and fine["renderer"] == "mujoco"+ assert frame_label(w.renderer, sc) is None # the competition picture: no tag+ sp, what = spectator_scene(Sport(), str(plugin), cfg)+ assert what == "presentation" and sp.is_presentation+ (d / "presentation.toml").write_text(decl.replace("version = 2\n", 'version = 2\nplayers = "fine"\n'))+ try:+ players_scene(Sport(), str(plugin), cfg)+ raise AssertionError("players must be full or a level of detail")+ except ValueError as e:+ assert "players" in str(e)+++# ---- core 0.2.14: hidden official seeds (core/seeds.py) and the continuous score (core/score.py) ---------------+def test_hidden_seed_commitments():+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 3, "single/L1": 2, "single/L2": 2}, avoid=[1, 2, 3])+ pub = seeds.public(priv)+ flat = [e["seed"] for v in priv["cells"].values() for e in v]+ assert pub["counts"] == {"duel": 3, "single/L1": 2, "single/L2": 2} and len(set(flat)) == 7 # no shared seeds+ assert all(seeds.SEED_RANGE[0] <= x <= seeds.SEED_RANGE[1] for x in flat)+ assert not any(str(x) in json.dumps(pub) for x in flat) # the public part names no seed+ for cell, entries in priv["cells"].items():+ fmt, _, lv = cell.partition("/L")+ for i, e in enumerate(entries):+ c = seeds.commitment("fixture_turn", e["seed"], e["salt"])+ assert seeds.index("fixture_turn", fmt, int(lv) if lv else None, c, pub) == i+ assert seeds.resolve(priv, cell, i, pub) == (e["seed"], e["salt"])+ e = priv["cells"]["single/L1"][0]+ c = seeds.commitment("fixture_turn", e["seed"], e["salt"])+ assert seeds.index("fixture_turn", "single", 2, c, pub) is None # another cell (level)+ assert seeds.index("fixture_turn", "duel", None, c, pub) is None # another cell (format)+ assert seeds.index("fixture_turn", "single", 1, seeds.commitment("fixture_turn", e["seed"], "0" * 32), pub) is None+ assert seeds.index("fixture_turn", "single", 1, None, pub) is None # no proof+ assert seeds.cell_of("duel", 2, pub["cells"]) == "duel" # a fixed level the sim reports+ forged = dict(pub, cells=dict(pub["cells"], duel=pub["cells"]["duel"][:-1] + ["ab" * 32]))+ assert seeds.index("fixture_turn", "duel", None, "ab" * 32, forged) is None # not the registered list+ try:+ seeds.resolve(seeds.new("fixture_turn", {"duel": 3, "single/L1": 2, "single/L2": 2}), "duel", 0, pub)+ raise AssertionError("a different private set resolved against the registration")+ except ValueError:+ pass+ s = seeds.scrub({"seed": 5, "x": {"rng_seed": 7, "v": [123456, "123456", 2.5]}, "step": 123456,+ "salt": "ab" * 16}, 123456, "ab" * 16)+ assert s == {"seed": -1, "x": {"rng_seed": -1, "v": [-1, "-1", 2.5]}, "step": 123456, "salt": "-1"}, s+++def hidden_turn_duel(seed, salt, index=None):+ """A turn duel of the fixture played to the end at `seed`, with the runner's salt (and the seed itself, for the+ fresh-process replay) in the sim's environment."""+ env = {"RO_SEED_SALT": salt or "", "RO_SEED": str(seed), "RO_SEED_INDEX": "" if index is None else str(index)}+ os.environ.update(env)+ try:+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=seed, first="A",+ action_level="low")+ svc = TurnService(SPORT_TURN, PLUGIN_TURN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("A", .3), ("B", .6))]+ for t in th:+ t.start()+ return svc, finish(svc)+ finally:+ for k in env:+ os.environ.pop(k, None)+++def test_hidden_seed_official_only_when_registered():+ """The verifier counts a match as official only when its commitment is in the registered cell (core 0.2.14)."""+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 3, "single": 2})+ reg = seeds.public(priv)+ e = priv["cells"]["duel"][1]+ svc, fin = hidden_turn_duel(e["seed"], e["salt"], 1)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["seed_proof"] == {"commitment": seeds.commitment("fixture_turn", e["seed"], e["salt"]), "index": 1}+ rc = json.loads((svc.data / "replay_check.json").read_text())+ assert rc["seed_commitment"] == fin["seed_proof"]["commitment"]+ contract = {"sport": "fixture_turn", "official": {"hidden_seeds": reg, "seeds": [e["seed"]], "first_any": True}}+ out = grade(fin, rc, contract, lambda d: {})+ assert out["official_config"] == 1 and out["hidden_seed"] == 1 and out["hidden_seed_index"] == 1, out+ assert out["seed"] == -1+ bad = dict(fin, seed_proof={"commitment": seeds.commitment("fixture_turn", e["seed"], "0" * 32)})+ out = grade(bad, dict(rc, seed_commitment=bad["seed_proof"]["commitment"]), contract, lambda d: {})+ assert out["official_config"] == 0 and out["hidden_seed"] == 0 and out["hidden_seed_index"] == -1+ out = grade(dict(fin, format="single"), rc, contract, lambda d: {}) # another cell+ assert out["hidden_seed"] == 0+ out = grade(dict(fin, seed_proof=None), rc, contract, lambda d: {}) # a public seed is not enough+ assert out["official_config"] == 0 and out["hidden_seed"] == 0+ other = seeds.public(seeds.new("fixture_turn", {"duel": 3, "single": 2})) # an unregistered set+ out = grade(fin, rc, dict(contract, official=dict(contract["official"], hidden_seeds=other)), lambda d: {})+ assert out["official_config"] == 0+ out = grade(fin, dict(rc, seed_commitment="ab" * 32), contract, lambda d: {}) # the replay must agree+ assert out["deterministic"] == 0 and out["official_config"] == 1 and out["valid_trial"] == 0+ svc2, fin2 = hidden_turn_duel(7, None) # no salt: an ordinary seed+ assert fin2["seed_proof"] is None and fin2["seed"] == 7+ assert grade(fin2, json.loads((svc2.data / "replay_check.json").read_text()), contract,+ lambda d: {})["official_config"] == 0+++def test_hidden_seeds_override_the_sports_official_rule():+ """Core 0.2.19: with a registered hidden seed set the sport's own official_config (a legacy public-seed rule in+ tests/sport_grade.py) cannot make a match official: only a registered hidden seed of the match's cell counts, and+ the sport's rule can only lower it."""+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 3, "single": 2})+ reg = seeds.public(priv)+ e = priv["cells"]["duel"][0]+ svc, fin = hidden_turn_duel(e["seed"], e["salt"], 0)+ rc = json.loads((svc.data / "replay_check.json").read_text())+ contract = {"sport": "fixture_turn", "official": {"hidden_seeds": reg, "first_any": True}}+ legacy = lambda d: {"official_config": 1} # noqa: E731 a sport that always says 1+ defer = lambda d: {} # noqa: E731 a sport that keeps the core's+ lower = lambda d: {"official_config": 0} # noqa: E731 e.g. its slowdown rule fails+ assert grade(fin, rc, contract, legacy)["official_config"] == 1 # hidden seed of the cell: official+ assert grade(fin, rc, contract, defer)["official_config"] == 1+ assert grade(fin, rc, contract, lower)["official_config"] == 0 # the sport can lower it+ svc2, pub = hidden_turn_duel(7, None) # a public seed: never official once frozen+ rc2 = json.loads((svc2.data / "replay_check.json").read_text())+ assert pub["seed_proof"] is None+ assert grade(pub, rc2, contract, legacy)["official_config"] == 0+ out = grade(dict(fin, format="single"), rc, contract, legacy) # a commitment of another cell+ assert out["official_config"] == 0 and out["hidden_seed"] == 0+ assert grade(pub, rc2, {"sport": "fixture_turn", "official": {}}, legacy)["official_config"] == 1 # not frozen+++def test_hidden_seed_is_never_written():+ """A hidden seed and its salt appear in no record of the match (episode, final.json, replay check, broadcast log,+ reward) nor in a reply to a player; the fresh-process replay still reproduces the match (core 0.2.14)."""+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 2})+ e = priv["cells"]["duel"][0]+ svc, fin = hidden_turn_duel(e["seed"], e["salt"], 0)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["sport_fields"]["seed"] == -1 and fin["sport_fields"]["draws"] == [-1, 1]+ assert fin["cfg"]["seed"] == -1 and fin["seed"] == -1+ out = grade(fin, json.loads((svc.data / "replay_check.json").read_text()),+ {"sport": "fixture_turn", "official": {"hidden_seeds": seeds.public(priv)}}, lambda d: {})+ assert out["hidden_seed"] == 1 and out["seed"] == -1+ texts = {f.name: f.read_text() for f in svc.data.iterdir() if f.is_file() and f.suffix in (".json", ".jsonl")}+ texts["reward"] = json.dumps(out)+ os.environ.update(RO_SEED_SALT=e["salt"])+ try:+ texts["spec"] = json.dumps(svc.public(svc.spec("A")[1]))+ texts["observe"] = json.dumps(svc.public(svc.routes(True)["observe"]("A", {})[1]))+ finally:+ os.environ.pop("RO_SEED_SALT", None)+ assert "episode.jsonl" in texts and "replay_check.json" in texts and "final.json" in texts+ for name, text in texts.items():+ assert str(e["seed"]) not in text and e["salt"] not in text, name+ head = json.loads((svc.data / "episode.jsonl").read_text().splitlines()[0])+ assert head["cfg"]["seed"] == -1 and head["seed_hidden"]["commitment"] == fin["seed_proof"]["commitment"]+ from core.episode import header_cfg+ try:+ header_cfg(head) # an offline replay needs the seed from the host+ raise AssertionError("a hidden-seed episode replayed without its seed")+ except ValueError:+ pass+ os.environ.update(RO_SEED=str(e["seed"] + 1), RO_SEED_SALT=e["salt"])+ try:+ header_cfg(head)+ raise AssertionError("a wrong seed was accepted for a hidden-seed episode")+ except ValueError:+ pass+ finally:+ os.environ.pop("RO_SEED", None), os.environ.pop("RO_SEED_SALT", None)+++def test_continuous_score_in_final_reward_and_replay():+ svc, fin = hidden_turn_duel(5, None)+ c = fin["continuous"]+ assert c["name"] == "score_share" and c["higher_is_better"] is True and c["forfeited"] == []+ assert abs(c["by_side"]["A"] - .3 / .9) < 1e-6 and abs(c["by_side"]["B"] - .6 / .9) < 1e-6, c+ rc = json.loads((svc.data / "replay_check.json").read_text())+ assert rc["continuous"] == c["by_side"]+ out = grade(fin, rc, {"sport": "fixture_turn", "score": {"forfeit": 0.0}}, lambda d: {})+ assert out["A_continuous_score"] == c["by_side"]["A"] and out["B_continuous_score"] == c["by_side"]["B"]+ assert "continuous_score" not in out # two sides: per seat only+ out = grade(dict(fin, continuous=dict(c, by_side={"A": 0.9, "B": 0.1})), rc, {}, lambda d: {})+ assert out["deterministic"] == 0 and out["valid_trial"] == 0 # the replay must agree+++def test_continuous_score_forfeit_value_on_no_show():+ with start_window(1):+ svc, post = turn_service(["A", "B"])+ assert post["start"]("A", {})[0] == 200 # B never starts+ fin = finish(svc)+ check_no_show(svc, fin)+ assert fin["continuous"]["by_side"] == {"A": 0.5, "B": 0.0} and fin["continuous"]["forfeited"] == ["B"]+ out = graded(svc, fin)+ assert out["A_continuous_score"] == 0.5 and out["B_continuous_score"] == 0.0+++def test_continuous_score_rules():+ from core import score+ decl = {"score": {"name": "x", "text": "t", "from": "share", "forfeit": 0.0}, "formats": {"d": {"seats": ["A", "B"]}}}+ m = Stub({"A": 3, "opponent": 1})+ assert score.compute(m, decl, ["A"])["by_side"] == {"A": 0.75} # against a scripted opponent+ assert score.compute(Stub({"A": 0, "B": 0}), decl, ["A", "B"])["by_side"] == {"A": 0.5, "B": 0.5}+ assert score.compute(m, decl, ["A"], forfeited=["A"])["by_side"] == {"A": 0.0}+ d = {"score": dict(decl["score"], **{"from": "margin", "forfeit": -10})}+ assert score.compute(Stub({"A": 1, "B": 4, "C": 2}), d, ["A", "B"])["by_side"] == {"A": -3.0, "B": 2.0}+ d = {"score": dict(decl["score"], **{"from": "own"})}+ assert score.compute(Stub({"A": 31}), d, ["A"])["by_side"] == {"A": 31.0}+ assert score.compute(m, {}, ["A"]) is None # not declared: nothing+ h = Stub({"A": 0})+ h.continuous_score = lambda: {"A": float("nan")}+ try:+ score.compute(h, {"score": dict(decl["score"], **{"from": "hook"})}, ["A"])+ raise AssertionError("a non-finite continuous score was accepted")+ except RuntimeError:+ pass+ assert score.problems(decl, False) == []+ assert score.problems({"score": {"name": "Bad name", "from": "hook", "forfeit": "x"}}, False)+ solo = {"score": dict(decl["score"]), "formats": {"s": {"seats": ["A"]}}}+ assert any("opponent" in p for p in score.problems(solo, False))+++# ------------------------------------------------------------------ core 0.2.15: a layer's tick+def test_layer_tick_is_applied_logged_and_replayed():+ """An action layer's tick(seat, match) (the skill in the loop's step(), skilleval/inloop.py) runs every control+ step before the actions: its command is applied, logged as a command row and the episode replays without the+ layer (core/local.py and core/realtime.py share the rule)."""+ from core import local+ from core.episode import read_rows, replay++ class Tick(SPORT.action_layer("low").__class__):+ def tick(self, seat, match):+ return {"type": "move", "entity": "e0", "v": 0.25 if (match.k // 10) % 2 else -0.5} \+ if match.k % 10 == 0 else None++ class WithTick:+ def __getattr__(self, k):+ return getattr(SPORT, k)++ def action_layer(self, level):+ return Tick(0)++ class Idle:+ def act(self, view):+ return None++ cfg = MatchConfig(sport="fixture", format="solo", seats=("A",), seed=1, slowdown=1.0)+ d = Path(tempfile.mkdtemp(prefix="core-test-"))+ r = local.play(WithTick(), cfg, {"A": Idle()}, data=d, render=False)+ rows = read_rows(d / "episode.jsonl")+ cmds = [x for x in rows if x["ev"] == "cmd"]+ assert len(cmds) == 9 and all(c["cmd"]["entity"] == "e0" for c in cmds), cmds[:3]+ assert r["scores"]["A"] != 0+ rep = replay(SPORT, rows)+ assert rep["state_sha"] == r["digest"] and rep["scores"] == r["scores"], (rep, r)+++def main():+ tests = [(n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)]+ bad = 0+ for name, f in tests:+ t = time.time()+ try:+ f()+ print(f"ok {name} ({time.time() - t:.1f} s)")+ except Exception: # noqa: BLE001+ bad += 1+ print(f"FAIL {name}\n{traceback.format_exc()}")+ print(f"{len(tests) - bad}/{len(tests)} passed")+ return 1 if bad else 0++++def test_local_play_refused_action_is_a_refusal():+ """core 0.2.3: a built-in player's invalid action is refused (as HTTP 400 in a real match), not a crash."""+ from core import local+ cfg = MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")++ class Flaky:+ def __init__(self):+ self.n = 0++ def act(self, view):+ self.n += 1+ return {"type": "add", "v": 5.0} if self.n == 1 else {"type": "add", "v": 0.5} # first: out of range++ r = local.play(SPORT_TURN, cfg, {"A": Flaky(), "B": Flaky()}, render=False, plugin=PLUGIN_TURN)+ assert r["winner"] in ("A", "B"), r # the match was played out despite the refused first actions++++def test_team_channel_switch_off():+ """core 0.2.5: RO_TEAM_CHANNEL=off switches a declared team channel off (403), on by default."""+ from core.channel import TeamChannel+ cfg = MatchConfig(sport="fixture", format="team", seats=("A1", "A2", "B1", "B2"), seed=1,+ sides={"A1": "A", "A2": "A", "B1": "B", "B2": "B"})+ conf = {"max_bytes": 64, "min_interval_s": 0.0, "max_messages": 5}+ os.environ.pop("RO_TEAM_CHANNEL", None)+ assert TeamChannel(cfg, conf).say("A1", "go left", 0, 0.01)[0] == 200+ os.environ["RO_TEAM_CHANNEL"] = "off"+ try:+ code, body = TeamChannel(cfg, conf).say("A1", "go left", 0, 0.01)+ assert code == 403 and "off" in body["error"], (code, body)+ finally:+ os.environ.pop("RO_TEAM_CHANNEL", None)+ assert TeamChannel(cfg, None).say("A1", "x", 0, 0.01)[0] == 404 # not declared: no channel at all++++# ------------------------------------------------------------ a session that ends mid-match (core 0.2.6, core rule 6)+def check_abandoned(svc, fin):+ """A single side whose session ended after the start: a valid loss by forfeit (abandoned), replayed; success 0."""+ assert fin["reason"] == "abandoned" and fin["forfeiting"] == "A" and fin["winner"] is None, fin+ assert fin["decided_by"] == "forfeit:abandoned" and fin["match_winner"] is None, fin+ assert fin["valid_trial"] and fin["deterministic"] and not fin["technical_failure"], fin["errors"]+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "forfeit" and r["seat"] == "A" and r["why"] == "abandoned" for r in rows)+ out = graded(svc, fin)+ assert out["valid_trial"] == 1 and out["technical_failure"] == 0 and out["success"] == 0, out+ assert out["abandoned"] == 1 and out["no_show"] == 0 and out["A_won"] == 0 and out["A_no_show"] == 0, out+++def test_solo_quit_realtime_single_mid_match_is_a_valid_loss():+ for when in ("running", "review"):+ svc, post = service(["A"], fmt="single")+ threading.Thread(target=post["start"], args=("A", {}), daemon=True).start() # never reviews+ t = time.time()+ while svc.phase != when and time.time() - t < 10:+ time.sleep(0.005)+ assert svc.phase == when, svc.phase+ svc.collect() # the session ends mid-match+ fin = finish(svc)+ check_abandoned(svc, fin)+ assert fin["steps"] < 90 and (when == "running" or fin["steps"] == 30), fin["steps"]+++def test_solo_quit_turn_single_on_and_off_turn_is_a_valid_loss():+ for case in ("on_turn", "awaiting_review", "off_turn"):+ svc, post = turn_service(["A"], fmt="single")+ post["start"]("A", {})+ if case != "on_turn":+ assert post["act"]("A", {"v": 0.5})[0] == 200 # one move, review pending+ if case == "off_turn":+ post["ready"]("A", {"why": "w", "plan": "p"})+ with svc.cond: # a sport whose to_move() names nobody for a while (e.g. a pending action)+ svc.set_turn(None)+ svc.collect()+ fin = finish(svc)+ check_abandoned(svc, fin)+ assert fin["steps"] == (0 if case == "on_turn" else 1), fin["steps"]+++def test_solo_quit_realtime_duel_unchanged():+ """Two sides: the collect before the end still leaves the match unfinished ("collected", invalid). A side that+ stops playing while the other plays on loses at the next review it owes (ready_timeout, valid)."""+ svc, post = service(["A", "B"], fmt="duel")+ for s in ("A", "B"):+ threading.Thread(target=post["start"], args=(s, {}), daemon=True).start()+ t = time.time()+ while svc.phase != "running" and time.time() - t < 10:+ time.sleep(0.005)+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == "collected" and fin["forfeiting"] is None and fin["winner"] is None, fin+ assert not fin["valid_trial"] and graded(svc, fin)["abandoned"] == 0+ svc, post = service(["A", "B"], fmt="duel")+ threading.Thread(target=play, args=(svc, post, "A"), daemon=True).start()+ threading.Thread(target=post["start"], args=("B", {}), daemon=True).start() # B starts, then never reviews+ fin = finish(svc)+ assert fin["reason"] == "ready_timeout" and fin["forfeiting"] == "B" and fin["winner"] == "A", fin+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++PLUGIN_IMG = str(Path(__file__).resolve().parent / "fixture_images" / "plugin.py")+_TINY = ('<mujoco><visual><headlight ambient=".5 .5 .5"/></visual><worldbody><geom type="plane" size="5 5 .1" '+ 'rgba=".3 .5 .3 1"/><body mocap="true" pos="0 0 .2"><geom type="box" size=".1 .1 .1" rgba="1 0 0 1"/>'+ '</body></worldbody></mujoco>')+_CAM = {"name": "top", "pos": [0, 0, 3], "lookat": [0, 0, 0], "up": [1, 0, 0], "fovy_deg": 60, "width": 64,+ "height": 48}+++def _img_service():+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ sport = load_plugin(PLUGIN_IMG)+ cfg = MatchConfig(sport="fixture_images", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")+ svc = TurnService(sport, PLUGIN_IMG, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ post["start"]("A", {})+ post["start"]("B", {})+ return svc, post+++def test_reply_images_turn_attached_replayable_and_review_state():+ """core 0.2.8: Match.reply_views -> the act reply carries the result's images (observe's format, frames with+ labels), drawn off the lock by the task renderer; a replay draws the same PNG; the sport sees whose review is due+ (the other seat gets no images while the actor reviews, although the sport's to_move() already names it)."""+ import base64+ import struct+ from core.episode import read_rows, reply_image+ svc, post = _img_service()+ assert post["observe"]("A", {})[1]["observation"].get("image_png_b64") # on turn: the camera image+ code, out = post["act"]("A", {"v": 0.7})+ assert code == 200, out+ ob = out["observation"]+ raw = base64.b64decode(ob["image_png_b64"])+ assert raw[:8] == b"\x89PNG\r\n\x1a\n" and struct.unpack(">II", raw[16:24]) == (160, 60)+ assert [(t["camera"], t["frame"], t["label"]) for t in ob["tiles"]] == [("top", 0, "before"), ("top", 1, "after")]+ assert ob["of"] and ob["note"] and "render_wall_s" in ob+ assert svc.m.awaiting_review == "A" and out["state"]["awaiting_review"] and svc.m.to_move() == "B"+ assert "image_png_b64" not in post["observe"]("B", {})[1]["observation"] # the review-window leak is closed+ rows = read_rows(svc.data / "episode.jsonl")+ assert [(r["seat"], r["tiles"]) for r in rows if r["ev"] == "reply_images"] == [("A", 2)] # information row+ img = reply_image(PLUGIN_IMG, rows, 1)+ assert img["png"] == raw and img["tiles"] == ob["tiles"] # a pure function of the recorded match+ post["ready"]("A", {"why": "w", "plan": "p"})+ assert svc.m.awaiting_review is None+ assert post["observe"]("B", {})[1]["observation"].get("image_png_b64") # B's turn now+ assert svc.camera is not None and not svc.camera.renderer.scene.is_presentation # the match scene only+ svc.collect()+ finish(svc)+++def test_reply_images_off_the_lock_and_off_the_clock():+ """Drawing the reply image neither blocks the other seat nor runs the actor's chess clock."""+ svc, post = _img_service()+ orig = svc.draw++ def slow(seat, job):+ time.sleep(1.5)+ return orig(seat, job)+ svc.draw = slow+ res = {}+ th = threading.Thread(target=lambda: res.update(r=post["act"]("A", {"v": 0.5})), daemon=True)+ t0 = time.time()+ th.start()+ time.sleep(0.5)+ t = time.time()+ code, st = svc.routes(False)["status"]("B", {})+ assert code == 200 and time.time() - t < 0.3, "the other seat was blocked by the drawing"+ assert svc.seats["A"].frozen == 1+ th.join()+ assert time.time() - t0 >= 1.5 and res["r"][0] == 200 and res["r"][1]["observation"].get("image_png_b64")+ used = svc.seats["A"].clock_used()+ assert used < 0.5, f"the drawing ran the actor's clock: {used:.2f} s"+ svc.collect()+ finish(svc)+++def test_reply_images_realtime():+ """Realtime: an act that takes effect at once carries its result's images (frames, camera order, labels), drawn+ after the act's timing was taken; the match stays deterministic."""+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ from renderers.base import Scene+ World = type(SPORT.build(MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)))++ class ImgWorld(World):+ def cameras(self, seat, query=None):+ return [_CAM]++ def render_state(self):+ return {"qpos": [], "mocap_pos": [[self.pos["A.e0"] * 0.01, 0.0, 0.2]], "mocap_quat": [[1, 0, 0, 0]]}++ def reply_views(self, seat, cmd, info):+ later = {"qpos": [], "mocap_pos": [[0.5, 0.0, 0.2]], "mocap_quat": [[1, 0, 0, 0]]}+ return {"frames": [{"cameras": [_CAM, dict(_CAM, name="top2")], "label": "now"},+ {"cameras": [_CAM, dict(_CAM, name="top2")], "state": later, "label": "later"}],+ "order": "camera", "columns": 2, "note": "two frames"}++ class ImgSport(type(SPORT)):+ def build(self, cfg):+ return ImgWorld(cfg)++ def scene(self, cfg):+ return Scene(xml=_TINY)++ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=1.0)+ svc = RealtimeService(ImgSport(), PLUGIN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ for s in ("A", "B"):+ threading.Thread(target=post["start"], args=(s, {}), daemon=True).start()+ while svc.phase != "running":+ time.sleep(0.01)+ code, out = post["act"]("A", {"type": "move", "v": 0.5, "entity": "e0"})+ assert code == 200, out+ ob = out["observation"]+ assert [(t["camera"], t["frame"], t["label"]) for t in ob["tiles"]] == [+ ("top", 0, "now"), ("top", 1, "later"), ("top2", 0, "now"), ("top2", 1, "later")], ob["tiles"]+ assert ob["note"] == "two frames" and ob["image_png_b64"] and "wall_s_after_request" in out["took_effect"]+ fin = run_all(svc, post, ["A", "B"])+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++# ------------------------------------------------------------------ core 0.2.11: malformed requests never void a match+HOSTILE_RAW = [b'{"type": "add", "v": 1' + b"0" * 400 + b"}", b'{"type": "add", "v": NaN}',+ b'{"type": "add", "v": Infinity}', b'{"type": "add", "v": 1e400}', b'{"type": []}', b'{"type": {}}',+ b'{"type": null}', b'{"type": "add", "v": [1, [2, [3]]]}', b'{"type": "add", "v": {"a": 1}}',+ b"[" * 5000 + b"]" * 5000, b'{"type": "' + b"x" * 20000 + b'"}', b"not json", b"\xff\xfe",+ b'{"type": "add", "v": "0.5"}', b"[1, 2]", b'"x"', b'{"type": "add", "v": 0.5, "x": ' ++ b"[" * 50 + b"]" * 50 + b"}"]+++def _http(svc, seats):+ from core.http import make_server+ srv = make_server(svc, seats, {}, port=0)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ return srv, srv.server_address[1]+++def _post(port, path, raw, timeout=10):+ time.sleep(0.06) # under the 20 requests per second and seat (core/http.py)+ import urllib.error+ import urllib.request+ req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data=raw, method="POST",+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.status, json.loads(r.read() or b"{}")+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read() or b"{}")+++def test_turn_malformed_actions_are_refusals_over_http():+ """core 0.2.11 (anti-cheat G3): a hostile act body (huge integer, NaN / inf, an unhashable type, nested junk,+ oversize strings, broken JSON) is the player's own 400; the match goes on and stays a valid trial."""+ svc, post = turn_service(["A", "B"])+ srv, port = _http(svc, ("A", "B"))+ try:+ for s in ("A", "B"):+ assert post["start"](s, {})[0] == 200+ assert svc.on_turn == "A"+ for raw in HOSTILE_RAW:+ code, out = _post(port, "/A/act", raw)+ assert 400 <= code < 500, (raw[:40], code, out)+ assert "detail" not in out and "Error" not in json.dumps(out), out+ for raw in (b'{"timeout_s": 1' + b"0" * 400 + b"}", b'{"timeout_s": [1]}', b'{"query": {"a": 1e999}}'):+ code, out = _post(port, "/A/wait", raw)+ assert 400 <= code < 500, (raw[:40], code, out)+ code, out = _post(port, "/A/observe", b'{"query": {"a": [1' + b"0" * 400 + b"]}}")+ assert code == 400, (code, out)+ assert svc.phase == "play" and not svc.errors, (svc.phase, svc.errors)+ assert svc.seats["A"].stats["refused_invalid"] >= 6, svc.seats["A"].stats+ finally:+ srv.shutdown()+ srv.server_close()+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("A", .3), ("B", .6))]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["reason"] == "match_over" and fin["valid_trial"] and fin["deterministic"], fin+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "refused_invalid" for r in rows)+++def test_parse_exceptions_are_refusals_and_world_errors_stay_failures():+ """Any exception of the action layer's parse is a refusal (no exception text to the player); an exception of+ the world after the action was accepted is still a technical failure, and the 500 reply carries no detail."""+ from core.sport import parse_action+ svc, post = turn_service(["A", "B"])+ inner = svc.layer++ class Crashy:+ level, worker, delay_steps = "low", None, 0++ def schema(self, m, seat):+ return inner.schema(m, seat)++ def parse(self, seat, body, m, ctx):+ if body.get("v") == 0.25:+ raise ZeroDivisionError("secret internal detail")+ return inner.parse(seat, body, m, ctx)++ def __getattr__(self, k):+ return getattr(inner, k)++ svc.layer = Crashy()+ try:+ parse_action(svc.layer, "A", {"type": "add", "v": 0.25}, svc.m, {})+ raise AssertionError("not refused")+ except Refused as exc:+ assert "secret" not in str(exc) and "ZeroDivisionError" in exc.cause+ srv, port = _http(svc, ("A", "B"))+ try:+ for s in ("A", "B"):+ post["start"](s, {})+ code, out = _post(port, "/A/act", b'{"type": "add", "v": 0.25}')+ assert code == 400 and "secret" not in json.dumps(out), (code, out)+ assert svc.phase == "play" and not svc.errors+ world_apply = svc.m.apply++ def boom(seat, cmd):+ raise RuntimeError("secret world detail")+ svc.m.apply = boom+ code, out = _post(port, "/A/act", b'{"type": "add", "v": 0.5}')+ assert code == 500 and out.get("error") == "technical failure" and "detail" not in out, (code, out)+ assert "secret" not in json.dumps(out)+ svc.m.apply = world_apply+ assert svc.reason == "technical_error" and svc.errors+ finally:+ srv.shutdown()+ srv.server_close()+++def test_realtime_malformed_actions_are_refusals_over_http():+ """The realtime protocol: hostile act / wait / observe / ready / say bodies are 400s, the world runs on."""+ svc, post = service(["A", "B"], fmt="duel")+ srv, port = _http(svc, ("A", "B"))+ try:+ for s in ("A", "B"): # both seats start and review as usual; A also sends hostile bodies+ threading.Thread(target=play, args=(svc, post, s), daemon=True).start()+ t = time.time()+ while svc.phase != "running" and time.time() - t < 10:+ time.sleep(0.01)+ assert svc.phase == "running"+ for raw in [*HOSTILE_RAW, b'{"type": "move", "v": 0.5, "entity": "' + b"e" * 9000 + b'"}']:+ code, out = _post(port, "/A/act", raw)+ assert 400 <= code < 500, (raw[:40], code, out)+ assert "detail" not in out, out+ for ep, raw in (("wait", b'{"dt": 1' + b"0" * 400 + b"}"), ("wait", b'{"dt": [1]}'),+ ("observe", b'{"query": {"q": 1e999}}'), ("observe", b'{"query": [1]}'),+ ("say", b'{"text": ["x"]}'), ("ready", b'{"why": 1' + b"0" * 400 + b"}")):+ code, out = _post(port, f"/A/{ep}", raw)+ assert 400 <= code < 500, (ep, raw[:40], code, out)+ assert svc.reason != "technical_error" and not svc.errors, (svc.reason, svc.errors)+ assert svc.seats["A"].stats["refused_invalid"] >= 6 and svc.seats["A"].stats["refused"] >= 6+ finally:+ srv.shutdown()+ srv.server_close()+ fin = finish(svc)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++def test_check_body_and_check_action_limits():+ from core.sport import check_action, check_body+ for bad in (10 ** 400, 2 ** 70, float("nan"), float("inf"), 1e300, "x" * 9000, [0] * 5000,+ json.loads("[" * 20 + "]" * 20), {"k" * 9000: 1}):+ try:+ check_body({"v": bad})+ raise AssertionError(f"accepted {str(bad)[:20]}")+ except Refused:+ pass+ check_body({"type": "x", "q": [[0.1] * 8] * 600, "s": "ok", "n": None, "b": True, "i": -3})+ schema = {"go": {"v": {"type": "vector", "len": 3}, "r": {"type": "vector", "len": "1 or 2"},+ "rows": {"type": "rows", "len": 2, "max_rows": 3}, "o": {"type": "object", "keys": ["a"]},+ "e": {"type": "enum", "values": ["x"]}, "b": {"type": "boolean"}, "n": {"type": "number"}}}+ check_action(schema, {"type": "go", "v": [1, 2, 3], "r": [1], "rows": [[1, 2]], "o": {"a": 1}, "e": "x",+ "b": False, "n": 2})+ check_action(schema, {"rods": {}}) # an implicit type stays with the layer+ for body in ({"type": []}, {"type": 3}, {"type": "x" * 65}, {"type": "go", "v": [1, 2]},+ {"type": "go", "v": [1, 2, "3"]}, {"type": "go", "r": [1, 2, 3]}, {"type": "go", "rows": [[1]]},+ {"type": "go", "rows": [[1, 2]] * 4}, {"type": "go", "o": {"z": 1}}, {"type": "go", "e": ["x"]},+ {"type": "go", "b": 1}, {"type": "go", "n": "1"}, {"type": "go", "n": True}, [1]):+ try:+ check_action(schema, body)+ raise AssertionError(f"accepted {body}")+ except Refused:+ pass+# ------------------------------------------------------------------ unmetered seats (core 0.2.29)+def test_unmetered_seat_needs_no_meter_and_no_proxy():+ from core.launch import seat_mode+ from core.seats import Seat, validity_fields+ data = Path(tempfile.mkdtemp(prefix="core-test-"))+ os.environ["PLAYER_MODE_A"] = "unmetered"+ try:+ st = Seat("A", data)+ st.joined = True+ assert st.mode == "unmetered" and st.meter.decided_by_model() # acts pass without a metering proxy+ st.meter.check_ready()+ v = validity_fields({"A": st}, lambda s: s.mode == "model" and s.joined)+ assert v["meter_error"] == {"A": False} and v["proxy_error"] == {"A": False}+ assert v["player_modes"] == {"A": "unmetered"}+ assert seat_mode("A") == "unmetered" and seat_mode("B", {"RCB_PLAYER_MODE": "oracle"}) == "oracle"+ os.environ["PLAYER_MODE_A"] = "model"+ st = Seat("A", data)+ st.joined = True+ assert validity_fields({"A": st}, lambda s: s.mode == "model" and s.joined)["meter_error"] == {"A": True}+ os.environ["PLAYER_MODE_A"] = "metered-elsewhere"+ try:+ Seat("A", data)+ raise AssertionError("an unknown player mode must be refused")+ except ValueError:+ pass+ finally:+ os.environ.pop("PLAYER_MODE_A", None)+++# ------------------------------------------------------------------ core 0.2.13+def test_game_shortcuts_send_entity_and_enum_values_as_text():+ """The `game` shortcuts send `entity` as written and a value that is not a number (an enum value, true / false) as+ such; the core checks the body. Cores <= 0.2.12 sent robot 1 as entity "1.0" (refused) and exited with the usage+ text on an enum value."""+ from core.sport import MatchBase, SchemaLayer, parse_action+ cli = {"kick": ["kick", "entity", "power", "foot", "chip"]}+ game = {"__name__": "game"}+ exec(compile((ROOT / "core" / "game.py").read_text().replace("@@COMMANDS@@", json.dumps(cli)), "game", "exec"), game)+ sent = []+ game.update(call=lambda ep, body=None: sent.append(body) or {}, show=lambda out: None)+ game["main"](["kick", "1", "0.5", "left", "true"])+ assert sent == [{"type": "kick", "entity": "1", "power": 0.5, "foot": "left", "chip": True}], sent++ class Robots(MatchBase):+ def schema(self, seat):+ return {"kick": {"power": {"type": "number", "min": 0, "max": 1},+ "foot": {"type": "enum", "values": ["left", "right"]}, "chip": {"type": "boolean"}}}++ def entities(self, seat):+ return ("1", "2")+ assert parse_action(SchemaLayer(), "A", sent[0], Robots(), {}) == sent[0]+++def test_fairness_plays_and_counts_the_sides_of_a_team_format():+ """The fairness check plays a team format with its sides and judges it against one over the number of sides. The+ turn fixture's built-in player always adds 0.5, so the first side wins every match by the last tiebreak: +50 pp+ for the first side, 0 for seat A1 (whose side starts half the matches). Cores <= 0.2.12 played one side per seat+ (A1 won every match) and judged against 1/4: -25 pp and +75 pp."""+ from core import testkit+ rows = testkit.fairness(PLUGIN_TURN, matches=2)+ assert [r["name"] for r in rows] == ["fairness:team"], rows+ got = json.loads(rows[0]["detail"])+ assert got["N"] == 4 and got["first_side"]["advantage_pp"] == 50 and got["seat_A1"]["advantage_pp"] == 0, got+ assert not rows[0]["ok"]+++def test_replay_video_appears_only_when_complete():+ """The replay video is written to replay.part.mp4 and renamed once its writer has closed: a render that stops early+ (killed at RCB_VIDEO_TIMEOUT_S) leaves no replay.mp4 for the grader to count as rendered. Cores <= 0.2.12 wrote+ replay.mp4 in place."""+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ from core import episode, local, spectator+ sport = load_plugin(PLUGIN_IMG)+ cfg = MatchConfig(sport="fixture_images", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")++ class Mover:+ def act(self, view):+ return {"type": "add", "v": 0.5}+ data = Path(tempfile.mkdtemp(prefix="core-test-"))+ local.play(sport, cfg, {"A": Mover(), "B": Mover()}, data=data, render=False, plugin=PLUGIN_IMG)+ replay = episode.replay++ def stopped(sport, rows, observer): # the render stops after its first frame+ def first(match):+ observer(match)+ raise TimeoutError+ return replay(sport, rows, observer=first)+ episode.replay = stopped+ try:+ spectator.render_video(PLUGIN_IMG, data)+ raise AssertionError("the render went on")+ except TimeoutError:+ pass+ finally:+ episode.replay = replay+ assert (data / "replay.part.mp4").exists() and not (data / "replay.mp4").exists()+ info = spectator.render_video(PLUGIN_IMG, data)+ assert info["video"] and (data / "replay.mp4").stat().st_size and not (data / "replay.part.mp4").exists(), info+++def test_realtime_resume_time_is_not_game_time():+ """The world's clock restarts when Match.resume() has returned: a resume that takes 0.5 s (a sport setting up the+ next unit) no longer makes the loop run the missed control steps back to back. Cores <= 0.2.12 anchored the clock+ before resume(): the unit's first steps ran at once to catch up, the first one 0.5 s late."""+ World = type(SPORT.build(MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)))++ class SlowResume(World):+ def resume(self):+ time.sleep(0.5)+ super().resume()++ class SlowSport(type(SPORT)):+ def build(self, cfg):+ return SlowResume(cfg)++ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=1.0)+ svc = RealtimeService(SlowSport(), PLUGIN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ fin = run_all(svc, svc.routes(True), ["A", "B"])+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["sim_lag"]["late_max_s"] < 0.25, fin["sim_lag"]+++def test_entity_refused_from_a_seat_without_entities():+ """An act may name an entity only if the seat has entities (Match.entities); otherwise the core refuses it (400),+ in both protocols and in local play (parse_action). Cores <= 0.2.12 passed it on, and in real time every new+ entity string was a new act slot: one act in flight per (seat, entity), one pending act per (seat, entity)."""+ from core.sport import SchemaLayer, parse_action+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)+ world = SPORT.build(cfg)++ class OneBody(type(world)): # the realtime fixture's world without entities+ def entities(self, seat):+ return ()+ game = SPORT_TURN.build(MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=1, first="A"))+ assert parse_action(SchemaLayer(), "A", {"type": "move", "v": 0.5, "entity": "e1"}, world, {})["entity"] == "e1"+ for layer, m, body in ((SchemaLayer(), OneBody(cfg), {"type": "move", "v": 0.5}),+ (SPORT_TURN.action_layer("low"), game, {"v": 0.5})):+ for entity in ("x1", "x2", 7):+ try:+ parse_action(layer, "A", {**body, "entity": entity}, m, {})+ raise AssertionError(f"{type(m).__name__} accepted entity {entity!r}")+ except Refused as e:+ assert e.code == 400 and "entit" in str(e), e+ assert "entity" not in parse_action(layer, "A", body, m, {})+++# ------------------------------------------------------------------ core 0.2.16: the budget of the authenticated seat+class _Held:+ """A service whose `hold` stays open until the gate opens (open requests); `ping` answers at once."""++ def __init__(self):+ self.gate, self.entered = threading.Event(), threading.Semaphore(0)++ def routes(self, post):+ return {"hold": self.hold, "ping": lambda seat, body: (200, {"seat": seat})}++ def hold(self, seat, body):+ self.entered.release()+ self.gate.wait(30)+ return 200, {"seat": seat}++ def failure(self, ep, exc):+ pass+++def _call(port, path, timeout=30):+ """One POST without retries: (status, raw body); a connection refused before its request was read (closed while+ the client still wrote it, which core/client.py retries like a bare 429) is (429, b"")."""+ import urllib.error+ import urllib.request+ req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data=b"{}", method="POST",+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.status, r.read()+ except urllib.error.HTTPError as e:+ return e.code, e.read()+ except urllib.error.URLError as e:+ if isinstance(e.reason, (BrokenPipeError, ConnectionResetError)):+ return 429, b""+ raise+++def _hold(port, svc, seats, n=4):+ """n held requests per seat, each in its own thread; returns (threads, results) once all reached the service."""+ results, threads = [], []+ for s in seats:+ for _ in range(n):+ t = threading.Thread(target=lambda s=s: results.append((s, _call(port, f"/{s}/hold"))), daemon=True)+ t.start()+ threads.append(t)+ for _ in range(n * len(seats)):+ assert svc.entered.acquire(timeout=15), f"held requests refused: {results}"+ return threads, results+++def test_http_budget_belongs_to_the_authenticated_seat():+ """core 0.2.16: without SEAT_HOSTS every local seat may be any seat; each seat has its own 4 open requests and+ 20 per second (cores <= 0.2.15 charged every local connection to the first seat: a team format's 8 local seats+ shared 4 slots and got 429s). The 429 of a full seat is bare (core/client.py retries it), other seats go on."""+ from core.http import make_server+ seats = ("A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4")+ svc = _Held()+ srv = make_server(svc, seats, {}, port=0)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ port = srv.server_address[1]+ try:+ threads, results = _hold(port, svc, ["A1"])+ assert _call(port, "/A1/ping") == (429, b""), "a seat over its own 4 open requests"+ code, raw = _call(port, "/B1/ping")+ assert code == 200 and json.loads(raw) == {"seat": "B1"}, (code, raw)+ more, results2 = _hold(port, svc, seats[1:]) # every other seat: 4 open requests each, 32 in all+ svc.gate.set()+ for t in threads + more:+ t.join(15)+ got = results + results2+ assert len(got) == 32 and all(c == 200 and json.loads(raw)["seat"] == s for s, (c, raw) in got), got+ time.sleep(1.1) # a new second for every seat+ codes = [_call(port, "/A2/ping")[0] for _ in range(30)]+ assert codes[:20] == [200] * 20 and 429 in codes, codes # A2's 20 per second ...+ code, raw = _call(port, "/A3/ping")+ assert code == 200 and json.loads(raw) == {"seat": "A3"}, (code, raw) # ... are not A3's+ finally:+ svc.gate.set()+ srv.shutdown()+ srv.server_close()+++def test_http_seat_never_spends_another_seats_budget():+ """core 0.2.16: a request for a seat its address may not be (SEAT_HOSTS) is refused (403) before it spends any+ seat's budget, and before a request is read an address holds only the budget of the seats it may be."""+ from core.http import make_server+ svc = _Held()+ srv = make_server(svc, ("A", "B"), {"B": "192.0.2.1"}, port=0) # B's container: never this host (TEST-NET-1)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ port = srv.server_address[1]+ try:+ for _ in range(8):+ time.sleep(0.06)+ assert _call(port, "/B/ping")[0] == 403, "impersonating B"+ assert srv.arrivals["B"] == [] and srv.slots["B"].acquire(False), "B's budget spent by another address"+ srv.slots["B"].release()+ code, raw = _call(port, "/A/ping")+ assert code == 200 and json.loads(raw) == {"seat": "A"}, (code, raw)+ time.sleep(1.1)+ threads, results = _hold(port, svc, ["A"])+ assert _call(port, "/A/ping") == (429, b"") # this address may be A only: A's 4 open requests+ assert _call(port, "/B/ping") == (429, b"") # and no more, whatever seat the path names+ svc.gate.set()+ for t in threads:+ t.join(15)+ assert [c for _, (c, _) in results] == [200] * 4, results+ finally:+ svc.gate.set()+ srv.shutdown()+ srv.server_close()+++# ------------------------------------------------------------------ core 0.2.17: the testkit's replay limit+def test_testkit_replay_timeout_from_sport_toml():+ """core 0.2.17: the fresh-process replays of the generic tests (determinism, solo_quit) take sport.toml [timing]+ replay_timeout_s when it is above 1800 s (a 600 s match replays in more than 1800 s), never less than 1800 s;+ a replay over the limit is a failed row that names the limit, not a crash of the suite."""+ import subprocess+ from core import testkit+ assert testkit.replay_timeout({}) == 1800+ assert testkit.replay_timeout({"timing": {"slowdown": 20}}) == 1800+ assert testkit.replay_timeout({"timing": {"replay_timeout_s": 600}}) == 1800 # the task's default: no tighter+ assert testkit.replay_timeout({"timing": {"replay_timeout_s": 3600}}) == 3600+ decl = {"formats": {"duel": {"seats": ["A", "B"], "first": ["A"]}}, "modes": {"action_levels": ["low"]},+ "timing": {"replay_timeout_s": 4321}}+ seen, run = [], subprocess.run++ def spy(cmd, **kw):+ seen.append(kw.get("timeout"))+ return run(cmd, **kw)+ testkit.subprocess.run = spy+ try:+ rows = testkit.t_determinism(SPORT_TURN, PLUGIN_TURN, decl)+ assert seen == [4321] and all(r["ok"] for r in rows), (seen, rows)++ def slow(cmd, **kw):+ raise subprocess.TimeoutExpired(cmd, kw["timeout"])+ testkit.subprocess.run = slow+ rows = testkit.t_determinism(SPORT_TURN, PLUGIN_TURN, decl)+ finally:+ testkit.subprocess.run = run+ bad = {r["name"]: r for r in rows}["determinism:fresh_process_replay"]+ assert not bad["ok"] and "4321 s" in bad["detail"] and "replay_timeout_s" in bad["detail"], rows++++def test_team_channel_reads_after_a_seq_never_consume():+ """core 0.2.20: every message has a per-side seq; reads with a read mark return each message after it once per+ read mark, any number of clients; without a read mark the recent window (recent_s game seconds, at most recent_max);+ POST /team pages through the log; the limits of say are unchanged."""+ from core.channel import TeamChannel+ cfg = MatchConfig(sport="fixture", format="team", seats=("A1", "A2", "B1", "B2"), seed=1,+ sides={"A1": "A", "A2": "A", "B1": "B", "B2": "B"})+ ch = TeamChannel(cfg, {"max_bytes": 64, "min_interval_s": 0.2, "max_messages": 4, "recent_s": 1.0,+ "recent_max": 2})+ dt = 0.02+ assert ch.say("A1", "a", 0, dt)[1]["sent"]["seq"] == 1+ assert ch.say("A1", "b", 5, dt)[0] == 429 # 0.2 s between two messages of one seat+ assert ch.say("A2", "c", 5, dt)[1]["sent"]["seq"] == 2 # one seq per side+ assert ch.say("B1", "z", 5, dt)[1]["sent"]["seq"] == 1 # the other side counts its own+ assert ch.say("A1", "d", 10, dt)[1]["sent"]["seq"] == 3+ assert ch.say("A1", "e", 100, dt)[1]["sent"]["seq"] == 4+ for _ in range(3): # never consumed+ msgs, top = ch.messages("A2", 100, dt, since=0)+ assert [m["text"] for m in msgs] == ["a", "d", "e"] and top == 4, (msgs, top)+ assert [m["seq"] for m in ch.messages("A2", 100, dt, since=3)[0]] == [4]+ assert ch.messages("A2", 100, dt, since=4)[0] == []+ assert [m["text"] for m in ch.messages("A2", 100, dt)[0]] == ["e"] # recent: the last 1.0 s only+ assert [m["text"] for m in ch.messages("A2", 10, dt)[0]] == ["a", "d"] # at step 10: both within 1 s, max 2+ assert [m["text"] for m in ch.messages("B2", 100, dt, since=0)[0]] == ["z"]+ assert ch.messages("A1", 100, dt, since=0)[0][0]["text"] == "c" # A1 sees A2's only+ code, page = ch.page("A2", 100, 1)+ assert code == 200 and [m["seq"] for m in page["messages"]] == [3, 4] and page["team_seq"] == 4+ assert not page["more"]+ ch.page_max = 1+ assert ch.page("A2", 100, 0)[1]["more"] and len(ch.page("A2", 100, 0)[1]["messages"]) == 1+ assert ch.say("A1", "f", 200, dt)[0] == 200 # A1's 4th message+ assert ch.say("A1", "g", 300, dt)[0] == 429 # max_messages (4 per seat) unchanged+ off = TeamChannel(cfg, None)+ assert off.messages("A1", 0, dt) == ([], 0) and off.page("A1", 0, 0)[0] == 404+++def test_team_channel_turn_protocol_and_http_since():+ """core 0.2.20: the turn protocol reads the channel the same way (status / wait / observe with team_since, POST+ /team), and an HTTP GET carries the read mark as ?team_since=N (anything but a small integer is a 400)."""+ from core.http import make_server+ sides = {"A1": "A", "A2": "A", "B1": "B", "B2": "B"}+ svc, post = turn_service(list(sides), sides, fmt="team")+ if not svc.channel.enabled: # the turn fixture declares no channel+ svc.channel.declared = svc.channel.enabled = True+ assert post["say"]("A1", {"text": "hi"})[0] == 200+ get = svc.routes(False)+ st = get["status"]("A2", {})[1]["state"]+ assert [m["text"] for m in st["team_messages"]] == ["hi"] and st["team_seq"] == 1+ assert get["status"]("A2", {"team_since": 1})[1]["state"]["team_messages"] == []+ assert get["team"]("A2", {"since": 0})[1]["messages"][0]["from"] == "A1"+ srv = make_server(svc, tuple(sides), {}, port=0)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ port = srv.server_address[1]+ import urllib.error+ import urllib.request++ def fetch(path):+ try:+ with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=10) as r:+ return r.status, json.load(r)+ except urllib.error.HTTPError as e:+ return e.code, json.load(e)+ try:+ code, out = fetch("/A2/status?team_since=0")+ assert code == 200 and out["state"]["team_messages"][0]["text"] == "hi", out+ code, out = fetch("/A2/status?team_since=1")+ assert code == 200 and out["state"]["team_messages"] == [], out+ assert fetch("/A2/status?team_since=-3")[0] == 400+ assert fetch("/A2/status?team_since=abc")[0] == 400+ code, out = fetch("/A2/team?since=0")+ assert code == 200 and out["messages"][0]["text"] == "hi", out+ finally:+ srv.shutdown()+ srv.server_close()+++def test_requests_after_the_end_never_void_a_finished_match():+ """core 0.2.26: once a match is over, observe / act answer 409 with the final state and draw nothing (realtime and+ turn); after finalization the render workers are closed, so a late draw returns no images and a late request's+ failure is only logged: a player that keeps observing after the end (713 broken pipes in a four-seat match)+ never voids the finished, replayed match."""+ svc, post = service(["A", "B"], fmt="duel")+ fin = run_all(svc, post, ["A", "B"])+ assert fin["valid_trial"] and svc.finalized, fin["errors"]++ class Closed: # a render worker after finalize(): every call is a broken pipe+ lock = threading.Lock()++ def call(self, job, wait=True):+ raise BrokenPipeError(32, "Broken pipe")++ def close(self):+ pass+ svc.workers["render", "A"] = Closed()+ code, out = post["observe"]("A", {})+ assert code == 409 and out["error"] == "the match is over" and out["now"]["done"], (code, out)+ assert "observation" not in out+ code, out = post["act"]("A", {"type": "move", "v": 0.5})+ assert code == 409 and out["now"]["done"], (code, out)+ assert svc.draw("A", {"state": {}, "cams": []}) is None # finalized: nothing drawn+ svc.failure("observe", BrokenPipeError(32, "Broken pipe")) # what core/http.py reports+ with svc.cond:+ svc.write_final()+ fin2 = json.loads((svc.data / "final.json").read_text())+ assert fin2["valid_trial"] and not fin2["technical_failure"] and fin2["errors"] == fin["errors"], fin2+ assert fin2["winner"] == fin["winner"] and svc.phase == "over"++ tsvc, tpost = turn_service(["A", "B"])+ th = [threading.Thread(target=play_turn, args=(tsvc, tpost, s), daemon=True) for s in ("A", "B")]+ for t in th:+ t.start()+ tfin = finish(tsvc)+ assert tfin["valid_trial"], tfin["errors"]+ for ep in ("observe", "act"):+ code, out = tpost[ep]("A", {"v": 0.5} if ep == "act" else {})[:2]+ assert code == 409 and out["error"] == "the match is over" and out["state"]["done"], (ep, code, out)+++_SPECTATOR_PLUGIN = """import importlib.util, os+_spec = importlib.util.spec_from_file_location("fixture_images_base", os.environ["RO_TEST_FIXTURE_IMAGES"])+_base = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_base)+EXTRA = '<geom name="spectators_only" type="box" pos="0.5 0.5 0.2" size="0.2 0.2 0.2" rgba="1 1 0 1"/>'+++class Game(_base.Game):+ def spectator_state(self):+ with open(os.environ["RO_TEST_SPECTATOR_LOG"], "a") as f:+ f.write("x\\n")+ return self.render_state()+++class Fixture(_base.Fixture):+ def build(self, cfg):+ return Game(cfg)++ def spectator_scene(self, cfg):+ from renderers.base import Scene+ if os.environ.get("RO_TEST_SPECTATOR_FAIL"):+ raise RuntimeError("no spectator scene here")+ return Scene(xml=_base.XML.replace("</worldbody>", EXTRA + "</worldbody>"))+++SPORT = Fixture()+"""+++def test_sport_spectator_scene_and_state_draw_the_video_only():+ """core 0.2.28: a sport's own spectator scene (Sport.spectator_scene(cfg)) with Match.spectator_state() draws the+ replay video; RO_VIDEO_SCENE=match and a failing spectator_scene fall back to the match scene; the players' scene+ (Sport.scene) is untouched and the episode replays to the same digest."""+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ from core import local, spectator+ from core.episode import read_rows, replay+ tmp = Path(tempfile.mkdtemp(prefix="core-test-"))+ plugin = tmp / "plugin.py"+ plugin.write_text(_SPECTATOR_PLUGIN)+ shutil.copy2(Path(PLUGIN_IMG).parent / "sport.toml", tmp / "sport.toml")+ log = tmp / "spectator.log"+ os.environ["RO_TEST_FIXTURE_IMAGES"] = PLUGIN_IMG+ os.environ["RO_TEST_SPECTATOR_LOG"] = str(log)+ try:+ sport = load_plugin(str(plugin))+ cfg = MatchConfig(sport="fixture_images", format="duel", seats=("A", "B"), seed=1, first="A",+ action_level="low")+ sc, what = spectator.spectator_scene(sport, str(plugin), cfg)+ assert what == "spectator" and "spectators_only" in sc.xml and "spectators_only" not in sport.scene(cfg).xml+ os.environ["RO_VIDEO_SCENE"] = "match"+ try:+ sc2, what2 = spectator.spectator_scene(sport, str(plugin), cfg)+ finally:+ del os.environ["RO_VIDEO_SCENE"]+ assert what2 == "match" and "spectators_only" not in sc2.xml+ os.environ["RO_TEST_SPECTATOR_FAIL"] = "1"+ try:+ sc3, what3 = spectator.spectator_scene(sport, str(plugin), cfg)+ finally:+ del os.environ["RO_TEST_SPECTATOR_FAIL"]+ assert what3.startswith("match (spectator scene unavailable") and "spectators_only" not in sc3.xml++ class Mover:+ def act(self, view):+ return {"type": "add", "v": 0.5}+ data = tmp / "run"+ r = local.play(sport, cfg, {"A": Mover(), "B": Mover()}, data=data, render=False, plugin=str(plugin))+ assert not log.exists() # the match itself never asks for the spectator state+ info = spectator.render_video(str(plugin), data)+ assert info["video"] and info["scene"] == "spectator" and info["label"] is None, info+ n = len(log.read_text().splitlines()) # one spectator state per drawn frame (held 1 s: turn protocol)+ assert n > 0 and info["frames"] == n * 10, (info, n)+ rep = replay(sport, read_rows(data / "episode.jsonl"))+ assert rep["state_sha"] == r["digest"], (rep, r)+ finally:+ for k in ("RO_TEST_FIXTURE_IMAGES", "RO_TEST_SPECTATOR_LOG"):+ os.environ.pop(k, None)++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/test_diagnose.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/test_diagnose.pynew file mode 100644index 0000000000..5331675bef--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/tests/test_diagnose.py@@ -0,0 +1,193 @@+"""Tests of the diagnostic records (core/diaglog.py, core 0.2.25) and the post-match diagnosis (core/diagnose.py):+in-process matches (core/local.py) of the realtime fixture and the live realtime service (a turn-protocol+example: the example sport's tests/test_diagnose.py). Run in the sim image:+ docker run --rm -v $PWD:/w -w /w -e MUJOCO_GL=osmesa ghcr.io/mll-lab-nu/eai-olympiad:0.1.0 \\+ python3 core/tests/test_diagnose.py+"""+from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import threading+import time+from pathlib import Path++HERE = Path(__file__).resolve().parent+ROOT = HERE.parents[1]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(HERE))++import test_core as tc # noqa: E402 (service helpers; sets the short timeouts)+from core import diagnose, local # noqa: E402+from core.episode import load_plugin, read_rows, replay # noqa: E402+from core.sport import MatchConfig # noqa: E402++++class Mover:+ """A fixture player: every observation, move entity e0 (and e1 every other time)."""++ def __init__(self, v=0.3):+ self.v, self.n = v, 0++ def act(self, view):+ self.n += 1+ return {"type": "move", "v": self.v if self.n % 2 else -self.v, "entity": "e0" if self.n % 3 else "e1"}+++def fixture_local(delay=0):+ os.environ["FIXTURE_DELAY"] = str(delay)+ try:+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)+ d = Path(tempfile.mkdtemp(prefix="diag-fx-"))+ res = local.play(tc.SPORT, cfg, {"A": Mover(0.3), "B": Mover(-0.2)}, data=d, render=False,+ plugin=tc.PLUGIN, every=4)+ return d, res+ finally:+ os.environ.pop("FIXTURE_DELAY", None)+++def test_local_rows_link_every_act():+ d, res = fixture_local()+ rep = diagnose.load(d, tc.PLUGIN)+ assert rep["interface"] == diagnose.INTERFACE and all(rep["has"][n] for n in ("observe", "act_received",+ "effect", "event"))+ link = diagnose.linkage(rep)+ for seat in ("A", "B"):+ L = link[seat]+ assert L["acts"] > 10 and L["act_ids_contiguous"], L+ assert L["with_observation"] == L["acts"] and L["effect"] == L["acts"] == L["effect_with_cmd"], L+ assert L["unresolved"] == 0 and L["both"] == 0, L+ for a in rep["acts"][seat]:+ assert a["k_obs"] == a["k_recv"] == a["k_effect"] and a["view_steps"] == [], a+ # events: one per unit end, with the step at which the unit ended+ assert [e["k"] for e in rep["events"]] == [30, 60, 90], rep["events"]+ # the replay rows are unchanged by the diagnostic rows: the fresh replay gives the local result+ sport = load_plugin(tc.PLUGIN)+ assert replay(sport, read_rows(d / "episode.jsonl"))["state_sha"] == res["digest"]+++def test_local_delayed_effects_and_drops():+ d, _ = fixture_local(delay=3)+ rep = diagnose.load(d, tc.PLUGIN)+ link = diagnose.linkage(rep)+ for seat in ("A", "B"):+ L = link[seat]+ assert L["unresolved"] == 0 and L["both"] == 0 and L["dropped"] > 0, L+ assert set(L["dropped_by"]) <= {"unit_over", "match_over"}, L+ for a in rep["acts"][seat]:+ if a["k_effect"] is not None:+ assert a["k_effect"] == a["k_recv"] + 3, a+++def test_world_at_matches_the_replay():+ d, res = fixture_local(delay=2)+ rep = diagnose.load(d, tc.PLUGIN)+ w = rep["world"]()+ m = w.at(45)+ assert m.k == 45+ pos45 = dict(m.pos)+ w.at(90)+ assert w.k == 90+ assert w.at(45).pos == pos45 # backwards: rebuilt, same state+ w2 = rep["world"]()+ assert w2.run().state_digest() == res["digest"]+ assert sorted(w2.events) == [30, 60, 90]+ # before / after the rows of a step: an effect at step k changes the velocity, not yet the position+ a = next(a for a in rep["acts"]["A"] if a["k_effect"] is not None and a["k_effect"] > 5)+ pre = rep["world"]().at(a["k_effect"])+ post = rep["world"]().at(a["k_effect"], after=True)+ key = f"A.{a['decision']['entity']}"+ assert post.vel[key] == a["cmd"]["v"] and pre.pos == post.pos+++def test_turn_service_rows():+ svc, post = tc.turn_service(["A", "B"])++ def loop(seat):+ post["start"](seat, {})+ while svc.phase != "over":+ st = post["wait"](seat, {"timeout_s": 1})[1]["state"]+ if st["done"] or not st["your_turn"]:+ continue+ if st["awaiting_review"]:+ post["ready"](seat, {"why": "w", "plan": "p"})+ else:+ post["observe"](seat, {})+ post["act"](seat, {"v": 0.5})+ th = [threading.Thread(target=loop, args=(s,), daemon=True) for s in ("A", "B")]+ for t in th:+ t.start()+ final = tc.finish(svc)+ assert final["valid_trial"], final+ rep = diagnose.load(svc.data, tc.PLUGIN_TURN)+ link = diagnose.linkage(rep)+ for seat in ("A", "B"):+ L = link[seat]+ assert L["acts"] > 0 and L["with_observation"] == L["acts"] == L["effect"] == L["effect_with_cmd"], L+ for a in rep["acts"][seat]:+ assert a["k_obs"] == a["k_recv"] == a["k_effect"], a+ w = rep["world"]()+ assert w.run().state_digest() == final["state_sha"]+++def test_service_rows_link_acts_effects_and_team_delivery():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ os.environ["FIXTURE_DELAY"] = "2"+ try:+ svc, post = tc.service(list(sides), sides)+ finally:+ os.environ.pop("FIXTURE_DELAY", None)+ said = []++ def act(seat, post):+ post["observe"](seat, {})+ post["act"](seat, {"type": "move", "v": 0.2, "entity": "e0"})+ if seat == "A1" and not said and svc.phase == "running":+ said.append(post["say"](seat, {"text": "go"})[0])+ final = tc.run_all(svc, post, list(sides), **{s: {"act": act} for s in sides})+ assert final["valid_trial"], final+ rep = diagnose.load(svc.data, tc.PLUGIN)+ link = diagnose.linkage(rep)+ for seat in sides:+ L = link[seat]+ assert L["acts"] > 0 and L["act_ids_contiguous"] and L["unresolved"] == 0 and L["both"] == 0, (seat, L)+ assert L["with_observation"] == L["acts"], (seat, L)+ assert L["effect"] == L["effect_with_cmd"], (seat, L)+ for a in rep["acts"][seat]:+ if a["k_effect"] is not None:+ assert a["k_effect"] - a["k_recv"] >= 2 and a["k_obs"] <= a["k_recv"], a+ # the reaction report (core 0.2.23) agrees with the act rows: acts with an effect = the report's acts+ rr = final["reaction"]["by_seat"]+ for seat in sides:+ assert rr[seat]["acts"] == link[seat]["effect"], (rr[seat], link[seat])+ assert [e["k"] for e in rep["events"]] == [30, 60, 90]+ if said == [200]:+ got = [r for r in rep["team_delivered"] if r["from"] == "A1"]+ assert [r["seat"] for r in got] == ["A2"], got # the teammate, once; never the other side+ assert got[0]["k"] >= got[0]["sent_k"]+ # the diagnostic rows are not replayed: the fresh replay of the service's episode passed+ assert final["deterministic"]+++def main():+ tests = [(n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)]+ bad = 0+ for name, f in tests:+ t = time.time()+ try:+ f()+ print(f"ok {name} ({time.time() - t:.1f} s)")+ except Exception: # noqa: BLE001+ import traceback+ bad += 1+ print(f"FAIL {name}\n{traceback.format_exc()}")+ print(f"{len(tests) - bad}/{len(tests)} passed")+ return 1 if bad else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/turn.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/turn.pynew file mode 100644index 0000000000..59c40b1944--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/turn.py@@ -0,0 +1,349 @@+"""Protocol eai-standard-turn/1.0: turns decided by the plugin (Match.to_move), one chess clock per seat (CLOCK_S of+wall time, running only on its own turn, service time excluded; out of time = the match is lost), and after every+action that does not end the match its actor reviews (ready WHY PLAN) before play goes on.++Phases: prepare (until every seat sent start; after the first, START_TIMEOUT_S: a side that has not started by then+loses, "no_show"; if none started, incomplete; a single side has START_TIMEOUT_S from the service start, else it+loses; the collect before the start decides the same at once, core 0.2.7) -> play -> over.+An action or review out of turn: 409; one action in flight per seat: 429; a seat that stops playing on its turn+(collect hook) loses ("abandoned"); a single side whose match has started loses at the collect whoever is on turn+(core 0.2.6). With more than two sides a side that loses on the clock may retire while the+others play on (Match.retire); observations may carry a query (observation parameters) that the sport validates.+Images (core 0.2.8): the observation's cameras and an action's reply images (Match.reply_views) are snapshotted under+the lock and drawn after it is released, so drawing never blocks the other seats; the seat's clock stands still+while its images are drawn. The core tells the sport whose review is due (Match.awaiting_review).+"""+from __future__ import annotations++import base64+import os+import threading+import time+import traceback++from .diaglog import jsonable, view_steps+from .service import Service+from .realtime import query_of+from .sport import FINISHED, Refused, parse_action++WAIT_MAX_S = 60.0+REVIEW_MAX_CHARS = 2000+++class TurnService(Service):+ protocol = "turn"+ protocol_id = "eai-standard-turn/1.0"++ def __init__(self, *a, **kw):+ self.clock_s = float(os.environ.get("CLOCK_S", "3600"))+ super().__init__(*a, clock_s=self.clock_s, **kw)+ self.start_deadline = self.on_turn = self.review_due = None+ if len(self.cfg.side_list()) == 1: # nobody to wait for: the start window opens now+ self.start_deadline = time.time() + self.start_window()+ for st in self.seats.values():+ st.stats.update(n_act=0, n_observe=0, n_wait=0, refused_busy=0, refused_turn=0, refused_not_model=0,+ refused_invalid=0, n_reviews=0)++ def routes(self, post):+ fns = ({"start": self.start, "observe": self.observe, "act": self.act, "ready": self.ready, "wait": self.wait}+ if post else {"spec": self.spec, "status": self.status})+ out = {ep: self.guarded(ep, fn) for ep, fn in fns.items()}+ if post:+ out["say"] = self.say+ out["team"] = self.team # read-only, never consumes (core 0.2.20)+ return out++ @property+ def review_due(self):+ return self._review_due++ @review_due.setter+ def review_due(self, seat):+ """The seat whose review is due; the sport sees it as Match.awaiting_review (core 0.2.8)."""+ self._review_due = seat+ self.m.awaiting_review = seat++ def guarded(self, ep, fn):+ """Every call runs under the lock, its service time is taken off the caller's clock, final.json follows. A+ handler may return (code, reply, job): the job (images) is drawn after the lock is released, with the+ caller's clock stopped, and attached to the reply as `observation`."""+ def run(seat, body):+ if ep == "spec":+ return fn(seat, body)+ st = self.seats[seat]+ if ep == "act" and not st.act_lock().acquire(blocking=False):+ with self.cond:+ st.count("refused_busy")+ return 429, {"refused": True, "busy": True, "error": "busy: one action at a time"}+ try:+ with self.cond:+ t = time.time()+ try:+ res = fn(seat, body)+ except Exception as exc: # noqa: BLE001+ if exc.__class__.__name__ == "Refused":+ raise+ traceback.print_exc()+ self.failure(ep, exc)+ return 500, {"error": "technical failure"} # details: the logs, never the player+ finally:+ if ep not in ("wait", "status"):+ self.busy(seat, t)+ self.write_final()+ if len(res) == 2 or res[2] is None:+ return res[:2]+ st.freeze(time.time())+ return self.finish_images(ep, seat, *res)+ finally:+ if ep == "act":+ st.act_lock().release()+ return run++ def finish_images(self, ep, seat, code, out, job):+ """Off the lock: draw `job` and attach it (observe: the camera images; act: the result of the action)."""+ st = self.seats[seat]+ try:+ obs = self.reply_images(seat, job) if ep == "act" else self.observe_images(seat, job, out["observation"])+ except Exception as exc: # noqa: BLE001+ traceback.print_exc()+ with self.cond:+ st.thaw(time.time())+ self.failure(f"{ep}_images", exc)+ with self.cond:+ self.write_final()+ return 500, {**out, "error": "technical failure"}+ with self.cond:+ st.thaw(time.time())+ self.write_final()+ out["observation"] = obs+ return code, out++ def observe_images(self, seat, job, meta) -> dict:+ out = self.draw(seat, job)+ obs = dict(meta)+ if out is not None:+ obs = {"image_png_b64": base64.b64encode(out["png"]).decode(), **meta}+ if out.get("tiles"):+ obs["tiles"] = out["tiles"]+ return obs++ def spec_core(self):+ return {"clock": {"total_s": self.clock_s, "runs": "on your turn only (your actions and your reviews); the "+ "time the service is busy does not count; out of time = you lose the match",+ "start_window_s": self.start_window()},+ "start": self.start_rule(),+ "decision_rule": ("program play: your own program may act without a new model response; one action "+ "in flight" if os.environ.get("RCB_ACT_RULE") == "program" else+ "a new model response before every action")}++ # ------------------------------------------------------------------ clock and turns+ def set_turn(self, seat):+ now = time.time()+ if self.on_turn is not None:+ self.seats[self.on_turn].stop_turn(now)+ self.on_turn = seat+ if seat is not None:+ self.seats[seat].start_turn(now)+ self.ep.write("turn", seat=seat, clock_left_s=round(self.seats[seat].clock_left(), 1))+ self.cond.notify_all()++ def busy(self, seat, t):+ st = self.seats[seat]+ if self.on_turn == seat and st.turn_t0 is not None:+ st.turn_busy += time.time() - max(t, st.turn_t0)++ def on_end(self):+ self.set_turn(None)++ def lose(self, seat, why):+ if super().lose(seat, why): # retired; the others play on+ self.review_due = None if self.review_due == seat else self.review_due+ if self.phase == "play" and (self.on_turn == seat or self.on_turn is None+ or self.seats[self.on_turn].retired):+ self.set_turn(self.m.to_move())+ return True+ return False++ # ------------------------------------------------------------------ replies+ def state(self, seat, query=None, since=None):+ others = [s for s in self.cfg.seats if s != seat]+ if self.phase == "prepare":+ turn = "start" if not self.seats[seat].joined else "waiting for the opponent to start"+ elif self.phase == "over":+ turn = "over"+ elif self.on_turn == seat:+ turn = "review" if self.review_due == seat else "you"+ else:+ turn = "opponent"+ out = {"seat": seat, "phase": self.phase, "turn": turn, "your_turn": turn in ("you", "review"),+ "awaiting_review": self.review_due == seat, "done": self.phase == "over",+ **self.observation(seat, query, since), "clock_left_s": round(self.seats[seat].clock_left(), 1)}+ if self.retired:+ out["retired"] = list(self.retired)+ if len(others) == 1:+ out["opponent_clock_left_s"] = round(self.seats[others[0]].clock_left(), 1)+ if self.phase == "over":+ o = self.outcome()+ w, side = o.winner, self.cfg.side_of(seat)+ out.update({"reason": self.reason, "won": w == side,+ "winner": None if w is None else ("you" if w == side else "opponent")})+ if len(self.cfg.side_list()) > 2:+ out["place"] = o.ranking.index(side) + 1 if side in o.ranking else None+ return out++ def status(self, seat, body=None):+ return 200, {"state": self.state(seat, since=self.team_since(body))}++ def gate(self, seat):+ if self.phase == "over": # core 0.2.26: 409 and the final state, nothing drawn+ return 409, {"error": "the match is over", "state": self.state(seat)}+ if self.phase == "prepare":+ return 409, {"error": "the match has not started (both players must send start)", "state": self.state(seat)}+ return None++ def start(self, seat, body):+ st = self.seats[seat]+ if self.phase != "prepare" or st.joined:+ return 409, {"error": "already started", "state": self.state(seat)}+ st.meter.check_ready()+ st.joined = True+ self.ep.write("start", seat=seat)+ if all(s.joined for s in self.seats.values()):+ self.begin()+ else:+ self.start_deadline = time.time() + self.start_window()+ self.cond.notify_all()+ return 200, {"started": True, "state": self.state(seat)}++ def begin(self):+ self.phase, self.start_deadline = "play", None+ self.bc.event("run")+ self.bc.frame(force=True)+ self.set_turn(self.m.to_move())++ def observe(self, seat, body):+ g = self.gate(seat)+ if g:+ return g+ query = query_of(body)+ since = self.team_since(body)+ self.seats[seat].count("n_observe")+ (job, meta), now = self.query_guard(seat, query, lambda: (self.camera_job(seat, query),+ self.state(seat, query, since)))+ obs_id = self.seats[seat].stats["n_observe"] # diagnostics (core 0.2.25): never replayed+ self.diag("observe", seat=seat, obs_id=obs_id, k=self.m.k, view_steps=view_steps(meta, job, self.m.k),+ query=query)+ self.acts.observed(seat, obs_id)+ return 200, {"state": now, "observation": dict(meta)}, job # drawn off the lock++ def act(self, seat, body):+ g = self.gate(seat)+ if g:+ return g+ st = self.seats[seat]+ if self.on_turn != seat or self.review_due == seat:+ st.count("refused_turn")+ why = "review your last action first" if self.review_due == seat else "it is not your turn"+ return 409, {"error": why, "state": self.state(seat)}+ try:+ cmd = parse_action(self.layer, seat, body, self.m, {"clock_left_s": {s: x.clock_left() for s, x in+ self.seats.items()}})+ except Refused as exc: # a malformed action: the player's own error, never a failure+ self.refused_invalid(seat, exc)+ raise+ if not st.meter.decided_by_model():+ st.count("refused_not_model")+ return 429, {"refused": True, "error": "refused: no new model response since your previous action"}+ st.count("n_act")+ if st.clock_left() < 0:+ self.lose(seat, "clock")+ return 200, {"clock_forfeit": "your clock ran out: you lose the match", "state": self.state(seat)}+ low, info = self.layer.lower(seat, cmd, None, self.m)+ act_id = self.acts.new(seat) # diagnostics (core 0.2.25): act -> observation -> effect+ self.diag("act_received", seat=seat, k=self.m.k, act_id=act_id, obs_id_last=self.acts.last_obs.get(seat),+ decision=cmd)+ self.ep.write("cmd", k=self.m.k, seat=seat, cmd=low, model_call=st.meter.last_call(),+ clock_used_s=round(st.clock_used(), 1))+ k_cmd = self.m.k+ applied = self.m.apply(seat, low) or {}+ self.diag("effect", seat=seat, act_id=act_id, k=k_cmd, info=jsonable(applied),+ **({"rejected": True} if "rejected" in applied else {}))+ job = self.reply_job(seat, low, applied) # the result's images: snapshot now, drawn off the lock+ info = {**applied, **info}+ self.bc.frame(force=True)+ self.bc.event("action", seat=seat, scores=self.m.scores())+ if self.m.phase().state == FINISHED:+ self.end("match_over")+ else:+ self.review_due = seat+ return 200, {**self.layer.reply(seat, cmd, info, self.m), "state": self.state(seat)}, job++ def ready(self, seat, body):+ g = self.gate(seat)+ if g:+ return g+ st = self.seats[seat]+ if self.review_due != seat:+ st.count("refused_turn")+ return 409, {"error": "no review is due from you now (reviews follow each of your actions)",+ "state": self.state(seat)}+ why, plan = body.get("why"), body.get("plan")+ if not (isinstance(why, str) and isinstance(plan, str) and why.strip() and plan.strip()):+ return 400, {"error": "ready needs two non-empty texts: WHY and PLAN"}+ if len(why) > REVIEW_MAX_CHARS or len(plan) > REVIEW_MAX_CHARS:+ return 400, {"error": f"WHY and PLAN are limited to {REVIEW_MAX_CHARS} characters each"}+ rv = {"seat": seat, "after_action": self.m.k, "why": why.strip(), "plan": plan.strip(),+ "clock_used_s": round(st.clock_used(), 1)}+ self.reviews.append(rv)+ st.count("n_reviews")+ self.ep.write("review", **rv)+ self.review_due = None+ if st.clock_left() < 0:+ self.lose(seat, "clock")+ return 200, {"accepted": "review recorded", "clock_forfeit": "your clock ran out: you lose the match",+ "state": self.state(seat)}+ if self.m.to_move() != seat:+ self.set_turn(self.m.to_move())+ return 200, {"accepted": "review recorded", "state": self.state(seat)}++ def wait(self, seat, body):+ try:+ timeout = min(WAIT_MAX_S, max(0.0, float(body.get("timeout_s", WAIT_MAX_S))))+ except (TypeError, ValueError, OverflowError):+ return 400, {"error": "timeout_s must be a number"}+ since = self.team_since(body)+ self.seats[seat].count("n_wait")+ deadline = time.time() + timeout+ while self.phase != "over" and self.on_turn != seat and time.time() < deadline:+ self.cond.wait(min(1.0, max(0.01, deadline - time.time())))+ return 200, {"state": self.state(seat, since=since)}++ # ------------------------------------------------------------------ watchdog, collect+ def loop(self):+ while True:+ time.sleep(0.5)+ with self.cond:+ if self.finalizing:+ return+ if self.phase == "prepare" and self.start_deadline and time.time() > self.start_deadline:+ self.start_deadline = None+ if self.close_start_window():+ self.begin()+ elif self.phase == "play" and self.on_turn and self.seats[self.on_turn].clock_left() < 0:+ self.lose(self.on_turn, "clock")++ def collect(self):+ def run():+ with self.cond:+ if self.phase == "play" and self.on_turn:+ s = self.on_turn+ self.lose(s, "clock" if self.seats[s].clock_left() < 0 else "abandoned")+ elif self.no_show_at_collect(): # before the start: a side not started loses (core 0.2.7)+ self.start_deadline = None+ elif not self.abandon_single(): # a single side off its turn also loses (core 0.2.6)+ self.end("incomplete" if self.phase == "prepare" else "collected")+ threading.Thread(target=run, daemon=True).start()++ def extra_final(self):+ return {"clock_s": self.clock_s, "clock_used_s": {s: round(st.clock_used(), 1) for s, st in self.seats.items()},+ "started": {s: st.joined for s, st in self.seats.items()}}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/workers.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/workers.pynew file mode 100644index 0000000000..a1636b44ba--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/core/workers.py@@ -0,0 +1,121 @@+"""Worker processes for slow per-seat work outside the world lock (rendering, planning): one process per (kind, seat),+one request in flight. The sport answers Sport.worker_init(kind, seat, cfg) and Sport.worker_call(obj, kind, job);+the kind "camera" is the core's own: the sport's camera definitions drawn by the task's renderer (core/observe.py)."""+from __future__ import annotations++import json+import os+import pickle+import select+import struct+import subprocess+import sys+import threading+import time+++def _send(f, obj):+ b = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)+ f.write(struct.pack("<Q", len(b)) + b)+ f.flush()+++def _read(f, n, deadline):+ buf = b""+ fd = f.fileno()+ while len(buf) < n:+ if deadline is not None:+ left = deadline - time.monotonic()+ if left <= 0 or not select.select([fd], [], [], left)[0]:+ raise TimeoutError("worker timed out")+ chunk = os.read(fd, n - len(buf))+ if not chunk:+ raise EOFError("worker closed")+ buf += chunk+ return buf+++def _recv(f, deadline=None):+ (n,) = struct.unpack("<Q", _read(f, 8, deadline))+ return pickle.loads(_read(f, n, deadline))+++def affinity(name: str):+ """Pin this process to the CPUs in environment variable `name` (e.g. "4-7,9"), if set."""+ v = os.environ.get(name, "")+ if v:+ cpus = set()+ for part in v.split(","):+ a = part.split("-")+ cpus.update(range(int(a[0]), int(a[-1]) + 1))+ os.sched_setaffinity(0, cpus)+++class ProcessWorker:+ def __init__(self, plugin: str, kind: str, seat: str, cfg: dict, timeout: float = 30.0):+ self.timeout, self.lock = timeout, threading.Lock()+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ self.proc = subprocess.Popen([sys.executable, "-m", "core.workers", plugin, kind, seat, json.dumps(cfg)],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=root)+ if _recv(self.proc.stdout, time.monotonic() + 120) != "ready":+ self.close()+ raise RuntimeError("worker startup failed")++ def call(self, job, wait: bool = False):+ """One job; a second one in flight is refused (BlockingIOError) unless `wait` (then it queues)."""+ if not self.lock.acquire(blocking=wait):+ raise BlockingIOError("one request per seat and worker may be in flight")+ try:+ _send(self.proc.stdin, job)+ ok, value = _recv(self.proc.stdout, time.monotonic() + self.timeout)+ if not ok:+ raise RuntimeError(value)+ return value+ except Exception:+ self.close()+ raise+ finally:+ self.lock.release()++ def close(self):+ if self.proc.poll() is None:+ self.proc.terminate()+ try:+ self.proc.wait(timeout=2)+ except subprocess.TimeoutExpired:+ self.proc.kill()+++def main(plugin, kind, seat, cfg_json):+ from .episode import load_plugin+ from .sport import MatchConfig+ affinity(f"RO_{kind.upper()}_{seat}_CPUS")+ sport = load_plugin(plugin)+ cfg = MatchConfig.from_json(json.loads(cfg_json))+ if kind == "camera":+ from .observe import CameraWorker, players_scene+ obj = CameraWorker(players_scene(sport, plugin, cfg), cfg.renderer)+ call = lambda o, k, job: o.draw_job(job) # noqa: E731 (observation or reply images)+ else:+ obj = sport.worker_init(kind, seat, cfg)+ call = sport.worker_call+ out = os.fdopen(os.dup(1), "wb")+ os.dup2(2, 1) # stray prints of the simulator go to stderr+ sys.stdout = sys.stderr+ _send(out, "ready")+ while True:+ try:+ job = _recv(sys.stdin.buffer)+ except EOFError:+ return+ t0 = time.monotonic()+ try:+ res = call(obj, kind, job)+ res["worker_s"] = time.monotonic() - t0+ _send(out, (True, res))+ except Exception as exc: # noqa: BLE001+ _send(out, (False, repr(exc)))+++if __name__ == "__main__":+ main(*sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/metering/think_proxy.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/metering/think_proxy.pynew file mode 100644index 0000000000..f9b84a44f4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/metering/think_proxy.py@@ -0,0 +1,894 @@+#!/usr/bin/env python3+"""Model-traffic proxy that runs in a task's sim sidecar and meters the agent's thinking.++In interactive mode ("thinking costs sim time") the agent's harness talks to this proxy instead of+the model API: Codex (OpenAI Responses via OpenRouter) or Claude Code (Anthropic Messages, on a Claude+subscription). The proxy+ * holds the real credentials (from its own environment: `OPENROUTER_API_KEY` for OpenRouter,+ `CLAUDE_CODE_OAUTH_TOKEN` for Anthropic); the agent container only has placeholders, so the agent+ cannot bypass the meter;+ * routes by request: Anthropic-style requests (an `anthropic-version` header, or a /v1/messages path)+ go to https://api.anthropic.com with the subscription token as Bearer; /backend-api/* (Codex logged in with a+ ChatGPT subscription, see harbor_agents/codex_chatgpt_think.py) goes to https://chatgpt.com with the sidecar's+ CODEX_ACCESS_TOKEN / CODEX_ACCOUNT_ID; everything else goes to OpenRouter (or Azure, THINK_OPENAI_ROUTE). A seat+ on THINK_OPENAI_ROUTE=chatgpt gets the ChatGPT backend only: any other request is refused (403);+ * follows no upstream redirect: a 30x goes back to the agent, never with the real credentials to another host;+ * forwards everything to OpenRouter unchanged, except the model-turn repair that Gemini needs+ (same rule as harbor_agents/or_proxy.py);+ * reads the `usage` of every completed response (streamed or not) and keeps cumulative counts:+ requests, input, cached input, output and reasoning tokens;+ * publishes the counts atomically to `THINK_USAGE_FILE` (default /data/think_usage.json) and on+ `GET /think/usage`, which the game service reads to turn "tokens since the last observation"+ into simulated time and to check that every decision follows a new model call (see think_clock.py);+ * logs every request to `THINK_CALLS_FILE` (default /data/think_calls.jsonl) for the cheating audit (rules 5.6):+ sequence number, start/end time, the client's address, User-Agent and harness session headers, the route, the+ model, the HTTP status, its usage, and an excerpt of what the model emitted (tool calls, text). Never the+ credentials or the request body;+ * with THINK_CLIENT_HOST set (multi-seat duels), serves only that compose service;+ * forwards only the model endpoints the harnesses use (ALLOWED_PATHS: Messages, Responses, the ChatGPT backend's+ Codex endpoints); any other path is refused (403) and logged as blocked. It locks the seat's model: THINK_MODEL+ (comma-separated names or fnmatch patterns, provider prefixes ignored; per seat RO_SEAT_ENV_THINK_MODEL_<seat>), or+ else the first model the seat used; a request for another model is refused (403). It strips server-side tools+ the provider would run on the agent's behalf (web search / fetch, code execution, remote MCP, file search,+ OpenRouter plugins and the `:online` model suffix): the model reaches nothing outside the game through the meter.++Usage (inside the sidecar): python3 think_proxy.py [port=18090]+Standard library only.+"""+from __future__ import annotations++import http.client+import json+import re+import uuid+import os+import sys+import threading+import time+import urllib.error+import urllib.request+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++UPSTREAM = os.environ.get("THINK_UPSTREAM", "https://openrouter.ai/api")+ANTHROPIC_UPSTREAM = os.environ.get("THINK_ANTHROPIC_UPSTREAM", "https://api.anthropic.com")+CHATGPT_UPSTREAM = os.environ.get("THINK_CHATGPT_UPSTREAM", "https://chatgpt.com") # Codex on a ChatGPT subscription+# THINK_CHATGPT_MODEL (per seat: RO_SEAT_ENV_THINK_CHATGPT_MODEL_<seat>, from players.toml `deployment` of a ChatGPT+# subscription player) pins the seat's ChatGPT-backend calls to that model: a request the model lock admitted is sent+# with this model (rec["model_alias"] keeps the name the agent sent). The harness can then use its own slug for the+# model family (Codex 0.158.0 has metadata for "gpt-6-sol", none for "gpt-6.1-sol") while the backend serves the pinned+# model ("gpt-6.1-sol"). Empty: no pin.+CHATGPT_MODEL = os.environ.get("THINK_CHATGPT_MODEL", "").strip()+++def chatgpt_pin(body: bytes, rec: dict) -> bytes:+ """The ChatGPT backend's pinned model (THINK_CHATGPT_MODEL) in place of the model the agent named."""+ try:+ d = json.loads(body)+ except ValueError:+ return body+ if not isinstance(d, dict) or not isinstance(d.get("model"), str) or d["model"] == CHATGPT_MODEL:+ return body+ rec["model_alias"] = d["model"]+ d["model"] = CHATGPT_MODEL+ return json.dumps(d).encode()+# OpenAI-style requests (Codex) go to OpenRouter unless THINK_OPENAI_ROUTE=azure: then to an Azure AI Foundry resource+# (AZURE_AI_ENDPOINT, e.g. https://<res>.services.ai.azure.com/models, key AZURE_AI_API_KEY), /v1/... -> /openai/v1/...,+# the model's provider prefix dropped ("openai/gpt-6-astra" -> deployment "gpt-6-astra").+# THINK_OPENAI_ROUTE=azure_sol is a second Azure resource with the same wire (an Azure OpenAI resource, e.g.+# https://<res>.openai.azure.com/): its own AZURE_SOL_ENDPOINT, AZURE_SOL_API_KEY and AZURE_SOL_DEPLOYMENTS. A seat's+# route is set per seat (THINK_OPENAI_ROUTE_<seat>, core/launch.py), and only that seat's proxy gets its variables.+# On azure_sol the deployments are pinned: a request for a model that is not one of AZURE_SOL_DEPLOYMENTS goes to them+# anyway (rec["model_alias"] keeps the name the agent sent). The agent can then use its harness's own name for the+# model family (Codex knows "gpt-6-sol" and has its metadata) while the resource serves its deployment ("gpt-6.1-sol").+# THINK_OPENAI_ROUTE=chatgpt: the seat plays on a ChatGPT subscription only. Its proxy forwards the ChatGPT backend+# (/backend-api/*) and refuses every other request (OpenRouter / Azure / Anthropic paths) before any credential is+# touched, so a program in that seat cannot reach another provider with a task-wide key (core/launch.py also drops those+# keys from the seat's proxy).+AZURE_ROUTES = {"azure": ("AZURE_AI_ENDPOINT", "AZURE_AI_API_KEY", "AZURE_DEPLOYMENTS"),+ "azure_sol": ("AZURE_SOL_ENDPOINT", "AZURE_SOL_API_KEY", "AZURE_SOL_DEPLOYMENTS")}+ROUTE = os.environ.get("THINK_OPENAI_ROUTE", "openrouter").strip().lower()+AZURE = ROUTE in AZURE_ROUTES+AZURE_ROUTE = ROUTE if AZURE else "azure"+AZURE_ENDPOINT_VAR, AZURE_KEY_VAR, AZURE_POOL_VAR = AZURE_ROUTES[AZURE_ROUTE]+AZURE_PINNED = AZURE_ROUTE == "azure_sol"+CHATGPT_ONLY = ROUTE == "chatgpt"+AZURE_BASE = os.environ.get(AZURE_ENDPOINT_VAR, "").strip().rstrip("/").removesuffix("/models")+USAGE_FILE = os.environ.get("THINK_USAGE_FILE", "/data/think_usage.json")+CALLS_FILE = os.environ.get("THINK_CALLS_FILE") or (USAGE_FILE.replace("think_usage", "think_calls").rsplit(".json", 1)[0] + ".jsonl"+ if "think_usage" in os.path.basename(USAGE_FILE)+ else os.path.join(os.path.dirname(USAGE_FILE) or ".", "think_calls.jsonl"))+SESSION_HEADERS = ("x-claude-code-session-id", "session_id", "conversation_id", "originator", "x-app", "openai-beta")+EXCERPT_MAX = 2000+ACT_RE = re.compile(os.environ.get("THINK_ACT_REGEX", r"\bgame\s+act\b"))+CONTINUE_TEXT = "Continue from where you left off."+MODEL_ITEM_TYPES = {"reasoning", "function_call", "custom_tool_call", "web_search_call", "local_shell_call",+ "computer_call", "mcp_call", "image_generation_call", "code_interpreter_call", "item_reference"}+HOP_BY_HOP = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-connection",+ "content-length", "host", "accept-encoding", "authorization", "x-api-key", "api-key", "chatgpt-account-id"}+# Azure deployment failover (program play tasks): AZURE_DEPLOYMENTS lists replicas of one model (e.g.+# "gpt-6-astra,gpt-6-astra-2,gpt-6-astra-3"; empty = no failover). Each deployment has its own per-minute token+# limit, and Azure may report an exceeded limit inside an HTTP 200 stream. The request is sent to the next deployment,+# before any byte reaches the agent, when a deployment+# * answers HTTP 408, 429, 500, 502, 503 or 504 (AZURE_FAILOVER_STATUS; Azure's own 408 "The operation was timeout."+# came ~21 s into a request in the 2026-10-14 soccer pilots),+# * times out or drops the connection (socket timeout, connection reset) before its response headers, or during the+# first events of a stream, which the proxy reads before it relays anything (azure_peek),+# * opens its stream with a rate-limit / overload / server-error failure, or closes it before any output.+# A failure after the first byte was relayed to the agent is never retried: the agent sees it as before. The last+# deployment tried answers the agent whatever it is (its error included). The proxy then stays on the deployment that+# worked. Switches are recorded (rec["azure_failovers"] with the reason, USAGE["azure_failovers"]); they are not model+# failures and do not count as rate_limit_retries. Empty AZURE_DEPLOYMENTS, and every non-Azure upstream: no failover.+AZURE_POOL = [d.strip() for d in os.environ.get(AZURE_POOL_VAR, "").split(",") if d.strip()]+AZURE_CURRENT = [0]+class _NoRedirect(urllib.request.HTTPRedirectHandler):+ """Follow no redirect: a 30x goes back to the client as it is, so the credentials this proxy adds (Authorization,+ api-key, chatgpt-account-id) never travel to a host the redirect names."""+ def redirect_request(self, *a, **kw):+ return None+++OPENER = urllib.request.build_opener(_NoRedirect) # replaces the default (following) redirect handler+AZURE_RATE_WORDS = ("rate limit", "rate_limit", "too_many_requests", "server_is_overloaded", '"429"')+# A failed stream's error object (not the whole response, which echoes the instructions) naming a server-side fault.+AZURE_SERVER_WORDS = ("server_error", "internal_error", "service_unavailable", "overloaded", "timeout", "timed out",+ '"408"', '"500"', '"502"', '"503"', '"504"')+AZURE_FAILOVER_STATUS = (408, 429, 500, 502, 503, 504)+UPSTREAM_TIMEOUT_S = float(os.environ.get("THINK_UPSTREAM_TIMEOUT_S", "") or 600) # socket timeout per upstream read+++def upstream_fault(exc) -> str | None:+ """A short reason when `exc` is a timeout or a dropped connection of the upstream (worth another deployment)."""+ if isinstance(exc, urllib.error.HTTPError):+ return None+ if isinstance(exc, urllib.error.URLError) and isinstance(exc.reason, BaseException):+ exc = exc.reason+ if isinstance(exc, (TimeoutError, ConnectionError, http.client.IncompleteRead)):+ return type(exc).__name__+ return None+++def azure_peek(resp, limit=1 << 20):+ '''Read whole SSE events until one that is not response.created / response.in_progress. Returns the bytes read+ and, if that event is a rate-limit / overload failure, a short reason (else None).'''+ buf, seen = b"", 0+ read = getattr(resp, "read1", resp.read)+ while len(buf) < limit:+ chunk = read(65536)+ if not chunk: # closed before any output: a stream always ends with an event+ head = buf.lstrip()+ return buf, ("stream closed before output" if not head or head.startswith((b"event:", b"data:")) else None)+ buf += chunk+ events = buf.replace(b"\r\n", b"\n").split(b"\n\n")[:-1]+ for ev in events[seen:]:+ seen += 1+ payload = b"\n".join(l[5:].strip() for l in ev.split(b"\n") if l.startswith(b"data:"))+ try:+ d = json.loads(payload) if payload and payload != b"[DONE]" else {}+ except ValueError:+ d = {}+ t = d.get("type", "") if isinstance(d, dict) else ""+ if t in ("response.created", "response.in_progress", ""):+ continue+ text = json.dumps(d).lower()+ if t in ("error", "response.failed"):+ err = (d.get("response") or {}).get("error") or d.get("error") or (d if t == "error" else {})+ if any(k in text for k in AZURE_RATE_WORDS):+ return buf, f"{t} ({(err.get('code') if isinstance(err, dict) else '') or 'rate limit'})"+ if any(k in json.dumps(err).lower() for k in AZURE_SERVER_WORDS):+ return buf, f"{t} ({(err.get('code') if isinstance(err, dict) else '') or 'server error'})"+ return buf, None+ return buf, None+++class PrefixedResponse:+ '''A response whose first bytes were already read by azure_peek.'''+ def __init__(self, resp, head):+ self.resp, self.head = resp, head+ self.status, self.headers = resp.status, resp.headers++ def read1(self, n=-1):+ if self.head:+ out, self.head = self.head, b""+ return out+ return getattr(self.resp, "read1", self.resp.read)(n)++ read = read1++ def close(self):+ self.resp.close()+++RATE_LIMIT_WAITS_S = tuple(float(x) for x in os.environ.get("THINK_RETRY_WAITS_S", "").split(",") if x.strip())++LOCK = threading.Lock()+USAGE = {"requests": 0, "responses_with_usage": 0, "input_tokens": 0, "cached_input_tokens": 0,+ "output_tokens": 0, "reasoning_tokens": 0, "updated_at": 0.0,+ "model_calls_completed": 0, "in_flight": 0, "last_completed_at": 0.0,+ "epoch": uuid.uuid4().hex, "failed_model_calls": 0,+ "rate_limit_retries": 0, "last_response_seq": None, "blocked_requests": 0,+ "act_calls_completed": 0, "last_act_call_at": 0.0, "last_act_response_seq": None, "last_act_started_at": 0.0}+++def publish() -> None:+ tmp = USAGE_FILE + ".tmp"+ os.makedirs(os.path.dirname(USAGE_FILE) or ".", exist_ok=True)+ with open(tmp, "w") as f:+ json.dump(USAGE, f)+ os.replace(tmp, USAGE_FILE)+++def azure_model(body: bytes) -> bytes:+ """Azure deployments are named without the provider prefix the agent uses for OpenRouter."""+ try:+ d = json.loads(body)+ except ValueError:+ return body+ if isinstance(d, dict) and isinstance(d.get("model"), str) and "/" in d["model"]:+ d["model"] = d["model"].rsplit("/", 1)[1]+ return json.dumps(d).encode()+ return body+++def is_model_call(method: str, path: str) -> bool:+ """A model turn: Anthropic Messages (not count_tokens), OpenAI Responses / Chat Completions (OpenRouter or the+ ChatGPT backend). Model listings, token counting and telemetry are not."""+ if method != "POST":+ return False+ p = path.split("?")[0]+ if "count_tokens" in p:+ return False+ return p.endswith(("/v1/messages", "/responses", "/chat/completions"))+++# Anti-cheat (audit 2026-10-08, G4): the proxy is no open forwarder with the real credentials.+ALLOWED_PATHS = {("POST", "/v1/messages"), ("POST", "/v1/messages/count_tokens"), ("POST", "/v1/responses"),+ ("POST", "/v1/chat/completions"), ("POST", "/openai/v1/responses"),+ ("POST", "/backend-api/codex/responses"), ("GET", "/backend-api/codex/models"), ("GET", "/v1/models"),+ ("POST", "/v1/responses/compact"), ("POST", "/backend-api/codex/responses/compact")} # Codex compaction+SERVER_TOOL_PREFIXES = ("web_search", "web_fetch", "code_execution", "bash_code_execution",+ "text_editor_code_execution", "code_interpreter", "file_search", "mcp") # tool "type"s+STRIP_KEYS = ("mcp_servers", "plugins", "web_search_options", "container", "tool_resources")+MODEL_LOCK = [m.strip() for m in os.environ.get("THINK_MODEL", "").split(",") if m.strip()]+FIRST_MODEL: list = [] # without THINK_MODEL: the first model this seat used+++def path_allowed(method: str, path: str) -> bool:+ return (method, path.split("?")[0].rstrip("/") or "/") in ALLOWED_PATHS+++def bare_model(name) -> str:+ """'openrouter/openai/gpt-x:online' -> 'gpt-x' (provider prefixes and OpenRouter variants dropped)."""+ return str(name or "").rsplit("/", 1)[-1].split(":", 1)[0].strip().lower()+++def model_allowed(name) -> bool:+ import fnmatch+ m = bare_model(name)+ if not m:+ return True # no model named (listings): nothing to lock+ if MODEL_LOCK:+ return any(fnmatch.fnmatchcase(m, bare_model(p)) for p in MODEL_LOCK)+ with LOCK:+ if not FIRST_MODEL:+ FIRST_MODEL.append(m)+ return m == FIRST_MODEL[0]+++def strip_server_tools(payload: dict) -> list:+ """Remove the provider-run tools and options from a request (in place); returns what was removed."""+ gone = []+ tools = payload.get("tools")+ if isinstance(tools, list):+ keep = []+ for t in tools:+ kind = str(t.get("type", "")) if isinstance(t, dict) else ""+ if kind.lower().startswith(SERVER_TOOL_PREFIXES): # client tools (function, custom) stay+ gone.append(kind)+ else:+ keep.append(t)+ if len(keep) != len(tools):+ payload["tools"] = keep+ if not keep:+ payload.pop("tools", None)+ payload.pop("tool_choice", None)+ for k in STRIP_KEYS:+ if k in payload:+ gone.append(k)+ payload.pop(k)+ model = payload.get("model")+ if isinstance(model, str) and ":online" in model:+ payload["model"] = model.replace(":online", "")+ gone.append(":online")+ if isinstance(payload.get("models"), list): # OpenRouter fallback models: another model+ gone.append("models")+ payload.pop("models")+ return gone+++def screen(method: str, path: str, body: bytes | None, rec: dict) -> tuple[int, str, bytes | None]:+ """Before anything is forwarded: (0, "", body to send) or (http status, reason, None) for a refusal."""+ if not path_allowed(method, path):+ return 403, "path not allowed (only the model endpoints of the harnesses)", None+ if not body:+ return 0, "", body+ try:+ payload = json.loads(body)+ except ValueError:+ return 400, "request body is not JSON", None+ if not isinstance(payload, dict):+ return 400, "request body is not a JSON object", None+ if not model_allowed(payload.get("model")):+ return 403, "model not allowed for this seat", None+ gone = strip_server_tools(payload)+ if gone:+ rec["stripped"] = gone+ return 0, "", json.dumps(payload).encode()+ return 0, "", body+++def log_call(rec: dict) -> None:+ line = json.dumps(rec, default=str)+ with LOCK:+ with open(CALLS_FILE, "a") as f:+ f.write(line + "\n")+++def _allowed_client(addr: str) -> bool:+ """Multi-seat duels: THINK_CLIENT_HOST names the only compose service allowed to use this proxy, so one seat+ cannot think on (or hide its thinking behind) the other seat's meter. Unset: anyone (single-player tasks)."""+ host = os.environ.get("THINK_CLIENT_HOST")+ if not host:+ return True+ try:+ import socket+ return addr in {ai[4][0] for ai in socket.getaddrinfo(host, None)}+ except OSError:+ return False+++class Excerpt:+ """What the model emitted in one response, from its stream or JSON body: tool calls and text, truncated."""+ def __init__(self):+ self.parts: list[str] = []+ self.n = 0++ def add(self, s) -> None:+ if not s or self.n >= EXCERPT_MAX:+ return+ s = str(s)[: EXCERPT_MAX - self.n]+ self.parts.append(s); self.n += len(s)++ def feed_event(self, ev: dict) -> None:+ t = ev.get("type", "")+ if t == "content_block_start": # Anthropic+ cb = ev.get("content_block") or {}+ if cb.get("type") in ("tool_use", "server_tool_use"):+ self.add(f"[tool {cb.get('name')}] ")+ elif t == "content_block_delta":+ d = ev.get("delta") or {}+ self.add(d.get("partial_json") or d.get("text"))+ elif t == "response.output_item.done": # OpenAI Responses+ it = ev.get("item") or {}+ if it.get("type") in ("function_call", "custom_tool_call"):+ self.add(f"[tool {it.get('name')}] {it.get('arguments') or it.get('input') or ''} ")+ elif it.get("type") == "local_shell_call":+ self.add(f"[shell] {json.dumps(it.get('action'))} ")+ elif t == "response.output_text.delta":+ self.add(ev.get("delta"))++ def feed_body(self, obj: dict) -> None:+ for cb in obj.get("content") or []: # Anthropic, non-streamed+ if cb.get("type") == "tool_use":+ self.add(f"[tool {cb.get('name')}] {json.dumps(cb.get('input'))} ")+ elif cb.get("type") == "text":+ self.add(cb.get("text"))+ for it in obj.get("output") or []: # Responses, non-streamed+ self.feed_event({"type": "response.output_item.done", "item": it})++ def text(self) -> str:+ return "".join(self.parts)+++def account(usage: dict) -> None:+ """Add one response's usage (Responses API or Chat Completions shape)."""+ if not isinstance(usage, dict):+ return 0+ inp = int(usage.get("input_tokens", usage.get("prompt_tokens", 0)) or 0)+ out = int(usage.get("output_tokens", usage.get("completion_tokens", 0)) or 0)+ det_in = usage.get("input_tokens_details") or usage.get("prompt_tokens_details") or {}+ det_out = usage.get("output_tokens_details") or usage.get("completion_tokens_details") or {}+ cached = int(det_in.get("cached_tokens", 0) or 0)+ if "cache_read_input_tokens" in usage or "cache_creation_input_tokens" in usage: # Anthropic shape+ cached = int(usage.get("cache_read_input_tokens", 0) or 0)+ inp += cached + int(usage.get("cache_creation_input_tokens", 0) or 0)+ with LOCK:+ USAGE["responses_with_usage"] += 1+ USAGE["input_tokens"] += inp+ USAGE["cached_input_tokens"] += cached+ USAGE["output_tokens"] += out+ USAGE["reasoning_tokens"] += int(det_out.get("reasoning_tokens", 0) or 0)+ USAGE["updated_at"] = time.time()+ publish()+ return out+++class AnthropicStream:+ """Collects one Messages stream's usage: input from message_start, final output from message_delta."""+ def __init__(self):+ self.usage: dict = {}++ def feed(self, line: bytes, excerpt: "Excerpt | None" = None) -> None:+ if not line.startswith(b"data:"):+ return+ try:+ ev = json.loads(line[5:].strip() or b"{}")+ except ValueError:+ return+ if excerpt is not None:+ excerpt.feed_event(ev)+ if ev.get("type") == "message_start":+ self.usage.update((ev.get("message") or {}).get("usage") or {})+ elif ev.get("type") == "message_delta" and ev.get("usage"):+ self.usage.update(ev["usage"])+++def is_anthropic(path: str, headers) -> bool:+ """Codex (OpenRouter) only uses /v1/responses (and /v1/models); Claude Code uses /v1/messages*, /api/*+ and always sends anthropic-version."""+ if path.startswith("/v1/responses") or path.startswith("/v1/chat"):+ return False+ return bool(headers.get("anthropic-version")) or path.startswith(("/v1/messages", "/v1/complete", "/api/"))+++def usage_from_sse_line(line: bytes) -> dict | None:+ if not line.startswith(b"data:"):+ return None+ data = line[5:].strip()+ if not data or data == b"[DONE]":+ return None+ try:+ ev = json.loads(data)+ except ValueError:+ return None+ if ev.get("type") in ("response.completed", "response.done", "response.incomplete"):+ return (ev.get("response") or {}).get("usage")+ if "usage" in ev and ev.get("object", "").startswith("chat.completion"):+ return ev.get("usage")+ return None+++def repair(body: bytes, path: str) -> bytes:+ if "/responses" not in path:+ return body+ try:+ payload = json.loads(body)+ except ValueError:+ return body+ items = payload.get("input")+ if isinstance(items, list) and items and isinstance(items[-1], dict) and (+ items[-1].get("role") == "assistant" or items[-1].get("type") in MODEL_ITEM_TYPES):+ items.append({"type": "message", "role": "user", "content": [{"type": "input_text", "text": CONTINUE_TEXT}]})+ return json.dumps(payload).encode()+ return body+++class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, fmt, *args):+ sys.stderr.write("think_proxy: %s\n" % (fmt % args))++ def _json(self, code: int, obj: dict) -> None:+ b = json.dumps(obj).encode()+ self.send_response(code); self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)++ def do_GET(self):+ if not _allowed_client(self.client_address[0]):+ self.send_error(403, "not your seat's proxy"); return+ if self.path.rstrip("/") == "/think/usage":+ with LOCK:+ return self._json(200, dict(USAGE))+ return self._forward(None)++ def do_POST(self):+ if not _allowed_client(self.client_address[0]):+ self.send_error(403, "not your seat's proxy"); return+ n = int(self.headers.get("Content-Length") or 0)+ return self._forward(self.rfile.read(n) if n else b"")++ def _forward(self, body: bytes | None) -> None:+ pre = {}+ code, why, body = screen(self.command, self.path, body, pre)+ if not code and CHATGPT_ONLY and not self.path.startswith("/backend-api/"):+ code, why = 403, "route chatgpt: only the ChatGPT backend (/backend-api/*) is forwarded for this seat"+ if code: # refused before any credential is touched+ rec = {"t0": round(time.time(), 3), "client": self.client_address[0], "method": self.command,+ "path": self.path.split("?")[0][:200], "user_agent": self.headers.get("User-Agent", ""),+ "model_call": False, "status": code, "blocked": why, "t1": round(time.time(), 3)}+ with LOCK:+ USAGE["blocked_requests"] = USAGE.get("blocked_requests", 0) + 1+ rec["epoch"] = USAGE["epoch"]+ publish()+ log_call(rec)+ return self._json(code, {"error": {"type": "think_proxy_refused", "message": f"think_proxy: {why}"}})+ chatgpt = self.path.startswith("/backend-api/") # Codex logged in with a ChatGPT subscription+ anthropic = not chatgpt and is_anthropic(self.path, self.headers)+ azure = AZURE and not chatgpt and not anthropic+ name = "CODEX_ACCESS_TOKEN" if chatgpt else ("CLAUDE_CODE_OAUTH_TOKEN" if anthropic else+ (AZURE_KEY_VAR if azure else "OPENROUTER_API_KEY"))+ key = os.environ.get(name, "")+ if body and azure:+ body = azure_model(body)+ elif body and chatgpt and CHATGPT_MODEL: # after the model lock admitted the agent's name+ body = chatgpt_pin(body, pre)+ elif body and not anthropic and not chatgpt:+ body = repair(body, self.path)+ model_call = is_model_call(self.command, self.path)+ rec = {"t0": round(time.time(), 3), "client": self.client_address[0], "method": self.command,+ "path": self.path.split("?")[0], "route": "chatgpt" if chatgpt else ("anthropic" if anthropic else (AZURE_ROUTE if azure else "openrouter")),+ "user_agent": self.headers.get("User-Agent", ""), "model_call": model_call,+ "session": {h: self.headers.get(h) for h in SESSION_HEADERS if self.headers.get(h)}, **pre}+ try:+ rec["model"] = (json.loads(body) or {}).get("model") if body else None+ except (ValueError, AttributeError):+ rec["model"] = None+ with LOCK:+ USAGE["requests"] += 1+ rec["seq"] = USAGE["requests"]+ rec["epoch"] = USAGE["epoch"]+ if model_call:+ USAGE["in_flight"] += 1+ publish() # publish in-flight and request count before the carrying response can trigger a tool+ try:+ if not key or (azure and not AZURE_BASE):+ rec["status"] = 500+ rec["error"] = "missing_upstream_credentials"+ return self._json(500, {"error": {"message": f"think_proxy: {name} (and {AZURE_ENDPOINT_VAR}) not set in the sidecar"}})+ self._forward_upstream(body, chatgpt, anthropic, key, rec, azure)+ except Exception as exc:+ rec["error"] = type(exc).__name__+ rec["completed"] = False+ self.close_connection = True+ finally:+ with LOCK:+ if model_call:+ USAGE["in_flight"] -= 1+ if rec.get("status") == 200 and rec.get("completed"):+ USAGE["model_calls_completed"] += 1+ USAGE["last_completed_at"] = time.time()+ USAGE["last_response_seq"] = rec["seq"]+ if rec.get("has_act"):+ USAGE["act_calls_completed"] += 1+ USAGE["last_act_call_at"] = time.time()+ USAGE["last_act_response_seq"] = rec["seq"]+ USAGE["last_act_started_at"] = rec["t0"]+ else:+ USAGE["failed_model_calls"] += 1+ publish()+ rec["t1"] = round(time.time(), 6)+ rec["epoch"] = USAGE["epoch"]+ log_call(rec)++ def _forward_upstream(self, body, chatgpt: bool, anthropic: bool, key: str, rec: dict, azure: bool = False) -> None:+ headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_BY_HOP}+ if azure: # Azure AI Foundry: api-key header, no bearer+ headers["api-key"] = key+ else:+ headers["Authorization"] = f"Bearer {key}" # the agent's placeholder credential is dropped above+ headers["Accept-Encoding"] = "identity"+ if anthropic: # subscription (OAuth) auth needs its beta flag+ betas = [b.strip() for b in headers.pop("anthropic-beta", headers.pop("Anthropic-Beta", "")).split(",") if b.strip()]+ if "oauth-2025-04-20" not in betas:+ betas.append("oauth-2025-04-20")+ headers["anthropic-beta"] = ",".join(betas)+ if chatgpt: # the subscription's account, not the agent's placeholder+ headers["chatgpt-account-id"] = os.environ.get("CODEX_ACCOUNT_ID", "")+ base = CHATGPT_UPSTREAM if chatgpt else (ANTHROPIC_UPSTREAM if anthropic else UPSTREAM)+ url = base.rstrip("/") + self.path # /v1/responses -> OpenRouter, /v1/messages -> Anthropic+ if azure: # /v1/responses -> <resource>/openai/v1/responses+ url = AZURE_BASE + "/openai" + (self.path if self.path.startswith("/v1") else "/v1" + self.path)+ req = urllib.request.Request(url, data=body, method=self.command, headers=headers)+ resp = None+ if azure and AZURE_POOL and self.command == "POST" and body:+ try:+ resp = self._azure_failover(url, body, headers, rec)+ except Exception as exc: # noqa: BLE001+ rec["status"] = 502; rec["error"] = repr(exc)[:200]+ return self._json(502, {"error": {"message": f"think_proxy upstream failure: {exc!r}"}})+ try:+ for attempt in (range(len(RATE_LIMIT_WAITS_S) + 1) if resp is None else ()):+ try:+ resp = OPENER.open(req, timeout=UPSTREAM_TIMEOUT_S); break+ except urllib.error.HTTPError as err:+ resp = err+ if err.code != 429 or attempt >= len(RATE_LIMIT_WAITS_S):+ break+ with LOCK:+ USAGE["rate_limit_retries"] += 1+ publish()+ rec.setdefault("retries", []).append({"status": 429, "at": time.time(),+ "wait_s": RATE_LIMIT_WAITS_S[attempt]})+ err.close()+ time.sleep(RATE_LIMIT_WAITS_S[attempt])+ except Exception as exc: # noqa: BLE001+ rec["status"] = 502; rec["error"] = repr(exc)[:200]+ return self._json(502, {"error": {"message": f"think_proxy upstream failure: {exc!r}"}})+ rec["status"] = resp.status+ if chatgpt: # subscription usage (x-codex-primary-used-percent, ...)+ limits = {k.lower(): v for k, v in resp.headers.items() if k.lower().startswith("x-codex-")}+ if limits:+ rec["codex_limits"] = limits+ with LOCK:+ USAGE["codex_limits"] = limits+ publish()+ self.send_response(resp.status)+ ctype = resp.headers.get("Content-Type", "")+ for k, v in resp.headers.items():+ if k.lower() not in HOP_BY_HOP:+ self.send_header(k, v)+ self.send_header("Connection", "close"); self.end_headers()+ audit = ResponseAudit(self.path, anthropic)+ streamed = "event-stream" in ctype+ whole = bytearray()+ read = getattr(resp, "read1", resp.read)+ rec["completed"] = False+ try:+ while True:+ chunk = read(4096) # never wait for a full 4 KB while SSE bytes are already available+ if not chunk:+ break+ rec.setdefault("upstream_first_byte_at", time.time())+ self.wfile.write(chunk); self.wfile.flush()+ rec.setdefault("downstream_first_byte_at", time.time())+ if streamed:+ audit.feed(chunk)+ else:+ whole.extend(chunk)+ if whole.lstrip().startswith((b"event:", b"data:")):+ streamed = True+ audit.feed(bytes(whole))+ whole.clear()+ if audit.terminal:+ rec["upstream_terminal_at"] = time.time()+ break+ if streamed:+ audit.finish()+ else:+ try:+ audit.body(json.loads(whole))+ except (ValueError, TypeError):+ audit.failed = True+ rec["completed"] = bool(resp.status == 200 and audit.success and not audit.failed)+ finally:+ resp.close()+ rec["output_tokens"] = account(audit.usage) if audit.usage else 0+ rec["excerpt"] = audit.excerpt.text()+ rec["response_id"] = audit.response_id+ rec["tool_calls"] = audit.tools+ rec["has_act"] = bool(rec.get("completed") and audit.has_act())+ rec["stream_error"] = audit.failed or not audit.success+ self.close_connection = True+++ def _azure_failover(self, url, body, headers, rec):+ '''Send to the current deployment; on a transient failure before any byte was relayed (HTTP 408/429/5xx, a+ timeout or dropped connection, an in-stream rate-limit / server failure or an empty stream), try the next one.+ The last deployment's answer, or its exception, goes to the agent as it is.'''+ try:+ data = json.loads(body)+ except ValueError:+ data = None+ if not isinstance(data, dict):+ return None+ if data.get("model") not in AZURE_POOL:+ if not AZURE_PINNED:+ return None # not a pooled model: the ordinary path+ rec["model_alias"] = data.get("model") # pinned route: served by the pool's deployment+ n = len(AZURE_POOL)+ start = AZURE_CURRENT[0]+ resp = None+ for i in range(n):+ idx = (start + i) % n+ data["model"] = AZURE_POOL[idx]+ payload = json.dumps(data).encode()+ h = dict(headers); h["Content-Length"] = str(len(payload))+ req = urllib.request.Request(url, data=payload, method="POST", headers=h)+ last = i == n - 1+ try:+ resp = OPENER.open(req, timeout=UPSTREAM_TIMEOUT_S)+ except urllib.error.HTTPError as err:+ resp = err+ if err.code in AZURE_FAILOVER_STATUS and not last:+ err.close()+ self._azure_switch(rec, idx, f"HTTP {err.code}")+ continue+ break+ except Exception as exc: # noqa: BLE001+ fault = upstream_fault(exc)+ if fault is None or last:+ raise+ self._azure_switch(rec, idx, fault)+ continue+ if data.get("stream") and not last:+ try:+ head, failed = azure_peek(resp) # nothing has been relayed to the agent yet+ except Exception as exc: # noqa: BLE001+ failed = upstream_fault(exc)+ if failed is None:+ resp.close()+ raise+ if failed:+ resp.close()+ self._azure_switch(rec, idx, failed)+ continue+ resp = PrefixedResponse(resp, head)+ break+ AZURE_CURRENT[0] = AZURE_POOL.index(data["model"])+ rec["azure_deployment"] = data["model"]+ return resp++ def _azure_switch(self, rec, idx, reason):+ rec.setdefault("azure_failovers", []).append({"from": AZURE_POOL[idx], "reason": reason, "at": time.time()})+ with LOCK:+ USAGE["azure_failovers"] = USAGE.get("azure_failovers", 0) + 1+ publish()+++class ResponseAudit:+ """Parse SSE boundaries independently of network chunks; count only a successful terminal event."""+ def __init__(self, path, anthropic=False):+ self.path, self.anthropic = path, anthropic+ self.buf = b""+ self.data = []+ self.success = self.failed = self.terminal = False+ self.usage = {}+ self.response_id = None+ self.excerpt = Excerpt()+ self.tools = []+ self.chat_choices = {}+ self.chat_tools = {}+ self.anthropic_tools = {}+ self.anthropic_stop = None++ def has_act(self):+ # Intent is read only from emitted tool arguments, never ordinary assistant text.+ # This is an operational gate, not authentication of which harness made the request.+ return self.success and not self.failed and any(+ ACT_RE.search(json.dumps(tool.get("arguments") or tool.get("input") or tool.get("action")+ or (tool.get("function") or {}).get("arguments") or "",+ ensure_ascii=False)) for tool in self.tools)++ def body(self, obj):+ if not isinstance(obj, dict):+ self.failed = True+ return+ self.response_id = obj.get("id", self.response_id)+ self.usage.update(obj.get("usage") or {})+ self.excerpt.feed_body(obj)+ if "output" in obj:+ self.tools = [it for it in obj["output"] if it.get("type") in ("function_call", "custom_tool_call", "local_shell_call")]+ self.tools += [it for it in obj.get("content", []) if it.get("type") == "tool_use"]+ self.tools += [it for ch in obj.get("choices", []) for it in (ch.get("message") or {}).get("tool_calls", [])]+ self.tools += [{"function": ch["message"]["function_call"]} for ch in obj.get("choices", [])+ if (ch.get("message") or {}).get("function_call")]+ if self.anthropic:+ self.success = obj.get("stop_reason") in ("end_turn", "tool_use", "stop_sequence") and obj.get("type") == "message"+ elif "/chat/completions" in self.path:+ self.success = bool(obj.get("choices")) and all(c.get("finish_reason") in ("stop", "tool_calls", "function_call") for c in obj["choices"])+ else:+ self.success = obj.get("status") == "completed"+ self.failed |= bool(obj.get("error"))+ self.terminal = True++ def event(self, data):+ if data == b"[DONE]":+ self.terminal = True+ self.success |= ("/chat/completions" in self.path and bool(self.chat_choices)+ and all(self.chat_choices.values()))+ self.tools += list(self.chat_tools.values())+ return+ try:+ ev = json.loads(data)+ except ValueError:+ self.failed = True+ return+ if not isinstance(ev, dict):+ self.failed = True+ return+ t = ev.get("type", "")+ self.excerpt.feed_event(ev)+ if t == "message_start":+ message = ev.get("message") or {}+ self.response_id = message.get("id")+ self.usage.update(message.get("usage") or {})+ elif t == "message_delta":+ self.usage.update(ev.get("usage") or {})+ self.anthropic_stop = (ev.get("delta") or {}).get("stop_reason", self.anthropic_stop)+ elif t == "content_block_start":+ cb = ev.get("content_block") or {}+ if cb.get("type") == "tool_use":+ self.anthropic_tools[ev.get("index", 0)] = dict(cb)+ elif t == "content_block_delta":+ tool = self.anthropic_tools.get(ev.get("index", 0))+ delta = ev.get("delta") or {}+ if tool is not None and delta.get("type") == "input_json_delta":+ tool["_json"] = tool.get("_json", "") + delta.get("partial_json", "")+ elif t == "message_stop":+ self.terminal = True+ self.success = self.anthropic_stop in ("end_turn", "tool_use", "stop_sequence")+ for tool in self.anthropic_tools.values():+ if "_json" in tool:+ try:+ tool["input"] = json.loads(tool.pop("_json"))+ except ValueError:+ self.failed = True+ self.tools.append(tool)+ elif t in ("response.completed", "response.done"):+ response = ev.get("response") or {}+ self.body(response)+ elif t in ("error", "response.failed", "response.incomplete") or ev.get("error"):+ self.failed = self.terminal = True+ self.usage.update((ev.get("response") or {}).get("usage") or {})+ elif t == "response.output_item.done":+ it = ev.get("item") or {}+ if it.get("type") in ("function_call", "custom_tool_call", "local_shell_call"):+ self.tools.append(it)+ if ev.get("object", "").startswith("chat.completion"):+ self.response_id = ev.get("id", self.response_id)+ self.usage.update(ev.get("usage") or {})+ for choice in ev.get("choices", []):+ ci = choice.get("index", 0)+ self.chat_choices.setdefault(ci, False)+ reason = choice.get("finish_reason")+ if reason is not None:+ self.chat_choices[ci] = reason in ("stop", "tool_calls", "function_call")+ self.failed |= not self.chat_choices[ci]+ delta = choice.get("delta") or {}+ self.excerpt.add(delta.get("content"))+ calls = delta.get("tool_calls") or []+ if delta.get("function_call"):+ calls = calls + [{"index": 0, "function": delta["function_call"]}]+ for fragment in calls:+ tool = self.chat_tools.setdefault((ci, fragment.get("index", 0)),+ {"type": "function", "function": {"name": "", "arguments": ""}})+ if fragment.get("id"):+ tool["id"] = fragment["id"]+ for field in ("name", "arguments"):+ tool["function"][field] += (fragment.get("function") or {}).get(field, "")+ self.excerpt.add(json.dumps(fragment))++ def feed(self, chunk):+ self.buf += chunk+ while b"\n" in self.buf:+ line, self.buf = self.buf.split(b"\n", 1)+ self.line(line.rstrip(b"\r"))++ def line(self, line):+ if not line:+ if self.data:+ self.event(b"\n".join(self.data))+ self.data = []+ elif line.startswith(b"data:"):+ self.data.append(line[5:].lstrip(b" "))++ def finish(self):+ if self.buf:+ self.line(self.buf.rstrip(b"\r"))+ self.buf = b""+ self.line(b"")++++def main() -> int:+ port = int(sys.argv[1]) if len(sys.argv) > 1 else 18090+ publish()+ srv = ThreadingHTTPServer(("0.0.0.0", port), Handler)+ srv.daemon_threads = True+ sys.stderr.write(f"think_proxy: listening on :{port} -> {UPSTREAM}; usage -> {USAGE_FILE}\n")+ srv.serve_forever()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/__init__.pynew file mode 100644index 0000000000..9a55e841d4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/__init__.py@@ -0,0 +1,40 @@+"""Renderer plugins (docs/framework_zh.md §3.1): a renderer draws a sport's scene, from its camera definitions, for+one world state. Sports never import a renderer; the core calls the task's observation renderer (task parameter+`renderer`, default DEFAULT) and the viewing tools any renderer for re-renders.++ from renderers import load, Scene, CameraDef+ R = load("mujoco")(Scene.from_file("scene.xml"))+ images = R.render({"qpos": qpos}, [CameraDef("behind", pos, lookat)])+"""+from __future__ import annotations++import importlib++from .base import CameraDef, Renderer, RendererUnavailable, Scene # noqa: F401++DEFAULT = "mujoco"+REGISTRY = { # name -> (module, realtime, needs_gpu, requires)+ "mujoco": ("renderers.mujoco", True, False, "mujoco; MUJOCO_GL=osmesa (CPU) or egl (GPU)"),+ "mujoco-showcase": ("renderers.mujoco_showcase", True, False, "as mujoco"),+ "cycles": ("renderers.cycles", False, True, "Docker, the rcb-showcase-blender image, an NVIDIA GPU (or device=CPU)"),+ "isaac": ("renderers.isaac", False, True, "Docker, the Isaac Sim 4.5 image, an NVIDIA RTX GPU"),+}+++def load(name: str = DEFAULT):+ """The Renderer subclass registered under `name`."""+ if name not in REGISTRY:+ raise KeyError(f"unknown renderer {name!r}; have {sorted(REGISTRY)}")+ return importlib.import_module(REGISTRY[name][0]).RENDERER+++def available() -> dict:+ return {n: {"realtime": rt, "needs_gpu": gpu, "requires": req} for n, (_, rt, gpu, req) in REGISTRY.items()}+++def players_model(sport_dir, match: Scene):+ """For a sport that draws its own images (the renderers' interface for sports): the compiled MjModel of the+ players' presentation scene its presentation.toml declares (`players`, renderer rule 6; the same kinematics as+ `match` checked), or None when it declares none (draw the match model). See renderers/presentation."""+ from .presentation import players_model as _players_model+ return _players_model(sport_dir, match)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/base.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/base.pynew file mode 100644index 0000000000..7cf75e40ba--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/base.py@@ -0,0 +1,156 @@+"""The renderer plugin interface (docs/framework_zh.md §3.1, renderer rules §9): a renderer turns a sport's scene,+camera definitions and one world state into images. It never changes physics or the match state: it draws on its own+copy of the model.++ scene = Scene(engine="mujoco", xml=MJCF text, assets={relative path: bytes}, look=None or a presentation look)+ a presentation scene (renderers/presentation.py, spectators only) also carries `match`, the match scene+ it dresses: same kinematics, extra visual-only geoms (scene_check.same_kinematics)+ cameras = [CameraDef(name, pos, lookat, up, fovy_deg, width, height), ...] (what Match.cameras(seat) returns)+ state = {"qpos": [...], optional "mocap_pos": [...], "mocap_quat": [...]}+ images = Renderer(scene).render(state, cameras) -> one H x W x 3 uint8 array per camera++The camera model is a pinhole that every renderer must reproduce (CameraDef.project): pixel (u, v) from the image's+top-left corner, u to the right, v down, vertical field of view fovy_deg. Only numpy is needed here; engines import+their own libraries inside their backend packages. Never put the renderers/ directory itself on sys.path (its+`mujoco` backend package would shadow the mujoco library); import it as the package `renderers`.+"""+from __future__ import annotations++import math+from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np+++class RendererUnavailable(RuntimeError):+ """The renderer cannot run here; `requirements` says what it needs (GPU, image, library ...)."""++ def __init__(self, name: str, why: str, requirements: str = ""):+ super().__init__(f"renderer {name!r} unavailable: {why}" + (f" (requires: {requirements})" if requirements else ""))+ self.name, self.why, self.requirements = name, why, requirements+++def _unit(v):+ v = np.asarray(v, dtype=float)+ n = np.linalg.norm(v)+ if not np.isfinite(n) or n < 1e-12:+ raise ValueError("degenerate camera direction")+ return v / n+++@dataclass+class CameraDef:+ name: str+ pos: tuple+ lookat: tuple+ up: tuple = (0.0, 0.0, 1.0)+ fovy_deg: float = 45.0+ width: int = 320+ height: int = 240++ def __post_init__(self):+ self.pos = tuple(float(x) for x in self.pos)+ self.lookat = tuple(float(x) for x in self.lookat)+ self.up = tuple(float(x) for x in self.up)+ self.fovy_deg, self.width, self.height = float(self.fovy_deg), int(self.width), int(self.height)+ if len(self.pos) != 3 or len(self.lookat) != 3 or len(self.up) != 3:+ raise ValueError("pos, lookat and up are 3-vectors")+ if not 0 < self.fovy_deg < 180 or self.width <= 0 or self.height <= 0:+ raise ValueError("fovy_deg in (0, 180), positive width and height")+ self.basis() # raises on a degenerate pose++ @staticmethod+ def from_dict(d: dict) -> "CameraDef":+ keys = ("name", "pos", "lookat", "up", "fovy_deg", "width", "height")+ return CameraDef(**{k: d[k] for k in keys if k in d})++ def to_dict(self) -> dict:+ return {"name": self.name, "pos": list(self.pos), "lookat": list(self.lookat), "up": list(self.up),+ "fovy_deg": self.fovy_deg, "width": self.width, "height": self.height}++ def focal_px(self) -> float:+ return (self.height / 2) / math.tan(math.radians(self.fovy_deg) / 2)++ def intrinsics(self) -> dict:+ return {"focal_px": self.focal_px(), "principal_point_px": [self.width / 2, self.height / 2],+ "width": self.width, "height": self.height}++ def basis(self):+ """(right, up, forward) unit vectors in the world frame."""+ fwd = _unit(np.subtract(self.lookat, self.pos))+ right = _unit(np.cross(fwd, self.up))+ up = np.cross(right, fwd)+ return right, up, fwd++ def project(self, point):+ """Pixel (u, v) of a world point (u right, v down, from the top-left corner; continuous coordinates, so the+ centre of pixel column i is u = i + 0.5). None if the point is behind the camera."""+ right, up, fwd = self.basis()+ d = np.subtract(point, self.pos)+ depth = float(d @ fwd)+ if depth <= 1e-9:+ return None+ f = self.focal_px()+ return (self.width / 2 + f * float(d @ right) / depth, self.height / 2 - f * float(d @ up) / depth)++ def spherical(self):+ """(lookat, distance, azimuth_deg, elevation_deg): the free-camera form the showcase exporters use."""+ d = np.subtract(self.lookat, self.pos)+ dist = float(np.linalg.norm(d))+ az = math.degrees(math.atan2(d[1], d[0]))+ el = math.degrees(math.asin(max(-1.0, min(1.0, d[2] / dist))))+ return list(self.lookat), dist, az, el+++@dataclass+class Scene:+ engine: str = "mujoco" # the physics engine whose scene format `xml` is in+ xml: str = "" # MJCF text (engine "mujoco")+ assets: dict = field(default_factory=dict) # {path as referenced by the xml (with meshdir/texturedir): bytes}+ look: dict | None = None # optional presentation appearance (showcase renderers only)+ match: "Scene | None" = None # set on a presentation scene only: the match scene it dresses+ credits: tuple = () # presentation scene: what was added, with its source and licence+ players: bool = False # a presentation scene the sport declares for its players' images too++ @property+ def is_presentation(self) -> bool:+ """A presentation scene (renderers/presentation): drawn for the players' images only when `players` is set+ (the sport declares it, renderer rule 6), else for spectators only."""+ return self.match is not None++ @staticmethod+ def from_file(path, look=None) -> "Scene":+ """A scene file plus every other file below its directory as an asset (paths relative to that directory)."""+ p = Path(path)+ assets = {str(f.relative_to(p.parent)): f.read_bytes() for f in sorted(p.parent.rglob("*"))+ if f.is_file() and f != p and "__pycache__" not in f.parts}+ return Scene(engine="mujoco", xml=p.read_text(), assets=assets, look=look)+++class Renderer(ABC):+ name: str = ""+ realtime: bool = True # fast enough for player images (still subject to the task's frame budget)+ needs_gpu: bool = False+ label: str | None = None # the tag a re-rendered frame carries ("re-rendered: <engine>"); None = default++ def __init__(self, scene: Scene, **opts):+ self.scene, self.opts = scene, opts++ @abstractmethod+ def render(self, state: dict, cameras: list) -> list:+ """One H x W x 3 uint8 image per camera (CameraDef or its dict form), for the given world state."""++ def close(self):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()+++def as_cameras(cameras) -> list:+ return [c if isinstance(c, CameraDef) else CameraDef.from_dict(c) for c in cameras]diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/budget.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/budget.pynew file mode 100644index 0000000000..a84e245e2e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/budget.py@@ -0,0 +1,31 @@+"""Frame-time budget of a player-image renderer (renderer rule 3): an observation (all of a seat's cameras) must be+drawn within the task's `frame_budget_ms`. tools/check measures it for the task's `renderer` parameter."""+from __future__ import annotations++import time++from .base import as_cameras+++def frame_ms(renderer_cls, scene, state, cameras, n: int = 5, warmup: int = 1, **opts) -> float:+ """Median wall milliseconds per observation (every camera once), after `warmup` untimed observations."""+ cams = as_cameras(cameras)+ r = renderer_cls(scene, **opts)+ try:+ for _ in range(warmup):+ r.render(state, cams)+ times = []+ for _ in range(max(1, n)):+ t = time.perf_counter()+ r.render(state, cams)+ times.append((time.perf_counter() - t) * 1000.0)+ finally:+ r.close()+ times.sort()+ return times[len(times) // 2]+++def check_budget(renderer_cls, scene, state, cameras, budget_ms: float, n: int = 5, **opts):+ """(ok, ms): ok when the renderer is real time and its median observation time is within budget_ms."""+ ms = frame_ms(renderer_cls, scene, state, cameras, n=n, **opts)+ return bool(getattr(renderer_cls, "realtime", False) and ms <= float(budget_ms)), msdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/cycles/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/cycles/__init__.pynew file mode 100644index 0000000000..d38cf96c01--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/cycles/__init__.py@@ -0,0 +1,38 @@+"""Blender 4.2 Cycles path tracing (offline, for re-rendering): the export of renderers/export.py traced by+scripts/olympiad/showcase/blender/cycles_render.py in the rcb-showcase-blender image. device = OPTIX (default) or+CUDA (GPU), or CPU (slow, no GPU needed)."""+from __future__ import annotations++import os++from ..export import SHOWCASE_TOOLS+from ..pathtrace import PathTracer++IMAGE = os.environ.get("SHOWCASE_BLENDER_IMAGE", "rcb-showcase-blender:4.2.23")+++class CyclesRenderer(PathTracer):+ name = "cycles"+ title = "Blender Cycles"+ image = IMAGE+ requirements = (f"Docker, the image {IMAGE} (docker build -t {IMAGE} scripts/olympiad/showcase/blender; 1.8 GB) "+ "and an NVIDIA GPU with the NVIDIA Container Toolkit (device=CPU works without one, slowly); "+ "mujoco in the calling process for the scene export")++ def __init__(self, scene, device: str = "OPTIX", **opts):+ self.device = device+ super().__init__(scene, **opts)+ if device == "CPU":+ self.needs_gpu = False++ def gpu_optional(self):+ return self.device == "CPU"++ def trace(self, work, size):+ self.docker(["-v", f"{work}:/s", "-v", f"{SHOWCASE_TOOLS}:/w:ro", self.image, "blender", "-b",+ "--factory-startup", "-P", "/w/blender/cycles_render.py", "--", "/s/export", "/s/out",+ "--samples", str(self.samples), "--size", size, "--device", self.device],+ gpu=self.device != "CPU")+++RENDERER = CyclesRendererdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/export.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/export.pynew file mode 100644index 0000000000..34e42323f6--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/export.py@@ -0,0 +1,104 @@+"""Scene export for the path-traced renderers (cycles, isaac): the format of scripts/olympiad/showcase/blender/+export_scene.py (scene.json, meshes.npz, poses.npz), written from a renderer's own MuJoCo model, a list of world+states and one camera per state. Geometry = the model's own meshes and tessellated primitives; materials and lights+= the showcase model's; the camera of each frame = its CameraDef (as lookat / distance / azimuth / elevation; the+path tracers keep the world z axis up, so a camera's `up` must be +z)."""+from __future__ import annotations++import json+import os+import sys++import numpy as np++from .base import CameraDef+from .scene_check import DEFAULT_RGBA, effective_rgba++SHOWCASE_TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts", "olympiad",+ "showcase")+++def _geom_mesh():+ sys.path[:0] = [p for p in (SHOWCASE_TOOLS, os.path.join(SHOWCASE_TOOLS, "blender")) if p not in sys.path]+ from export_scene import geom_mesh+ return geom_mesh+++def export(m, frames: list, outdir: str, title: str = "renderer") -> dict:+ """frames = [(state, CameraDef)], all cameras with the same size and field of view. Returns the scene summary."""+ import mujoco as mj+ from .mujoco import MujocoRenderer # noqa: F401 (same state handling)+ cams = [c for _, c in frames]+ if len({(c.width, c.height, c.fovy_deg) for c in cams}) != 1:+ raise ValueError("one export holds cameras of one size and field of view")+ for c in cams:+ if abs(abs(float(np.dot(c.up, (0, 0, 1)))) - float(np.linalg.norm(c.up))) > 1e-9 or c.up[2] <= 0:+ raise ValueError(f"camera {c.name}: the path tracers support up = +z only")+ geom_mesh = _geom_mesh()+ os.makedirs(outdir, exist_ok=True)+ d = mj.MjData(m)+ geoms, meshes = [], {}+ for g in range(m.ngeom):+ if m.geom_group[g] not in (0, 1, 2):+ continue+ rgba = np.asarray(effective_rgba(m, g), float)+ if rgba[3] <= 0.01:+ continue+ gm = geom_mesh(m, g)+ if gm is None:+ continue+ v, f, shade = gm+ meshes[f"v{g}"], meshes[f"f{g}"] = v.astype(np.float32), f.astype(np.int32)+ mid = int(m.geom_matid[g])+ mat = dict(specular=0.5, shininess=0.5, reflectance=0.0, emission=0.0, tex=None, texrepeat=[1, 1])+ if mid >= 0:+ mat.update(specular=float(m.mat_specular[mid]), shininess=float(m.mat_shininess[mid]),+ emission=float(m.mat_emission[mid]), reflectance=float(m.mat_reflectance[mid]),+ texrepeat=[float(x) for x in m.mat_texrepeat[mid]])+ tid = int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB])+ if tid >= 0 and m.tex_type[tid] == mj.mjtTexture.mjTEXTURE_2D:+ from PIL import Image+ h, w, c = m.tex_height[tid], m.tex_width[tid], m.tex_nchannel[tid]+ px = m.tex_data[m.tex_adr[tid]:m.tex_adr[tid] + h * w * c].reshape(h, w, c)[..., :3]+ name = f"tex{tid}.png"+ if not os.path.exists(os.path.join(outdir, name)):+ Image.fromarray(px).save(os.path.join(outdir, name))+ mat["tex"] = name+ rgba = m.mat_rgba[mid].astype(float) if np.allclose(m.geom_rgba[g], DEFAULT_RGBA) else rgba+ geoms.append(dict(id=g, name=m.geom(g).name or f"geom{g}", type=int(m.geom_type[g]),+ size=[float(x) for x in m.geom_size[g]], rgba=[float(x) for x in rgba], shade=shade,+ static=bool(m.body_weldid[m.geom_bodyid[g]] == 0), mat=mat))+ np.savez_compressed(os.path.join(outdir, "meshes.npz"), **meshes)+ ids = [gg["id"] for gg in geoms]+ pos = np.zeros((len(frames), len(ids), 3), np.float32)+ rot = np.zeros((len(frames), len(ids), 9), np.float32)+ for j, (state, _) in enumerate(frames):+ d.qpos[:] = np.asarray(state["qpos"], float)+ if m.nmocap and "mocap_pos" in state:+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(-1, 3)+ if m.nmocap and "mocap_quat" in state:+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(-1, 4)+ mj.mj_kinematics(m, d)+ mj.mj_comPos(m, d)+ mj.mj_camlight(m, d)+ pos[j], rot[j] = d.geom_xpos[ids], d.geom_xmat[ids]+ np.savez_compressed(os.path.join(outdir, "poses.npz"), pos=pos, rot=rot, step=np.arange(len(frames)))+ lights = [dict(name=m.light(i).name or f"light{i}", type=int(m.light_type[i]) if hasattr(m, "light_type") else 0,+ pos=[float(x) for x in d.light_xpos[i]], dir=[float(x) for x in d.light_xdir[i]],+ diffuse=[float(x) for x in m.light_diffuse[i]], cutoff=float(m.light_cutoff[i]),+ exponent=float(m.light_exponent[i]), castshadow=bool(m.light_castshadow[i]),+ bulbradius=float(m.light_bulbradius[i])) for i in range(m.nlight)]+ sky = None+ for t in range(m.ntex):+ if m.tex_type[t] == mj.mjtTexture.mjTEXTURE_SKYBOX:+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, w, c)+ sky = dict(top=(px[:h // 6].reshape(-1, c)[:, :3].mean(0) / 255).tolist(),+ horizon=(px[h * 5 // 6 - h // 12: h * 5 // 6].reshape(-1, c)[:, :3].mean(0) / 255).tolist())+ scene = dict(sport=title, decor=None, fps=1.0, fovy=float(cams[0].fovy_deg), geoms=geoms, lights=lights,+ headlight=dict(ambient=[float(x) for x in m.vis.headlight.ambient],+ diffuse=[float(x) for x in m.vis.headlight.diffuse]),+ sky=sky, cameras=[CameraDef.spherical(c) for c in cams], steps=list(range(len(frames))))+ with open(os.path.join(outdir, "scene.json"), "w") as f:+ json.dump(scene, f)+ return dict(geoms=len(geoms), frames=len(frames), lights=len(lights))diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/isaac/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/isaac/__init__.pynew file mode 100644index 0000000000..1b1d6d9402--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/isaac/__init__.py@@ -0,0 +1,49 @@+"""NVIDIA Isaac Sim 4.5 RTX path tracing (offline, for re-rendering): the export of renderers/export.py rendered by+scripts/olympiad/showcase/isaac/isaac_render.py in nvcr.io/nvidia/isaac-sim:4.5.0 (as root, as rerender.py runs it;+shader caches in SHOWCASE_ISAAC_CACHE, the first start compiles shaders for ~10 min)."""+from __future__ import annotations++import os+import subprocess++from ..export import SHOWCASE_TOOLS+from ..pathtrace import PathTracer++IMAGE = os.environ.get("SHOWCASE_ISAAC_IMAGE", "nvcr.io/nvidia/isaac-sim:4.5.0")+CACHE = os.environ.get("SHOWCASE_ISAAC_CACHE", os.path.expanduser("~/.cache/rcb-showcase-isaac"))+CACHES = (("kit", "/isaac-sim/kit/cache"), ("ov", "/root/.cache/ov"), ("glcache", "/root/.cache/nvidia/GLCache"),+ ("computecache", "/root/.nv/ComputeCache"), ("logs", "/root/.nvidia-omniverse/logs"),+ ("data", "/root/.local/share/ov/data"))+++class IsaacRenderer(PathTracer):+ name = "isaac"+ title = "Isaac Sim RTX"+ image = IMAGE+ requirements = (f"Docker, an NVIDIA RTX GPU (driver >= 535.129) with the NVIDIA Container Toolkit, the image "+ f"{IMAGE} (15 GB), ~20 GB free disk for caches, the NVIDIA Omniverse EULA (ACCEPT_EULA=Y); "+ "mujoco in the calling process for the scene export")++ def __init__(self, scene, mode: str = "PathTracing", **opts):+ self.mode = mode+ super().__init__(scene, **opts)++ def trace(self, work, size):+ args = ["-e", "ACCEPT_EULA=Y", "-e", "PRIVACY_CONSENT=Y", "-e", "OMNI_KIT_ACCEPT_EULA=YES"]+ for sub, dst in CACHES:+ os.makedirs(os.path.join(CACHE, sub), exist_ok=True)+ args += ["-v", f"{os.path.join(CACHE, sub)}:{dst}:rw"]+ if os.path.exists("/usr/share/nvidia/nvoptix.bin"):+ args += ["-v", "/usr/share/nvidia/nvoptix.bin:/usr/share/nvidia/nvoptix.bin:ro"]+ args += ["-v", f"{work}:/s", "-v", f"{SHOWCASE_TOOLS}:/w:ro", "--entrypoint", "/isaac-sim/python.sh", self.image,+ "/w/isaac/isaac_render.py", "/s/export", "/s/out", "--spp", str(self.samples), "--size", size,+ "--mode", self.mode]+ try:+ self.docker(args, gpu=True, root=True)+ finally: # Isaac writes as root+ subprocess.run(["docker", "run", "--rm", "--name", f"ro-renderer-isaac-chown-{os.getpid()}", "-v",+ f"{work}:/s", "--entrypoint", "chown", self.image, "-R",+ f"{os.getuid()}:{os.getgid()}", "/s"], capture_output=True)+++RENDERER = IsaacRendererdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/label.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/label.pynew file mode 100644index 0000000000..8dda2059eb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/label.py@@ -0,0 +1,40 @@+"""The tag on every re-rendered frame (renderer rule 5): which renderer drew it, bottom right, and whether the scene was+a presentation scene (renderer rule 6)."""+from __future__ import annotations++import numpy as np+++PRESENTATION = "presentation meshes, spectators only"+++def label_text(engine_title: str, decor: bool = False, presentation: bool = False) -> str:+ return (f"re-rendered: {engine_title}" + (" | surroundings for presentation only" if decor else "")+ + (f" | {PRESENTATION}" if presentation else ""))+++def frame_label(renderer, scene) -> str | None:+ """The tag of a spectator frame drawn by `renderer` (a Renderer instance or class) from `scene`: the renderer's+ own label, with the presentation-scene note when the scene is one; None = the competition picture (the default+ renderer on the match scene, or on the presentation scene a sport declares for its players' images), which+ carries no tag."""+ title = getattr(renderer, "title", None) or getattr(renderer, "name", "renderer")+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):+ return label_text(title, presentation=True)+ return getattr(renderer, "label", None)+++def stamp(img: np.ndarray, text: str) -> np.ndarray:+ from PIL import Image, ImageDraw, ImageFont+ im = Image.fromarray(np.ascontiguousarray(img))+ d = ImageDraw.Draw(im, "RGBA")+ s = max(10, im.size[1] // 40)+ try:+ f = ImageFont.truetype("DejaVuSans.ttf", s)+ except OSError:+ f = ImageFont.load_default()+ w = d.textlength(text, font=f)+ W, H = im.size+ d.rectangle([W - w - 16, H - s - 14, W - 4, H - 4], fill=(0, 0, 0, 150))+ d.text((W - w - 10, H - s - 10), text, font=f, fill=(255, 255, 255, 235))+ return np.asarray(im)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/mujoco/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/mujoco/__init__.pynew file mode 100644index 0000000000..1f52d6a69d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/mujoco/__init__.py@@ -0,0 +1,144 @@+"""The default renderer: MuJoCo's own rasterizer (CPU with MUJOCO_GL=osmesa, GPU with egl), real time.++The scene is compiled once from its MJCF text with spare world-body cameras added; each CameraDef is drawn by+setting one spare camera's pose and vertical field of view exactly (cam_pos / cam_quat / cam_fovy), so the picture+follows CameraDef.project to the pixel. The renderer keeps its own MjModel / MjData: the match's world is never+touched. A presentation scene (Scene.match set; spectators only) is drawn only when its kinematics equal the match+scene's (scene_check.same_kinematics); every renderer built on this one inherits the check."""+from __future__ import annotations++import numpy as np++from ..base import CameraDef, Renderer, RendererUnavailable, Scene, as_cameras++SPARE = "_ro_cam"+++def camera_quat(cam: CameraDef):+ """MuJoCo camera frame: x = image right, y = image up, looking along -z."""+ import mujoco as mj+ right, up, fwd = cam.basis()+ R = np.column_stack([right, up, -fwd])+ q = np.zeros(4)+ mj.mju_mat2Quat(q, R.reshape(-1))+ return q+++def compile_spec(spec, n_cams: int, size):+ """Add n spare cameras and make the off-screen buffer at least `size` (w, h); returns the compiled model."""+ g = spec.visual.global_+ g.offwidth, g.offheight = max(int(g.offwidth), int(size[0])), max(int(g.offheight), int(size[1]))+ for i in range(n_cams):+ spec.worldbody.add_camera(name=f"{SPARE}{i}", pos=[0, 0, 0], quat=[1, 0, 0, 0], fovy=45)+ return spec.compile()+++def load_spec(scene: Scene):+ import mujoco as mj+ if scene.engine != "mujoco":+ raise RendererUnavailable("mujoco", f"scene engine {scene.engine!r} is not MJCF")+ return mj.MjSpec.from_string(scene.xml, assets=dict(scene.assets or {}))+++class MujocoRenderer(Renderer):+ name = "mujoco"+ title = "MuJoCo"+ realtime = True+ needs_gpu = False+ label = None # the competition picture: no tag++ def __init__(self, scene: Scene, n_cams: int = 8, size=(640, 480), **opts):+ super().__init__(scene, **opts)+ try:+ import mujoco # noqa: F401+ except ImportError as exc: # pragma: no cover - the sim images have it+ raise RendererUnavailable(self.name, "the mujoco Python package is missing", "mujoco") from exc+ self._n, self._size = int(n_cams), tuple(size)+ self._build()++ # ---------------------------------------------------------------- model+ def make_spec(self):+ """The MjSpec to draw (subclasses change only visual properties)."""+ return load_spec(self.scene)++ def _build(self):+ import mujoco as mj+ self.close()+ self.m = compile_spec(self.make_spec(), self._n, self._size)+ if self.scene.match is not None: # a presentation scene: same kinematics as the match scene+ from ..scene_check import same_kinematics+ bad = same_kinematics(compile_spec(load_spec(self.scene.match), self._n, self._size), self.m)+ if bad:+ raise RuntimeError(f"{self.name}: the presentation scene's kinematics differ from the match scene: "+ f"{bad[:8]}")+ self.d = mj.MjData(self.m)+ self.cam_ids = [self.m.camera(f"{SPARE}{i}").id for i in range(self._n)]+ self._r = {}++ def _renderer(self, w, h):+ import mujoco as mj+ if (w, h) not in self._r:+ self._r[w, h] = mj.Renderer(self.m, height=h, width=w)+ return self._r[w, h]++ def set_state(self, state: dict):+ import mujoco as mj+ m, d = self.m, self.d+ q = np.asarray(state.get("qpos", d.qpos), dtype=float)+ if q.shape != (m.nq,):+ raise ValueError(f"state qpos has {q.size} values, the scene has nq={m.nq}")+ d.qpos[:] = q+ if m.nmocap:+ if "mocap_pos" in state:+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(m.nmocap, 3)+ if "mocap_quat" in state:+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(m.nmocap, 4)+ mj.mj_kinematics(m, d)+ mj.mj_comPos(m, d)+ mj.mj_camlight(m, d)++ # ---------------------------------------------------------------- drawing+ def render(self, state: dict, cameras: list) -> list:+ import mujoco as mj+ cams = as_cameras(cameras)+ w_max, h_max = max([c.width for c in cams] + [1]), max([c.height for c in cams] + [1])+ if len(cams) > self._n or w_max > self.m.vis.global_.offwidth or h_max > self.m.vis.global_.offheight:+ self._n = max(self._n, len(cams))+ self._size = (max(self._size[0], w_max), max(self._size[1], h_max))+ self._build()+ self.set_state(state)+ for cam, cid in zip(cams, self.cam_ids):+ self.m.cam_pos[cid] = cam.pos+ self.m.cam_quat[cid] = camera_quat(cam)+ self.m.cam_fovy[cid] = cam.fovy_deg+ mj.mj_camlight(self.m, self.d) # camera world poses from the new cam_pos / cam_quat+ self._clip(cams)+ out = []+ for cam, cid in zip(cams, self.cam_ids):+ r = self._renderer(cam.width, cam.height)+ r.update_scene(self.d, camera=cid)+ out.append(self.post(np.array(r.render(), dtype=np.uint8, copy=True), cam))+ return out++ def _clip(self, cams):+ """MuJoCo clips at zfar * stat.extent: keep every geom of the current state inside every camera's far plane+ (a small scene seen from afar, or a body far from the scene centre, would otherwise vanish). Visualization+ only, on our own model copy."""+ m, d = self.m, self.d+ ext = max(float(m.stat.extent), 1e-6)+ pts = np.asarray(d.geom_xpos) if m.ngeom else np.zeros((1, 3))+ rb = float(np.max(m.geom_rbound)) if m.ngeom else 0.0+ reach = max(float(np.max(np.linalg.norm(pts - np.asarray(c.pos), axis=1))) for c in cams) + rb+ if m.vis.map.zfar * ext < 1.05 * reach:+ m.vis.map.zfar = 1.05 * reach / ext++ def post(self, img, cam):+ return img++ def close(self):+ for r in getattr(self, "_r", {}).values():+ r.close()+ self._r = {}+++RENDERER = MujocoRendererdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/mujoco_showcase/__init__.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/mujoco_showcase/__init__.pynew file mode 100644index 0000000000..79543dd381--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/mujoco_showcase/__init__.py@@ -0,0 +1,121 @@+"""MuJoCo showcase: the same rasterizer with better lights, materials and anti-aliasing (real time; CPU with osmesa,+GPU optional). The scene is the default renderer's scene with visual changes only, checked by scene_check.same_scene+before the first frame (the renderer refuses to draw otherwise).++Look (Scene.look): None or {} = the generic showcase look below (shadow-casting key light, soft fill, satin materials+that keep every geom's colour, MSAA); {"preset": <name>} = a sport's look from scripts/olympiad/showcase/looks.py+(SHOWCASE[name], e.g. "tabletennis"), available when this checkout's showcase tools are present.+Options: ssaa (supersampling factor, default 1; 2 for re-renders), stamp (tag every frame with `label`, default False:+the tag is for re-rendered outputs, not for player images).++A presentation scene (Scene.match set, renderers/presentation.py): its added visual geoms keep their own materials+under any look, the kinematics check of the default renderer applies, and `label` says it is a presentation scene."""+from __future__ import annotations++import os+import sys++import numpy as np++from ..base import RendererUnavailable, Scene+from ..label import label_text, stamp+from ..mujoco import MujocoRenderer, compile_spec, load_spec+from ..scene_check import DEFAULT_RGBA, VISUAL_PREFIX, same_scene++SHOWCASE_TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),+ "scripts", "olympiad", "showcase")+++def _material(spec, name, **kw):+ mt = spec.add_material(name=name)+ for k, v in kw.items():+ setattr(mt, k, v)+ return mt+++def generic_look(spec, size):+ import mujoco as mj+ v = spec.visual+ v.global_.offwidth, v.global_.offheight = max(v.global_.offwidth, size[0]), max(v.global_.offheight, size[1])+ v.quality.offsamples = 8+ v.quality.shadowsize = 4096+ v.headlight.ambient = [0.18, 0.18, 0.2]+ v.headlight.diffuse = [0.25, 0.25, 0.25]+ v.headlight.specular = [0.1, 0.1, 0.1]+ for li in spec.lights:+ li.castshadow = True+ key = spec.worldbody.add_light(name="_showcase_key", pos=[4, -4, 8], dir=[-0.45, 0.45, -0.77],+ diffuse=[0.55, 0.53, 0.5], specular=[0.3, 0.3, 0.3], castshadow=True)+ fill = spec.worldbody.add_light(name="_showcase_fill", pos=[-4, 4, 6], dir=[0.5, -0.5, -0.7],+ diffuse=[0.22, 0.24, 0.28], specular=[0, 0, 0], castshadow=False)+ for li in (key, fill):+ if hasattr(li, "type"): # MuJoCo >= 3.3: light type enum+ li.type = mj.mjtLightType.mjLIGHT_DIRECTIONAL+ else: # pragma: no cover+ li.directional = True+ _material(spec, "_showcase_satin", specular=0.45, shininess=0.55, reflectance=0.0)+ _material(spec, "_showcase_satin_default", specular=0.45, shininess=0.55, reflectance=0.0, rgba=list(DEFAULT_RGBA))+ for g in spec.geoms:+ if g.material:+ continue # textured or already styled: keep it+ g.material = "_showcase_satin" if tuple(np.round(g.rgba, 6)) != DEFAULT_RGBA else "_showcase_satin_default"+++def preset_look(name):+ if not os.path.isdir(SHOWCASE_TOOLS):+ raise RendererUnavailable("mujoco-showcase", f"look preset {name!r} needs scripts/olympiad/showcase/looks.py")+ if SHOWCASE_TOOLS not in sys.path:+ sys.path.insert(0, SHOWCASE_TOOLS)+ import looks+ if name not in looks.SHOWCASE:+ raise ValueError(f"unknown showcase look {name!r}; have {sorted(looks.SHOWCASE)}")+ return looks.SHOWCASE[name]+++class ShowcaseRenderer(MujocoRenderer):+ name = "mujoco-showcase"+ title = "MuJoCo showcase"+ realtime = True+ needs_gpu = False+ label = label_text(title)++ def __init__(self, scene: Scene, ssaa: int = 1, stamp: bool = False, **opts):+ self.ssaa, self.stamp = max(1, int(ssaa)), bool(stamp)+ self.label = label_text(self.title, presentation=scene.match is not None and not scene.players)+ super().__init__(scene, **opts)++ def make_spec(self):+ spec = load_spec(self.scene)+ size = (self._size[0] * self.ssaa, self._size[1] * self.ssaa)+ look = self.scene.look or {}+ added = {g.name: g.material for g in spec.geoms if (g.name or "").startswith(VISUAL_PREFIX)}+ (preset_look(look["preset"]) if look.get("preset") else generic_look)(spec, size)+ for g in spec.geoms: # a presentation scene's own materials win over the look+ if g.name in added:+ g.material = added[g.name]+ return spec++ def _build(self):+ self._size = (max(self._size[0], 1), max(self._size[1], 1))+ super()._build()+ ref = compile_spec(load_spec(self.scene), self._n, self._size) # what the default renderer draws+ bad = same_scene(ref, self.m)+ if bad:+ raise RuntimeError(f"{self.name}: not the same scene as the default renderer: {bad[:8]}")+ self.scene_diffs = bad++ def render(self, state, cameras):+ from ..base import as_cameras+ cams = as_cameras(cameras)+ s = self.ssaa+ big = [type(c)(c.name, c.pos, c.lookat, c.up, c.fovy_deg, c.width * s, c.height * s) for c in cams]+ imgs = super().render(state, big)+ out = []+ for img, c in zip(imgs, cams):+ if s > 1: # box filter: same projection, anti-aliased+ img = img.reshape(c.height, s, c.width, s, 3).mean(axis=(1, 3)).round().astype(np.uint8)+ out.append(stamp(img, self.label) if self.stamp else img)+ return out+++RENDERER = ShowcaseRendererdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/pathtrace.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/pathtrace.pynew file mode 100644index 0000000000..1e1847773d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/pathtrace.py@@ -0,0 +1,98 @@+"""Shared part of the offline path-traced renderers (cycles, isaac): preflight (Docker, image, GPU), the showcase+model with its same-scene check, export (export.py), one container run per camera group, PNG read-back and the+re-render tag on every frame. These renderers are for re-rendering recorded matches (realtime = False); they run on+a host with Docker and an NVIDIA GPU, and need mujoco in the calling process for the export."""+from __future__ import annotations++import glob+import os+import shutil+import subprocess+import tempfile++import numpy as np++from .base import Renderer, RendererUnavailable, Scene, as_cameras+from .export import SHOWCASE_TOOLS, export+from .label import label_text, stamp+++def image_present(image: str) -> bool:+ return subprocess.run(["docker", "image", "inspect", image], capture_output=True).returncode == 0+++def gpu_present(gpu) -> bool:+ if gpu is None or shutil.which("nvidia-smi") is None:+ return False+ r = subprocess.run(["nvidia-smi", "-i", str(gpu), "--query-gpu=name", "--format=csv,noheader"],+ capture_output=True, text=True)+ return r.returncode == 0 and bool(r.stdout.strip())+++class PathTracer(Renderer):+ realtime = False+ needs_gpu = True+ image = ""+ requirements = ""+ title = ""++ def __init__(self, scene: Scene, gpu="0", samples: int = 64, stamp: bool = True, **opts):+ super().__init__(scene, **opts)+ self.gpu = None if gpu in (None, "none") else str(gpu)+ self.samples, self.stamp = int(samples), bool(stamp)+ self.label = label_text(self.title, presentation=scene.match is not None and not scene.players)+ self.preflight()+ from .mujoco_showcase import ShowcaseRenderer+ self._model = ShowcaseRenderer(scene, n_cams=1).m # raises unless it is the same scene++ def needs(self):+ return [] if self.gpu_optional() else [("gpu", gpu_present(self.gpu), "an NVIDIA GPU (gpu=<index>)")]++ def gpu_optional(self) -> bool:+ return False++ def preflight(self):+ if os.environ.get("RO_RENDERER_OFFLINE") == "1":+ raise RendererUnavailable(self.name, "disabled on this host (RO_RENDERER_OFFLINE=1)", self.requirements)+ if shutil.which("docker") is None or subprocess.run(["docker", "version"], capture_output=True).returncode:+ raise RendererUnavailable(self.name, "Docker is not available here", self.requirements)+ if not image_present(self.image):+ raise RendererUnavailable(self.name, f"missing image {self.image}", self.requirements)+ for what, ok, text in self.needs():+ if not ok:+ raise RendererUnavailable(self.name, f"no {text}", self.requirements)+ if not os.path.isdir(SHOWCASE_TOOLS):+ raise RendererUnavailable(self.name, "scripts/olympiad/showcase is missing", self.requirements)++ def render(self, state, cameras):+ cams = as_cameras(cameras)+ out = [None] * len(cams)+ groups = {}+ for i, c in enumerate(cams):+ groups.setdefault((c.width, c.height, c.fovy_deg), []).append(i)+ for (w, h, _), idx in groups.items():+ work = tempfile.mkdtemp(prefix=f"ro-{self.name}-")+ try:+ export(self._model, [(state, cams[i]) for i in idx], os.path.join(work, "export"), self.name)+ self.trace(work, f"{w}x{h}")+ files = sorted(glob.glob(os.path.join(work, "out", "frame_*.png")))+ if len(files) != len(idx):+ raise RuntimeError(f"{self.name}: {len(files)} frames for {len(idx)} cameras")+ from PIL import Image+ for i, f in zip(idx, files):+ img = np.asarray(Image.open(f).convert("RGB"))+ out[i] = stamp(img, self.label) if self.stamp else img+ finally:+ shutil.rmtree(work, ignore_errors=True)+ return out++ def trace(self, work: str, size: str):+ raise NotImplementedError++ def docker(self, args, gpu=True, root=False):+ c = ["docker", "run", "--rm", "--name", f"ro-renderer-{self.name}-{os.getpid()}", "--network", "none"]+ if not root:+ c += ["--user", f"{os.getuid()}:{os.getgid()}", "-e", "HOME=/tmp"]+ if gpu and self.gpu is not None:+ c += ["--gpus", f"device={self.gpu}", "-e", "NVIDIA_DRIVER_CAPABILITIES=all"]+ subprocess.run(c + args, check=True, capture_output=True)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/scene_check.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/scene_check.pynew file mode 100644index 0000000000..5713371f35--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/renderers/scene_check.py@@ -0,0 +1,164 @@+"""Same scene (renderer rule 2): a non-default renderer draws the default renderer's scene. The geometry, kinematics,+cameras and the colour a viewer sees of every untextured geom must be identical; a re-textured surface keeps its mean+colour within TEXTURE_TOL. Only lights, materials (specular, shininess, reflectance, textures with the same mean+colour) and image quality may differ. The same rule as scripts/olympiad/showcase/looks.same_scene, without the+sport-specific decor exception (decor is presentation-only and never part of a renderer's player picture).++Same kinematics (renderer rule 6): a presentation scene (renderers/presentation.py, spectators only) may differ from+the match scene in appearance and by added visual-only geoms, never in bodies, joints, frames, inertias or cameras;+same_kinematics() checks it before a renderer draws one, pose_diff() compares body poses over recorded states."""+from __future__ import annotations++import numpy as np++SAME = ("nq", "nv", "nbody", "njnt", "ngeom", "nmesh", "ncam", "nmocap",+ "body_parentid", "body_pos", "body_quat", "body_mass", "jnt_type", "jnt_qposadr", "jnt_pos", "jnt_axis",+ "geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_group", "geom_dataid",+ "mesh_vertnum", "mesh_vert", "mesh_face",+ "cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")+DEFAULT_RGBA = (0.5, 0.5, 0.5, 1.0)+TEXTURE_TOL = 0.02+MESH = 7 # mjtGeom.mjGEOM_MESH+++def effective_rgba(m, g):+ rgba = m.geom_rgba[g]+ if m.geom_matid[g] >= 0 and np.allclose(rgba, DEFAULT_RGBA):+ return m.mat_rgba[m.geom_matid[g]]+ return rgba+++def _texid(m, g):+ import mujoco as mj+ mid = m.geom_matid[g]+ return int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB]) if mid >= 0 else -1+++def _mean_colour(m, g):+ """Mean drawn colour of a geom (texture mean x material/geom colour), 0..1 RGB."""+ rgba = np.asarray(effective_rgba(m, g)[:3], float)+ t = _texid(m, g)+ if t < 0:+ return rgba+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, c)[:, :3]+ return rgba * (px.mean(0) / 255.0)+++SPARE = "_ro_cam" # the renderers' own spare cameras (renderers/mujoco), posed per frame: not scene cameras+++def _scene_cams(m):+ return [i for i in range(m.ncam) if not (m.camera(i).name or "").startswith(SPARE)]+++def same_scene(m0, m1) -> list:+ """Differences between the default model m0 and the renderer's model m1 (empty list = the same scene)."""+ bad = []+ c0, c1 = _scene_cams(m0), _scene_cams(m1)+ for name in SAME:+ a, b = np.asarray(getattr(m0, name)), np.asarray(getattr(m1, name))+ if name.startswith("cam_"):+ a, b = a[c0], b[c1]+ elif name == "ncam":+ a, b = np.asarray(len(c0)), np.asarray(len(c1))+ if np.shape(a) != np.shape(b) or not np.array_equal(a, b):+ bad.append(name)+ if bad:+ return bad+ if m0.vis.global_.fovy != m1.vis.global_.fovy:+ bad.append("vis.global.fovy")+ for g in range(m0.ngeom):+ t0, t1 = _texid(m0, g) >= 0, _texid(m1, g) >= 0+ if not t0 and not t1:+ if not np.allclose(effective_rgba(m0, g), effective_rgba(m1, g)):+ bad.append(f"colour of geom {m0.geom(g).name or g}")+ elif float(np.abs(_mean_colour(m0, g) - _mean_colour(m1, g)).max()) > TEXTURE_TOL:+ bad.append(f"mean colour of textured geom {m0.geom(g).name or g}")+ return bad+++# ------------------------------------------------------------------------------------- presentation scenes (spectators)+VISUAL_PREFIX = "_vis:" # the name prefix of a presentation scene's added geoms (renderers/presentation.py)+KINEMATICS = ("nq", "nv", "nu", "nbody", "njnt", "nmocap", "nsite", "qpos0",+ "body_parentid", "body_rootid", "body_weldid", "body_mocapid", "body_jntnum", "body_jntadr",+ "body_dofnum", "body_dofadr", "body_pos", "body_quat", "body_ipos", "body_iquat", "body_mass",+ "body_inertia", "jnt_type", "jnt_bodyid", "jnt_qposadr", "jnt_dofadr", "jnt_pos", "jnt_axis",+ "jnt_range", "dof_bodyid", "dof_jntid", "dof_armature", "dof_damping", "actuator_trnid",+ "site_bodyid", "site_pos", "site_quat", "opt.timestep", "opt.gravity")+MATCH_GEOM = ("geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_contype", "geom_conaffinity",+ "geom_condim", "geom_priority", "geom_friction", "geom_solref", "geom_solimp", "geom_margin", "geom_gap")+CAMERA = ("cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")+++def _arr(m, name):+ o = m+ for part in name.split("."):+ o = getattr(o, part)+ return np.asarray(o)+++def visual_geoms(m) -> list:+ return [g for g in range(m.ngeom) if (m.geom(g).name or "").startswith(VISUAL_PREFIX)]+++def _mesh_verts(m, g):+ i = m.geom_dataid[g]+ return m.mesh_vert[m.mesh_vertadr[i]:m.mesh_vertadr[i] + m.mesh_vertnum[i]]+++def same_kinematics(m0, m1) -> list:+ """Differences between the match model m0 and a presentation model m1 (empty list = the same kinematics):+ every body, joint, dof, frame, inertia, site, mocap body and scene camera is identical; m0's geoms are all in m1,+ in the same order, with the same geometry, pose and contact properties (only their appearance may change:+ group, colour, material, e.g. a collision mesh moved to the hidden group 3); every other geom of m1 is an added+ visual geom (name prefix VISUAL_PREFIX) that never collides (contype = conaffinity = 0) and is drawn (group+ 0..2). Body masses and inertias being equal, the added geoms carry no mass. So the same qpos puts every body at+ the same pose in both models: a presentation scene changes only what a spectator sees."""+ bad = []+ for name in KINEMATICS:+ a, b = _arr(m0, name), _arr(m1, name)+ if a.shape != b.shape or not np.array_equal(a, b):+ bad.append(name)+ c0, c1 = _scene_cams(m0), _scene_cams(m1)+ if len(c0) != len(c1):+ bad.append("ncam")+ else:+ bad += [n for n in CAMERA if not np.array_equal(_arr(m0, n)[c0], _arr(m1, n)[c1])]+ if bad:+ return bad+ extra = visual_geoms(m1)+ keep = [g for g in range(m1.ngeom) if g not in set(extra)]+ if len(keep) != m0.ngeom:+ return [f"{len(keep)} match geoms in the presentation scene for {m0.ngeom}"]+ bad += [n for n in MATCH_GEOM if not np.array_equal(_arr(m0, n), _arr(m1, n)[keep])]+ for g0, g1 in enumerate(keep):+ if (m0.geom(g0).name or "") != (m1.geom(g1).name or ""):+ bad.append(f"name of geom {g0}")+ elif m0.geom_dataid[g0] >= 0 and m0.geom_type[g0] == MESH and not np.array_equal(_mesh_verts(m0, g0),+ _mesh_verts(m1, g1)):+ bad.append(f"mesh of geom {m0.geom(g0).name or g0}")+ for g in extra:+ if m1.geom_contype[g] or m1.geom_conaffinity[g] or not 0 <= m1.geom_group[g] <= 2:+ bad.append(f"added geom {m1.geom(g).name} collides or is not drawn")+ return bad+++def pose_diff(m0, m1, states) -> float:+ """The largest difference of any body's (and site's) world position or orientation between the two models over+ the given states ({"qpos", optional "mocap_pos", "mocap_quat"}); 0.0 = bit-identical poses."""+ import mujoco as mj+ d0, d1 = mj.MjData(m0), mj.MjData(m1)+ worst = 0.0+ for st in states:+ for m, d in ((m0, d0), (m1, d1)):+ d.qpos[:] = np.asarray(st["qpos"], float)+ if m.nmocap and "mocap_pos" in st:+ d.mocap_pos[:] = np.asarray(st["mocap_pos"], float).reshape(m.nmocap, 3)+ if m.nmocap and "mocap_quat" in st:+ d.mocap_quat[:] = np.asarray(st["mocap_quat"], float).reshape(m.nmocap, 4)+ mj.mj_kinematics(m, d)+ for a, b in ((d0.xpos, d1.xpos), (d0.xquat, d1.xquat), (d0.xmat, d1.xmat), (d0.site_xpos, d1.site_xpos)):+ if np.asarray(a).size:+ worst = max(worst, float(np.abs(np.asarray(a) - np.asarray(b)).max()))+ return worstdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/spectator/broadcast_log.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/spectator/broadcast_log.pynew file mode 100644index 0000000000..879da02402--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/spectator/broadcast_log.py@@ -0,0 +1,140 @@+"""Spectator broadcast log: an append-only, compact record of what a broadcast camera needs to draw the match.++The sim service appends one line per drawn frame (every EVERY control steps of game time, plus the last state of every+point) and one line per match event (start, run, point, review pause, end) to /data/broadcast.jsonl. A renderer OUTSIDE+the sim (scripts/olympiad/broadcast.py) tails the file, rebuilds the MuJoCo state from the same scene and draws the+broadcast camera. Nothing in the sim reads this file back: the replay, the grader and the match result do not depend on+it, and any failure here only switches the log off (`RCB_BROADCAST=0` switches it off from the start).++Lines (JSON, one per line):+ {"ev": "hdr", "sport": ..., "mode": "single"|"duel", "slowdown": S, "dt": control step s, "every": n, ...}+ {"k": step, "q": [qpos ...], ...extra} a frame (extra: per-sport fields the drawing needs, e.g. "o")+ {"ev": "point"|"run"|"pause"|"end"|..., "k": step, ...}+"""+from __future__ import annotations++import json+import os+import time++PATH = os.path.join(os.environ.get("RCB_DATA", "/data"), "broadcast.jsonl")+++class BroadcastLog:+ def __init__(self, every: int = 2, digits: int = 5, path: str = PATH, **header):+ self.every = max(1, int(every))+ self.fmt = f"{{:.{int(digits)}f}}"+ self.f = None+ self.last_k = None+ if os.environ.get("RCB_BROADCAST", "1") != "1":+ return+ try:+ self.f = open(path, "a", buffering=1 << 16)+ self._write(json.dumps({"ev": "hdr", "ts": round(time.time(), 3), "every": self.every, **header}))+ except Exception: # noqa: BLE001 (spectator output only: never disturb the match)+ self.f = None++ def _write(self, line: str) -> None:+ if self.f is None:+ return+ try:+ self.f.write(line + "\n")+ self.f.flush()+ except Exception: # noqa: BLE001+ self.f = None++ def frame(self, k: int, q, force: bool = False, **extra) -> None:+ """One drawn frame at control step k (only every `every` steps unless forced; never twice for one step)."""+ if self.f is None or k == self.last_k or (not force and k % self.every):+ return+ self.last_k = k+ try:+ fmt = self.fmt.format+ s = '{"k":%d,"q":[%s]' % (k, ",".join(fmt(float(x)) for x in q))+ for key, v in extra.items():+ s += ',"%s":%s' % (key, json.dumps(v if not isinstance(v, float) else round(v, 5)))+ self._write(s + "}")+ except Exception: # noqa: BLE001+ self.f = None++ SKIP = ("k", "t", "leg_id", "wall_mono", "qpos", "point", "played_k", "flight")++ def snapshot(self, sn: dict, force: bool = False) -> None:+ """A frame from one of the sim's own camera snapshots (the dict its Match.step() keeps for the views: k,+ qpos and whatever else the sport draws, e.g. the ball "b" and the opponent "opp")."""+ if self.f is None or sn is None:+ return+ try:+ extra = {}+ for key, v in sn.items():+ if key in self.SKIP or v is None:+ continue+ if hasattr(v, "tolist"):+ v = v.tolist()+ if isinstance(v, (list, tuple)):+ v = [round(float(x), 5) if isinstance(x, float) else x for x in v]+ elif isinstance(v, float):+ v = round(v, 5)+ extra[key] = v+ self.frame(int(sn["k"]), sn["qpos"] if sn.get("qpos") is not None else (), force=force, **extra)+ except Exception: # noqa: BLE001+ self.f = None++ def after_step(self, game, point_ended: bool = False) -> None:+ """After a control step of a match object that keeps camera snapshots in `hist` (and the ended point's in+ `review_hist`): log the newest snapshot; when a point just ended, the point's last snapshot (the new point's+ reset state is not shown as the end of the old one)."""+ if self.f is None:+ return+ try:+ if point_ended:+ rh = getattr(game, "review_hist", None)+ if rh:+ self.snapshot(rh[-1], force=True)+ return+ h = game.hist[-1] if game.hist else None+ if h is not None and h["k"] == game.k:+ self.snapshot(h)+ except Exception: # noqa: BLE001+ self.f = None++ def event(self, ev: str, k: int, **fields) -> None:+ if self.f is None:+ return+ try:+ self._write(json.dumps({"ev": ev, "k": int(k), "ts": round(time.time(), 3), **fields}, default=_plain))+ except Exception: # noqa: BLE001+ self.f = None+++def pitch_frame(bc, rt) -> None:+ """Baseball (bbrt.RT / bbduel.Duel): a frame from the pitch clock's own display data (its newest camera snapshot:+ the ball, the swing's parameters and the time since release), every `every` steps of the pitch."""+ if bc is None or bc.f is None or rt.n % bc.every:+ return+ try:+ sn = rt.snapshots()[-1]+ bc.frame(int(sn["k"]), (), force=True, ball=[round(float(x), 4) for x in sn["ball"]],+ sw=None if sn["swing"] is None else [round(float(x), 5) for x in sn["swing"]], t=round(sn["t"], 4),+ p=int(sn["pitch"]))+ except Exception: # noqa: BLE001+ bc.f = None+++def flight(samples, step: float = 0.04, t_max: float = 8.0) -> list:+ """A batted ball's flight (bb.judge_batted samples: (t, x, y, z, ...)) every `step` s, for the replay."""+ out, nxt = [], 0.0+ for sm in samples or ():+ if sm[0] >= nxt - 1e-9 and sm[0] <= t_max:+ out.append([round(float(sm[0]), 3)] + [round(float(x), 3) for x in sm[1:4]])+ nxt = sm[0] + step+ if samples and (not out or out[-1][0] < samples[-1][0]) and samples[-1][0] <= t_max:+ out.append([round(float(samples[-1][0]), 3)] + [round(float(x), 3) for x in samples[-1][1:4]])+ return out+++def _plain(x):+ try:+ return x.tolist()+ except AttributeError:+ return str(x)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/bout.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/bout.pynew file mode 100644index 0000000000..2fae72600e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/bout.py@@ -0,0 +1,141 @@+"""The referee of an epee direct-elimination bout fenced phrase by phrase (FIE Technical Rules, August 2026: t.22,+t.37, t.38, t.44, t.92, t.124), the phrase-level sport since fencing-7.++The bout is 15 touches or 9 minutes of fencing time (t.38.2: three periods of 3 minutes; deviation: one period of 9+minutes, no breaks). Each phrase (phrases.py) gives a touch for one fencer, a double or none, and takes its fencing time+(the time to the halt; 3 s for a phrase without a touch). A double scores for both (t.92), except at 14-14, where it is+not counted. When the clock ends during a phrase, the phrase ends without a touch (t.44.1). At time the fencer ahead+wins; at equal scores one more minute for a deciding touch, the priority drawn by lot before it; still equal after the+minute, the fencer with priority wins. Every phrase starts on guard (t.22).++Unwillingness to fight (t.124): one minute of fencing time without a hit -> 'Halt!'. The first time both fencers get a+P-red card, a penalty hit each; the second time the fencer with the lower score gets the P-black card and loses the+bout, at equal scores the one who loses a lot. No P-card at 14-14 (the minute restarts). The minute restarts after each+hit, double, annulled double and penalty hit, not after a phrase without a touch; t.124 does not apply in the extra+minute.++The lots are drawn from the seed for the first fencer (seat A in format bout, the first player in format duel), so a+duel with the seats and the first player swapped is the mirror image. The rules are the same as the step-4 model of+the screening (docs/screening/fencing/phrase/game.py, play_bout)."""+from __future__ import annotations++import hashlib+import json+import math++import numpy as np++BOUT_S, EXTRA_S, PASSIVE_S, TOUCHES = 180.0, 60.0, 60.0, 15+++def regulation_s(touches):+ """3 minutes of fencing time per 5 touches: a pool bout (5) 3 minutes, a direct-elimination bout (15) 9"""+ return BOUT_S * math.ceil(touches / 5)+++class Bout:+ def __init__(self, seed, first, second, touches=TOUCHES):+ self.seed, self.T = int(seed), int(touches)+ self.first, self.second = first, second+ self.reg_s = regulation_s(self.T)+ self.score = {first: 0, second: 0}+ self.t = 0.0 # fencing time (s)+ self.minute0 = 0.0 # t.124: the fencing time of the last hit+ self.extra = False+ self.priority = None+ self.p_calls = 0 # 1: the P-red cards given, 2: the P-black card+ self.winner = self.how = None+ self.log: list[dict] = []++ @property+ def over(self):+ return self.winner is not None++ def limit_s(self):+ return self.reg_s + (EXTRA_S if self.extra else 0.0)++ def time_left_s(self):+ return round(max(0.0, self.limit_s() - self.t), 2)++ def no_hit_s(self):+ return None if self.extra else round(self.t - self.minute0, 2)++ def _lot(self, salt):+ """the first fencer wins a lot drawn from the seed (salt 38: the priority, 124: the P-black card)"""+ return self.first if np.random.default_rng([self.seed, salt]).random() < 0.5 else self.second++ def phrase(self, res, dur, info=None):+ """one phrase: res = the side that touched alone, 'double' or 'none'; dur = its fencing time (s); info: the+ phrase's own fields for the log. Returns the log record."""+ if self.over:+ raise RuntimeError("the bout is over")+ a, b = self.first, self.second+ rec = dict(n=len(self.log) + 1, **(info or {}), res=res, s=dur, t0=round(self.t, 2))+ if self.t + dur > self.limit_s() + 1e-9: # t.44.1: the clock ends the phrase before its touch+ rec.update(cut_by_clock=True, res="none", res_phrase=res)+ res, self.t = "none", self.limit_s()+ else:+ self.t += dur+ awarded, annulled, card = [], False, None+ if res in (a, b):+ awarded = [res]+ elif res == "double":+ if self.score[a] == self.score[b] == self.T - 1:+ annulled = True # 14-14: the double is not counted+ else:+ awarded = [a, b] # t.92+ for s in awarded:+ self.score[s] += 1+ hit = bool(awarded or annulled)+ black = None+ if hit:+ self.minute0 = self.t # t.124.3.d+ elif not self.extra and self.t - self.minute0 >= PASSIVE_S - 1e-9:+ self.minute0 = self.t+ if self.score[a] == self.score[b] == self.T - 1:+ card = "none at 14-14" # t.124.3.a+ elif self.p_calls == 0:+ self.p_calls, card = 1, "P-red to both" # a penalty hit each+ self.score[a] += 1+ self.score[b] += 1+ hit = True+ else:+ self.p_calls, card = 2, "P-black"+ if self.score[a] != self.score[b]:+ black = a if self.score[a] < self.score[b] else b+ else:+ black = self._lot(124)+ sa, sb = self.score[a], self.score[b]+ starts_extra = False+ time_up = self.t >= self.limit_s() - 1e-9+ if black is not None:+ self.winner, self.how = (b if black == a else a), "passivity"+ elif self.extra and sa != sb:+ self.winner, self.how = (a if sa > sb else b), "deciding_touch"+ elif not self.extra and max(sa, sb) >= self.T and sa != sb:+ self.winner, self.how = (a if sa > sb else b), "touches"+ elif time_up and not self.extra:+ if sa != sb:+ self.winner, self.how = (a if sa > sb else b), "time"+ else:+ self.extra, self.priority = True, self._lot(38) # the extra minute, on guard (t.22.8)+ starts_extra = True+ elif time_up and self.extra:+ self.winner, self.how = self.priority, "priority"+ rec.update(awarded=awarded, annulled=annulled, card=card, black=black, t=round(self.t, 2),+ score={a: sa, b: sb}, extra_minute_starts=starts_extra)+ self.log.append(rec)+ return rec++ def forfeit(self, side, why):+ """the core's decision (a chess clock run out, a session abandoned): `side` loses"""+ if not self.over:+ self.winner, self.how = (self.second if side == self.first else self.first), why++ def state(self):+ return dict(seed=self.seed, T=self.T, first=self.first, score=self.score, t=round(self.t, 6),+ minute0=round(self.minute0, 6), extra=self.extra, priority=self.priority, p_calls=self.p_calls,+ winner=self.winner, how=self.how, log=self.log)++ def state_sha(self):+ return hashlib.sha256(json.dumps(self.state(), sort_keys=True, default=str).encode()).hexdigest()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/builtin_players.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/builtin_players.pynew file mode 100644index 0000000000..9b95f8886e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/builtin_players.py@@ -0,0 +1,245 @@+"""fencing's built-in players (fencing-7, the phrase-level sport; the same action interface as a model's program:+core/client.py plays them over HTTP).++ Reference a reader of the opponent (since 2026-10-14; screening report, section 6 "fencing-7"): ten hypotheses+ about the opponent's next intention, each scored by how well it predicted the opponent's past choices+ (decayed log-score); the best one is answered with the logit answer (20 per net touch) by the phrase+ table of `game spec`, and in 10 % of the phrases a draw from the table's equilibrium mix. Five are the+ pattern reader of step 4 (2026-10-13): the opponent's mix; after its last intention; after its last two;+ after my last one; after the last pair (tables of decayed counts). Five model how the opponent reads me:+ it predicts MY next intention from my mix, after my last one, after my last two, after its last one or+ after the last pair, and answers that prediction (logit 40, 5 % spread). The pattern reader alone is+ the weak form of the capability-sensitivity check, the equilibrium mix the strong form. It reads only+ `game spec` and the state (the phrases so far), and draws from its own stream (the seed).+ Rival the reference drawing from a stream of the seed and its seat (the fairness policy: two references with+ the same seed would draw alike).+ Random a uniform intention every phrase (generic tests).+No simulator import: this file runs in the player's container as the task's oracle (numpy only)."""+from __future__ import annotations++import math++import numpy as np++PRIOR = 1.0+RESULT = {"you": 1, "opponent": -1, "double": 2, "double, not counted at 14-14": 2, "none": 0}+++def solve_zero_sum(M, max_iter=10000):+ """(value, x, y) of the zero-sum game where the row player maximises x' M y (simplex, Bland's rule)"""+ M = np.asarray(M, float)+ m, n = M.shape+ c = 1.0 - M.min()+ T = np.zeros((m + 1, n + m + 1))+ T[:m, :n] = M + c+ T[:m, n:n + m] = np.eye(m)+ T[:m, -1] = 1.0+ T[m, :n] = -1.0+ basis = list(range(n, n + m))+ for _ in range(max_iter):+ neg = np.flatnonzero(T[m, :-1] < -1e-12)+ if len(neg) == 0:+ break+ col = int(neg[0])+ colv = T[:m, col]+ pos = colv > 1e-12+ ratios = np.full(m, np.inf)+ ratios[pos] = T[:m, -1][pos] / colv[pos]+ ties = np.flatnonzero(ratios <= ratios.min() + 1e-12)+ r = int(min(ties, key=lambda k: basis[k]))+ T[r] /= T[r, col]+ for k in range(m + 1):+ if k != r and T[k, col] != 0.0:+ T[k] -= T[k, col] * T[r]+ basis[r] = col+ else:+ raise RuntimeError("simplex did not converge")+ z = T[m, -1]+ yp = np.zeros(n)+ for r, b in enumerate(basis):+ if b < n:+ yp[b] = T[r, -1]+ xp = np.clip(T[m, n:n + m], 0.0, None)+ return float(1.0 / z - c), xp / xp.sum(), yp / yp.sum()+++def table_from_spec(spec):+ """(intention names, my expected net touches per phrase T[mine, theirs], the equilibrium mix) from `game spec`"""+ names = list(spec["intentions"])+ pt = spec["phrase_table"]+ C = np.array([[pt["counts"][f"{a}|{b}"] for b in names] for a in names], float)+ P = (C + PRIOR) / (C.sum(-1, keepdims=True) + 4 * PRIOR)+ T = P[..., 0] - P[..., 1]+ _, x, _ = solve_zero_sum(T)+ return names, T, x+++class Reader:+ """the pattern reader (screening: game.py Context, beta 20, eps_eq 0.1)"""+ CONTEXTS = ("m", "o1", "o2", "me1", "pair")++ def __init__(self, T, eq, rng, beta=20.0, eps_eq=0.1, decay=0.9, prior=0.3, score_decay=0.8):+ self.P, self.eq, self.rng, self.n = T, eq, rng, len(eq)+ self.beta, self.eps_eq, self.decay, self.prior, self.score_decay = beta, eps_eq, decay, prior, score_decay+ self.hist = []+ self.tabs = {c: {} for c in self.CONTEXTS}+ self.score = {c: 0.0 for c in self.CONTEXTS}+ self._keys, self._preds = {}, {}+ self.used = "m"++ def _key(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "o1":+ return h[-1][1]+ if c == "o2":+ return (h[-2][1], h[-1][1]) if len(h) >= 2 else None+ if c == "me1":+ return h[-1][0]+ return (h[-1][1], h[-1][0])++ def _pred(self, c, key):+ t = self.tabs[c].get(key) if key is not None else None+ if t is None:+ return None+ p = t + self.prior+ return p / p.sum()++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ best, bs = "m", self.score["m"]+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ if p is not None and self.score[c] > bs + 1e-12:+ best, bs = c, self.score[c]+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def choose(self):+ p = self.dist()+ return int(min(np.searchsorted(np.cumsum(p), self.rng.random(), side="right"), len(p) - 1))++ def observe(self, mine, other, res):+ for c, p in self._preds.items():+ self.score[c] = self.score_decay * self.score[c] + math.log(p[other])+ self.hist.append((mine, other, res))+ for c, key in self._keys.items():+ if key is None:+ continue+ t = self.tabs[c].get(key)+ if t is None:+ t = self.tabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[other] += 1.0+++class MindReader(Reader):+ """the pattern reader plus five hypotheses that the opponent predicts my next intention (from the contexts MINE of+ my own play) and answers it"""+ MINE = ("m", "me1", "me2", "o1", "pair")++ def __init__(self, *a, beta_o=40.0, eps_o=0.05, **k):+ super().__init__(*a, **k)+ self.beta_o, self.eps_o = beta_o, eps_o+ self.mtabs = {c: {} for c in self.MINE}+ for c in self.MINE:+ self.score["tom_" + c] = 0.0+ self._mkeys = {}++ def _mkey(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "me1":+ return h[-1][0]+ if c == "me2":+ return (h[-2][0], h[-1][0]) if len(h) >= 2 else None+ if c == "o1":+ return h[-1][1]+ return (h[-1][0], h[-1][1])++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ self._mkeys = {c: self._mkey(c) for c in self.MINE}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ mmarg = self.mtabs["m"].get(0)+ for c in self.MINE:+ t = self.mtabs[c].get(self._mkeys[c]) if self._mkeys[c] is not None else None+ if t is None:+ t = mmarg+ q = np.full(self.n, 1.0 / self.n) if t is None else (t + self.prior) / (t + self.prior).sum()+ v = -self.P.T @ q # the opponent's net per intention against my predicted mix+ a = np.exp(self.beta_o * (v - v.max()))+ a /= a.sum()+ self._preds["tom_" + c] = self.eps_o / self.n + (1 - self.eps_o) * a+ best = max(self._preds, key=lambda c: (self.score[c], c == "m"))+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def observe(self, mine, other, res):+ for c, key in self._mkeys.items():+ if key is None:+ continue+ t = self.mtabs[c].get(key)+ if t is None:+ t = self.mtabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[mine] += 1.0+ super().observe(mine, other, res)+++class Reference:+ def __init__(self, spec, seat, seed=0):+ self.names, T, eq = table_from_spec(spec)+ self.idx = {s: i for i, s in enumerate(self.names)}+ self.r = MindReader(T, eq, self._rng(seed, seat))+ self.seen = 0++ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12]) # by seed, not by seat: mirror runs match++ def act(self, view):+ ph = view["state"].get("phrases") or []+ for p in ph[self.seen:]:+ self.r.observe(self.idx[p["you"]], self.idx[p["opponent"]], RESULT[p["result"]])+ self.seen = len(ph)+ return {"type": "phrase", "intention": self.names[self.r.choose()]}++ def review(self, reply):+ return ("read the phrase's result", f"answer the opponent's next intention as predicted by '{self.r.used}'")+++class Rival(Reference):+ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12, sum(map(ord, str(seat)))])+++class Random:+ def __init__(self, spec, seat, seed=0):+ self.names = list(spec["intentions"])+ self.g = np.random.default_rng(int(seed) * 7919 + 17) # by seed, not by seat: mirror runs match++ def act(self, view):+ return {"type": "phrase", "intention": self.names[int(self.g.integers(len(self.names)))]}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/cameras.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/cameras.pynew file mode 100644index 0000000000..53bc7173e7--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/cameras.py@@ -0,0 +1,140 @@+"""The seats' cameras (each in its own frame) and the observation image (drawn in the seat's render worker of the v0.2+core), fencing-7.++Each seat has two fixed cameras, placed the same way in its own frame (fencing.py: the seat stands at x < 0 and faces++x): `side` beside the piste (y = -7 m) looking across it, the seat's robot on the left and the opponent on the right;+`top` above and beside the piste looking down at it. The observation image shows the last phrase (phrases.py): 2 rows+(side, top) x 2 columns (the phrase half-way, at its end) of 800 x 360 pixel tiles; before the first phrase both+fencers on guard. Every seat sees its own robot red and the opponent's blue, the points yellow+(fencing.scene_xml(view=seat): the same scene, other colours).++The frames were kept from the measured phrases (phrases/frames.npz) on the table's ends; when a fencer fenced the+phrase from the table's other end (phrases.py: the ends are drawn for each phrase), the picture is turned by half a+turn about the centre of the piste (half_turn), so that each fencer is always drawn at its own end.++A Renderer keeps the tiles it drew (by camera and the frame's joint positions) and its last image.+"""+from __future__ import annotations++import hashlib+import math+from collections import OrderedDict++import numpy as np++import fencing as F++TILE = (800, 360) # width, height (as the legacy views.py)+FOVY = 45.0+FOCAL = TILE[1] / 2 / math.tan(math.radians(FOVY / 2)) # 434.6 px+CAMS = { # own frame: lookat, distance, azimuth (deg), elevation (deg) [MuJoCo free camera] (as the legacy views.py)+ "side": ((0.0, 0.0, 0.75), 7.0, 90.0, -5.0),+ "top": ((0.0, 0.0, 0.8), 7.5, 90.0, -70.0),+}+N_FRAMES = 2 # columns of the observation image: the last phrase half-way and at its end+IMAGE_LAYOUT = ("2 rows x 2 columns of 800 x 360 tiles. Row 1: the side camera, row 2: the top camera (poses in `game "+ "spec`). Columns: the last phrase half-way (left) and at its end (right); before the first phrase "+ "both fencers on guard. Your robot is red, the opponent's blue; the points are yellow.")+++def cam_info():+ """camera pose (own frame) and intrinsics, for /spec"""+ out = []+ for name, (la, dist, az, el) in CAMS.items():+ a, e = math.radians(az), math.radians(el)+ fwd = np.array([math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)])+ pos = np.asarray(la) - dist * fwd+ right = np.cross(fwd, [0.0, 0.0, 1.0])+ right /= np.linalg.norm(right)+ up = np.cross(right, fwd)+ out.append(dict(name=name, pos=[round(float(x), 4) for x in pos], forward=[round(float(x), 5) for x in fwd],+ right=[round(float(x), 5) for x in right], up=[round(float(x), 5) for x in up],+ fovy_deg=FOVY, tile_px=list(TILE), focal_px=round(FOCAL, 2),+ principal_point_px=[TILE[0] / 2, TILE[1] / 2],+ model="pinhole: pixel u = cx + f (d.right)/(d.forward), v = cy - f (d.up)/(d.forward) for a "+ "point at offset d from pos (u to the right, v down)"))+ return out+++class Renderer:+ """Draws one seat's observation image from camera frames (qpos); owns its own MjData and GL context."""++ def __init__(self, seat: str, cache: int = 32):+ import mujoco as mj+ self.mj, self.seat = mj, seat+ self.m = m = mj.MjModel.from_xml_string(F.scene_xml(view=seat))+ self.d = mj.MjData(m)+ self.r = mj.Renderer(m, height=TILE[1], width=TILE[0])+ self.cams = []+ sg = F.SIGN[seat]+ for la, dist, az, el in CAMS.values():+ c = mj.MjvCamera()+ c.lookat[:] = (sg * la[0], sg * la[1], la[2])+ c.distance, c.azimuth, c.elevation = dist, az + (0.0 if seat == "A" else 180.0), el+ self.cams.append(c)+ self.cache: OrderedDict = OrderedDict()+ self.size = cache+ self.drawn = 0 # tiles actually rendered (the rest came from the cache)+ self.last = (None, None) # (the frames' keys, the PNG) of the last image++ def tile(self, ci, snap):+ from PIL import Image, ImageDraw+ q = np.ascontiguousarray(snap["qpos"], dtype=np.float64)+ key = (ci, snap["label"], hashlib.sha1(q.tobytes()).hexdigest())+ if key in self.cache:+ self.cache.move_to_end(key)+ return self.cache[key]+ self.d.qpos[:] = q+ self.mj.mj_kinematics(self.m, self.d)+ self.r.update_scene(self.d, camera=self.cams[ci])+ im = Image.fromarray(self.r.render())+ ImageDraw.Draw(im).text((6, 4), snap["label"], fill=(255, 255, 255))+ img = np.asarray(im)+ self.drawn += 1+ self.cache[key] = img+ while len(self.cache) > self.size:+ self.cache.popitem(last=False)+ return img++ def render(self, snaps):+ """snaps: [{label, qpos}], oldest first -> PNG bytes"""+ from core.observe import png+ keys = tuple((sn["label"], hashlib.sha1(np.ascontiguousarray(sn["qpos"], dtype=np.float64).tobytes()).hexdigest())+ for sn in snaps)+ if self.last[0] == keys:+ return self.last[1]+ rows = [np.concatenate([self.tile(ci, sn) for sn in snaps], axis=1) for ci in range(len(self.cams))]+ out = png(np.concatenate(rows, axis=0))+ self.last = (keys, out)+ return out+++_HALF = {}+++def half_turn(m, qpos):+ """the same pose turned by half a turn about the vertical through the centre of the piste: fencer A's joints become+ B's and B's A's, each floating base at (-x, -y, z) and turned by pi about z"""+ import mujoco as mj+ key = id(m)+ if key not in _HALF:+ pairs = []+ for j in range(m.njnt):+ nm = mj.mj_id2name(m, mj.mjtObj.mjOBJ_JOINT, j)+ if nm.startswith("A_"):+ jb = mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, "B_" + nm[2:])+ pairs.append((int(m.jnt_type[j]), int(m.jnt_qposadr[j]), int(m.jnt_qposadr[jb])))+ _HALF[key] = pairs+ q = np.asarray(qpos, float)+ out = q.copy()+ zpi = np.array([0.0, 0.0, 0.0, 1.0])+ for typ, a, b in _HALF[key]:+ for src, dst in ((a, b), (b, a)):+ if typ == mj.mjtJoint.mjJNT_FREE:+ out[dst:dst + 3] = (-q[src], -q[src + 1], q[src + 2])+ qq = np.zeros(4)+ mj.mju_mulQuat(qq, zpi, q[src + 3:src + 7])+ out[dst + 3:dst + 7] = qq+ else:+ out[dst] = q[src]+ return outdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/fencing.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/fencing.pynew file mode 100644index 0000000000..1b7d536a9e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/fencing.py@@ -0,0 +1,80 @@+"""The scene of robot epee fencing (fencing-7, the phrase-level sport): the piste and two Unitree G1 humanoids of the+robot library, each holding an epee on its right wrist mount, for the cameras. The phrases themselves were measured in+the fencing-6 world (this file's World and Phrase referee up to revision fencing-6, with NVIDIA's SONIC policy on the+robots: docs/screening/fencing/phrase/) and are replayed from phrases/table.json (phrases.py); the cameras draw the+joint positions kept from them (phrases/frames.npz) in this scene, which is the scene they were measured in.++World (metres): piste surface z = 0, long axis x, centre line x = 0, on-guard lines x = +-2, rear limits x = +-7,+lateral limits y = +-0.75 (t.18-t.19). Fencer A stands at x < 0 facing +x, fencer B at x > 0 facing -x (both+right-handed). Each seat sees everything in its OWN frame: x' = s x, y' = s y, z' = z with s = +1 for A and -1 for B,+so in its own frame every fencer stands at x' < 0 and faces +x'.+"""+from __future__ import annotations++import math+import sys+import xml.etree.ElementTree as ET+from pathlib import Path++HERE = Path(__file__).resolve().parent+_ROOT = HERE.parent # sim/ in a task (bodies/ next to sport/); sports/ in a checkout+sys.path.insert(0, str(_ROOT if (_ROOT / "bodies").is_dir() else _ROOT.parent))+from bodies import load_body # noqa: E402++CONTROL_DT, SUBSTEPS, PHYS_DT = 0.01, 10, 0.001+SEATS = ("A", "B")+SIGN = {"A": 1.0, "B": -1.0}+OTHER = {"A": "B", "B": "A"}+# ---- piste (t.18, t.19)+PISTE_HALF, ON_GUARD, PISTE_HALF_W = 7.0, 2.0, 0.75+# ---- the fencer+BODY, HAND, WALKER = "unitree_g1", "epee", "falcon_legs"+SETTLE_STEPS = 100 # after the referee places the robots: 1 s standing on guard (frozen fencing time)+FALL_Z, FALL_TILT = 0.45, 1.0 # pelvis height (m), pelvis tilt (rad): down+ARM_PARTS = ("shoulder", "elbow", "wrist", "hand", "mount") # arm on arm is close quarters (t.24), not corps-a-corps+# ---- the apparatus+F_TOUCH = 7.35 # N: 750 g on the point+T_TOUCH_SAMPLES = 3 # >= 2 ms: three consecutive 1 ms samples above F_TOUCH+DOUBLE_MS = 45 # lockout: a touch by the other within 45 ms is a double (40-50 ms, Appendix B)+ACCENT = {"A": (0.1, 0.35, 0.85, 1), "B": (0.85, 0.15, 0.12, 1)}+RED, BLUE, YELLOW = (0.85, 0.15, 0.12, 1), (0.1, 0.35, 0.85, 1), (1.0, 0.85, 0.1, 1)+TINT = {"own": (0.9, 0.45, 0.4, 1), "opponent": (0.35, 0.5, 0.95, 1)} # the robots' shells in a seat's images+REVISION = "fencing-7"++WORLD_XML = f"""<mujoco model="piste"><compiler angle="radian" autolimits="true"/>+<option timestep="{PHYS_DT}" integrator="implicitfast"/>+<visual><global offwidth="1280" offheight="720"/></visual>+<worldbody><light pos="0 0 4" dir="0 0 -1"/><light directional="true" pos="0 -6 4" dir="0 1 -0.6" diffuse="0.5 0.5 0.5"/>+<geom name="floor" type="plane" size="10 4 0.1" conaffinity="5" rgba="0.55 0.55 0.6 1"/>+<geom name="piste" type="box" size="{PISTE_HALF} {PISTE_HALF_W} 0.0005" pos="0 0 0.0005" contype="0" conaffinity="0"+ rgba="0.35 0.38 0.45 1"/>+<geom name="centre_line" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="0 0 0.0006" contype="0" conaffinity="0" rgba="1 1 1 1"/>+<geom name="guard_A" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{-ON_GUARD} 0 0.0006" contype="0" conaffinity="0" rgba="1 1 1 1"/>+<geom name="guard_B" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{ON_GUARD} 0 0.0006" contype="0" conaffinity="0" rgba="1 1 1 1"/>+<geom name="rear_A" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{-PISTE_HALF} 0 0.0006" contype="0" conaffinity="0" rgba="1 0.2 0.2 1"/>+<geom name="rear_B" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{PISTE_HALF} 0 0.0006" contype="0" conaffinity="0" rgba="1 0.2 0.2 1"/>+</worldbody></mujoco>"""+++def scene_xml(view: str | None = None) -> str:+ """the piste and both fencers (the library's mount: the robot, its epee, its self-collision pairs). view: the seat+ whose camera images it draws (its robot red, the opponent blue, the points yellow; the physics is the same)"""+ B = load_body(BODY)+ root = ET.fromstring(WORLD_XML)+ for s in SEATS:+ acc = ACCENT[s] if view is None else (RED if s == view else BLUE)+ B.mount(root, f"{s}_", (-SIGN[s] * ON_GUARD, 0.0, 0.0), 0.0 if s == "A" else math.pi, hand=HAND, accent=acc)+ if view is not None: # the images only: own robot light red, the opponent light blue, points yellow+ for body in root.find("worldbody").iter("body"):+ nm = body.get("name") or ""+ if nm[:2] not in ("A_", "B_") or nm.endswith("hand"):+ continue+ tint = TINT["own" if nm[0] == view else "opponent"]+ for g in body.findall("geom"):+ if g.get("contype", None) == "0" or g.get("class", "").endswith("visual") or g.get("group") in ("1", "2"):+ g.attrib.pop("material", None)+ g.set("rgba", " ".join(str(c) for c in tint))+ for g in root.iter("geom"):+ if (g.get("name") or "").endswith("hand_tip"):+ g.set("rgba", " ".join(str(c) for c in YELLOW))+ return ET.tostring(root, encoding="unicode")diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/grade.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/grade.pynew file mode 100644index 0000000000..a6c7b75098--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/grade.py@@ -0,0 +1,77 @@+"""fencing's part of reward.json (the common part is core/grading.py: success, valid_trial, technical_failure,+deterministic, seed, official_config, video_rendered, <seat>_won, <seat>_transient/unrecovered_api_errors, ...):+numbers only, from final.json (and the seat's metering summary think_usage_<seat>.json, a declared artifact of the+sim). fencing-7 (the phrase-level sport): the bout's phrases instead of fencing-6's halts; the legacy reward names+of both tasks are kept where they still mean something (README.md)."""+import json+import os+from collections import Counter+from pathlib import Path++DATA = Path(os.environ.get("RCB_DATA", "/data"))+COUNTS = ("n_act", "n_observe", "n_reviews", "refused_busy", "refused_turn", "refused_not_model")+++def _usage(seat):+ try:+ return json.loads((DATA / f"think_usage_{seat}.json").read_text())+ except (OSError, ValueError):+ return {}+++def _bout(f):+ ph = f.get("phrases") or []+ return {"bout_over": int(f.get("how") in ("touches", "passivity", "time", "deciding_touch", "priority")),+ "extra_minute": int(bool(f.get("extra_minute"))), "phrases": len(ph),+ "doubles": sum(1 for r in ph if r.get("res") == "double"),+ "doubles_not_counted": sum(1 for r in ph if r.get("annulled")),+ "no_touch_phrases": sum(1 for r in ph if r.get("res") == "none"),+ "p_cards": int(f.get("p_cards") or 0), "fencing_time_s": float(f.get("fencing_time_s") or 0.0)}+++def _intentions(f, side, prefix):+ c = Counter((r.get("intentions") or {}).get(side) for r in f.get("phrases") or [])+ names = ("lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw")+ return {f"{prefix}intention_{n}": int(c.get(n, 0)) for n in names}+++def evaluate(d):+ f = d.get("sport_fields") or {}+ seats = d["cfg"]["seats"]+ scores = d.get("scores") or {}+ stats = d.get("seats") or {}+ out = _bout(f)+ if len(seats) == 1: # the bout against the scripted fencer (side B)+ s = seats[0]+ st, u = stats.get(s, {}), _usage(s)+ errs = d.get("errors") or []+ won = d.get("match_winner") == s and out["bout_over"] == 1+ rp = d.get("replay_scores") or {}+ pf, pa = int(scores.get(s, 0)), int(scores.get("B", 0))+ out.update(+ won=int(won), level=int(f.get("level") or 0), won_on_priority=int(won and f.get("how") == "priority"),+ sim_error=int(d.get("reason") == "technical_error" or any(e.get("where") != "replay" for e in errs)),+ replay_error=int(not d.get("deterministic") or any(e.get("where") == "replay" for e in errs)),+ meter_error=int(bool((d.get("meter_error") or {}).get(s))),+ proxy_error=int(bool((d.get("proxy_error") or {}).get(s))), finalized=int(bool(d.get("finalized"))),+ touches_for=pf, touches_against=pa, points_for=pf, points_against=pa,+ replay_touches_for=int(rp.get(s, -1)), replay_touches_against=int(rp.get("B", -1)),+ clock_forfeit=int(f.get("how") == "clock"), clock_used_s=float((d.get("clock_used_s") or {}).get(s, 0.0)),+ elapsed_s=float(d.get("elapsed_s") or 0.0), metered_requests=int(u.get("requests", 0)),+ metered_output_tokens=int(u.get("output_tokens", 0)), metered_input_tokens=int(u.get("input_tokens", 0)),+ rate_limit_retries=int(u.get("rate_limit_retries", 0)),+ transient_api_errors=int((d.get("transient_api_errors") or {}).get(s, 0)),+ unrecovered_api_errors=int((d.get("unrecovered_api_errors") or {}).get(s, 0)),+ **{k: int(st.get(k, 0)) for k in COUNTS}, **_intentions(f, s, ""), **_intentions(f, "B", "opponent_"))+ return out+ out.update(won_on_priority=int(bool(d.get("valid_trial")) and f.get("how") == "priority"),+ clock_forfeit=int(f.get("how") == "clock"), abandoned=int(f.get("how") == "abandoned"),+ first_player_A=int(f.get("first_player") == "A"), elapsed_s=float(d.get("elapsed_s") or 0.0))+ for s in seats:+ st = stats.get(s, {})+ out[s + "_points"] = int(scores.get(s, 0))+ out[s + "_clock_used_s"] = float((d.get("clock_used_s") or {}).get(s, 0.0))+ for k in COUNTS:+ out[s + "_" + k] = int(st.get(k, 0))+ out.update(_intentions(f, s, s + "_"))+ return outdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/opponent.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/opponent.pynew file mode 100644index 0000000000..436ee20472--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/opponent.py@@ -0,0 +1,370 @@+"""The scripted fencer of format bout (fencing-7, the phrase-level sport): before each phrase it chooses its intention+from what it has seen of the bout (the intentions both fencers played and the results), never from the agent's choice+for this phrase. It knows the phrase table (phrases.Table.counts, the same counts as `game spec` phrase_table).++Two levels (docs/screening/fencing.md, section 6 "Phrase-level construction" and "fencing-7"): level 1 chosen in step 4+of the screening on tables measured before it was frozen and checked on a table measured after (the design and the+check: docs/screening/fencing/phrase/game.py, the same classes); level 2 redesigned on the exact table on 2026-10-14,+because the first level 2 was beaten far more often than level 1 by a reader that models how it reads, then set to the+option the maintainers chose (Chi, 2026-10-14): checked on fresh seeds against the reference, the pattern reader, the+equilibrium mix and the simple programs (docs/screening/fencing/phrase/levels/):+ level 1 a reader with a fixed library of simple models of the agent (its whole-bout mix, its recent mix, it repeats+ its last intention, it answers my last one, it copies my last one, it plays what just won, it goes round the+ menu); it believes the model with the best recent prediction score and plays the best answer to it, but+ in 70 % of the phrases it plays its habit instead (the best answer to the agent's whole-bout mix, with a+ prior of 3 per intention): a slow, readable tendency+ level 2 a reader of the agent that also models how the agent reads it (class Mind): five predictors of the agent's+ next intention (its mix; after its last one; after its last two; after my last one; after the last pair)+ and five hypotheses that the agent predicts MY next intention from my patterns and answers it; the+ hypothesis with the best recent prediction score is answered (logit 20 per net touch), and in 10 % of the+ phrases a draw from the table's equilibrium mix+Its random draws come from its own stream (the seed), so a bout replays exactly."""+from __future__ import annotations++import math++import numpy as np++PRIOR = 1.0 # the table's counts + PRIOR per outcome: the expected net touches the players use+LEVELS = {+ 1: dict(family="models", h=0.7, habit_prior=3.0,+ desc="model reader, 70% habit (whole-bout best answer, prior 3)"),+ 2: dict(family="mind", beta=20.0, eps_eq=0.1,+ desc="reads your patterns and how you read it (logit 20), 10% equilibrium"),+}+++def solve_zero_sum(M, max_iter=10000):+ """Equilibrium of the zero-sum game where the row player maximises x' M y. Simplex on the column player's LP+ (max 1'y' s.t. (M + c) y' <= 1, y' >= 0, with M + c > 0), Bland's rule; the row player's mix from the duals.+ Returns (value, x, y)."""+ M = np.asarray(M, float)+ m, n = M.shape+ c = 1.0 - M.min()+ A = M + c+ T = np.zeros((m + 1, n + m + 1))+ T[:m, :n] = A+ T[:m, n:n + m] = np.eye(m)+ T[:m, -1] = 1.0+ T[m, :n] = -1.0+ basis = list(range(n, n + m))+ for _ in range(max_iter):+ neg = np.flatnonzero(T[m, :-1] < -1e-12)+ if len(neg) == 0:+ break+ col = int(neg[0])+ colv = T[:m, col]+ pos = colv > 1e-12+ ratios = np.full(m, np.inf)+ ratios[pos] = T[:m, -1][pos] / colv[pos]+ rmin = ratios.min()+ ties = np.flatnonzero(ratios <= rmin + 1e-12)+ r = int(min(ties, key=lambda k: basis[k]))+ T[r] /= T[r, col]+ for k in range(m + 1):+ if k != r and T[k, col] != 0.0:+ T[k] -= T[k, col] * T[r]+ basis[r] = col+ else:+ raise RuntimeError("simplex did not converge")+ z = T[m, -1]+ yp = np.zeros(n)+ for r, b in enumerate(basis):+ if b < n:+ yp[b] = T[r, -1]+ xp = np.clip(T[m, n:n + m], 0.0, None)+ x, y = xp / xp.sum(), yp / yp.sum()+ return float(1.0 / z - c), x, y+++class Knowledge:+ """the table as the players use it: P[i, j] = (counts + PRIOR) / (total + 4 PRIOR) over [me, other, double, none];+ T[i, j] = P(I touch alone) - P(the other touches alone): my expected net touches per phrase; x, y: its equilibrium"""++ def __init__(self, counts, prior=PRIOR):+ C = np.asarray(counts, float)+ self.n = C.shape[0]+ self.P = (C + prior) / (C.sum(-1, keepdims=True) + 4 * prior)+ self.T = self.P[..., 0] - self.P[..., 1]+ self.v, self.x, self.y = solve_zero_sum(self.T)+++def sample(p, rng):+ return int(min(np.searchsorted(np.cumsum(p), rng.random(), side="right"), len(p) - 1))+++class Policy:+ """one fencer's decision program from its own seat: P[mine, other] = its expected net touches per phrase.+ observe(mine, other, res): res 1 = I scored alone, -1 = the other alone, 2 = double (also annulled), 0 = nothing"""++ def __init__(self, name, desc=""):+ self.name, self.desc = name, desc++ def reset(self, kn, side, rng):+ self.side, self.rng = side, rng+ self.P = kn.T if side == 0 else -kn.T.T+ self.eq = kn.x if side == 0 else kn.y+ self.n = kn.n+ self.hist = []+ self.t = 0++ def observe(self, mine, other, res):+ self.hist.append((mine, other, res))+ self.t += 1+++class Context(Policy):+ """pattern prediction: five predictors of the other's next intention (its overall mix; after its last one; after+ its last two; after my last one; after the last pair), each a table of decayed counts; the predictor with the best+ recent log-score is used; then the best answer to the prediction (logit beta), and with probability eps_eq a draw+ from the equilibrium mix instead (so it cannot be read in turn)"""+ CONTEXTS = ("m", "o1", "o2", "me1", "pair")++ def __init__(self, name, desc="", beta=20.0, eps_eq=0.25, decay=0.9, prior=0.3, score_decay=0.8):+ super().__init__(name, desc)+ self.beta, self.eps_eq, self.decay, self.prior, self.score_decay = beta, eps_eq, decay, prior, score_decay++ def reset(self, kn, side, rng):+ super().reset(kn, side, rng)+ self.tabs = {c: {} for c in self.CONTEXTS}+ self.score = {c: 0.0 for c in self.CONTEXTS}+ self._keys, self._preds = {}, {}++ def _key(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "o1":+ return h[-1][1]+ if c == "o2":+ return (h[-2][1], h[-1][1]) if len(h) >= 2 else None+ if c == "me1":+ return h[-1][0]+ return (h[-1][1], h[-1][0])++ def _pred(self, c, key):+ t = self.tabs[c].get(key) if key is not None else None+ if t is None:+ return None+ p = t + self.prior+ return p / p.sum()++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ best, bs = "m", self.score["m"]+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ if p is not None and self.score[c] > bs + 1e-12:+ best, bs = c, self.score[c]+ v = self.P @ self._preds[best]+ if self.beta is None:+ core = (v >= v.max() - 1e-9).astype(float)+ else:+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def choose(self, score):+ return sample(self.dist(), self.rng)++ def observe(self, mine, other, res):+ for c, p in self._preds.items():+ self.score[c] = self.score_decay * self.score[c] + math.log(p[other])+ super().observe(mine, other, res)+ for c, key in self._keys.items():+ if key is None:+ continue+ t = self.tabs[c].get(key)+ if t is None:+ t = self.tabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[other] += 1.0+++class Mind(Context):+ """pattern prediction (Context) plus five hypotheses that the other reads ME: it predicts my next intention from my+ patterns (my mix; after my last one; after my last two; after its last one; after the last pair) and answers that+ prediction (logit beta_o, eps_o spread); every hypothesis is scored by how well it predicted the other's choices,+ the best one is answered (logit beta), and with probability eps_eq a draw from the equilibrium mix instead. The+ same reader as the reference (builtin_players.MindReader), from this fencer's seat."""+ MINE = ("m", "me1", "me2", "o1", "pair")++ def __init__(self, name, desc="", beta=20.0, eps_eq=0.1, beta_o=40.0, eps_o=0.05, **k):+ super().__init__(name, desc, beta=beta, eps_eq=eps_eq, **k)+ self.beta_o, self.eps_o = beta_o, eps_o++ def reset(self, kn, side, rng):+ super().reset(kn, side, rng)+ self.mtabs = {c: {} for c in self.MINE}+ for c in self.MINE:+ self.score["tom_" + c] = 0.0+ self._mkeys = {}++ def _mkey(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "me1":+ return h[-1][0]+ if c == "me2":+ return (h[-2][0], h[-1][0]) if len(h) >= 2 else None+ if c == "o1":+ return h[-1][1]+ return (h[-1][0], h[-1][1])++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ self._mkeys = {c: self._mkey(c) for c in self.MINE}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ mmarg = self.mtabs["m"].get(0)+ for c in self.MINE:+ t = self.mtabs[c].get(self._mkeys[c]) if self._mkeys[c] is not None else None+ if t is None:+ t = mmarg+ q = np.full(self.n, 1.0 / self.n) if t is None else (t + self.prior) / (t + self.prior).sum()+ v = -self.P.T @ q # the other's net per intention against my predicted mix+ a = np.exp(self.beta_o * (v - v.max()))+ a /= a.sum()+ self._preds["tom_" + c] = self.eps_o / self.n + (1 - self.eps_o) * a+ best = max(self._preds, key=lambda c: (self.score[c], c == "m"))+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def observe(self, mine, other, res):+ for c, key in self._mkeys.items():+ if key is None:+ continue+ t = self.mtabs[c].get(key)+ if t is None:+ t = self.mtabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[mine] += 1.0+ super().observe(mine, other, res)+++class Models(Policy):+ """a reader with a fixed library of simple models of the other fencer, each predicting its next intention:+ marg its whole-bout mix recent its recency-weighted mix (0.7)+ repeat it repeats its last intention counter it answers my last intention with the table's best answer+ copy it copies my last intention winner it plays what won the last phrase (whoever played it)+ seq it continues its last step through the menu (a cycle)+ each model's prediction is 80 % its guess, 20 % spread (marg and recent as they are); the model with the best+ recent log-score (decay `score_decay`) is believed; the answer is the best (or logit beta) against it.+ habit: with probability h it plays its habit instead, the best answer to the other's whole-bout mix with a strong+ prior (`habit_prior` per intention): a slow, readable tendency. eps_eq: a draw from the equilibrium mix."""+ ALL = ("marg", "recent", "repeat", "counter", "copy", "winner", "seq")++ def __init__(self, name, desc="", models=ALL, h=0.0, habit_prior=3.0, eps_eq=0.0, beta=None, score_decay=0.7):+ super().__init__(name, desc)+ self.models, self.h, self.habit_prior, self.eps_eq, self.beta = tuple(models), h, habit_prior, eps_eq, beta+ self.score_decay = score_decay++ def reset(self, kn, side, rng):+ super().reset(kn, side, rng)+ self.wall = np.zeros(self.n)+ self.wrec = np.zeros(self.n)+ self.score = {m: 0.0 for m in self.models}+ self._preds = {}+ Q = -self.P.T # Q[a, k]: the other's net when it plays a against my k+ self.other_brs = [np.flatnonzero(Q[:, k] >= Q[:, k].max() - 1e-9) for k in range(self.n)]++ def _point(self, k):+ """80 % on k (or spread over the tied set k), 20 % spread"""+ p = np.full(self.n, 0.2 / self.n)+ if np.ndim(k):+ p[k] += 0.8 / len(k)+ else:+ p[k] += 0.8+ return p++ def _predict(self):+ h, n = self.hist, self.n+ out = {}+ for m in self.models:+ if m == "marg":+ p = self.wall + 0.5+ out[m] = p / p.sum()+ elif m == "recent":+ p = self.wrec + 0.3+ out[m] = p / p.sum()+ elif not h:+ continue+ elif m == "repeat":+ out[m] = self._point(h[-1][1])+ elif m == "counter":+ out[m] = self._point(self.other_brs[h[-1][0]])+ elif m == "copy":+ out[m] = self._point(h[-1][0])+ elif m == "winner":+ mine, other, res = h[-1]+ out[m] = self._point(mine if res == -1 else other)+ elif m == "seq" and len(h) >= 2:+ out[m] = self._point((2 * h[-1][1] - h[-2][1]) % n)+ return out++ def dist(self):+ self._preds = self._predict()+ best = max(self._preds, key=lambda m: (self.score[m], m == "marg"))+ v = self.P @ self._preds[best]+ if self.beta is None:+ core = (v >= v.max() - 1e-9).astype(float)+ else:+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ hp = self.wall + self.habit_prior+ hv = self.P @ (hp / hp.sum())+ habit = (hv >= hv.max() - 1e-9).astype(float)+ habit /= habit.sum()+ return self.h * habit + self.eps_eq * self.eq + (1.0 - self.h - self.eps_eq) * core++ def choose(self, score):+ return sample(self.dist(), self.rng)++ def observe(self, mine, other, res):+ for m, p in self._preds.items():+ self.score[m] = self.score_decay * self.score[m] + math.log(p[other])+ super().observe(mine, other, res)+ self.wall[other] += 1.0+ self.wrec *= 0.7+ self.wrec[other] += 1.0+++def make_level(level):+ s = dict(LEVELS[level])+ fam, desc = s.pop("family"), s.pop("desc")+ return {"models": Models, "ctx": Context, "mind": Mind}[fam](f"level {level}", desc, **s)+++class Opponent:+ """the scripted fencer at a level, the second fencer (side 1) of the bout"""++ def __init__(self, level, seed, kn):+ self.level = int(level)+ self.p = make_level(self.level)+ self.p.reset(kn, 1, np.random.default_rng([int(seed), 13]))++ def choose(self, score):+ return self.p.choose(score)++ def observe(self, mine, other, res):+ self.p.observe(mine, other, res)++ def state(self):+ return dict(level=self.level, hist=self.p.hist, rng=self.p.rng.bit_generator.state)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases.pynew file mode 100644index 0000000000..c54080437a--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases.py@@ -0,0 +1,120 @@+"""The world of the phrase-level sport (fencing-7): every phrase of the bout is one of the phrases measured in the+fencing-6 world, looked up in a table.++A phrase starts with both fencers on guard GAP_M apart (pelvis to pelvis). Each fencer has chosen one intention+(INTENTIONS), a fixed skill on the robot: the Unitree G1 of the robot library with its epee, its legs, waist and+left arm driven by NVIDIA's SONIC whole-body policy tracking our own fencing motions (en garde, steps, lunge), its+sword arm by the point skill. Each fencer starts its intention after a delay of 0, 10, ... 50 ms (JITTER_STEPS control+steps, drawn for each phrase from the seed); the phrase ends at the first touch (the electric apparatus and the+45 ms lockout of fencing-6's phrase referee) or after MAX_S without one. In that world a phrase's outcome is a function+of the two intentions and the two delays alone (every phrase measured more than once gave the same result at the same+step), so the 9 x 9 x 6 x 6 = 2916 phrases were each played once (docs/screening/fencing/phrase/: the generator, the+determinism check) and the bout replays them from phrases/table.json.++The two ends of the piste are not exactly alike in the simulation (the same phrase fenced from the other end ends+differently in about one case in seven), so each phrase also draws the end each fencer fences from: the first fencer+(seat A in format bout, the first player in format duel) is on the table's end A with probability 1/2. Both fencers+therefore meet the same chances, and a fencer's chances against an intention are the table's counts over both ends+(Table.counts: out of 2 x 36 phrases).++phrases/frames.npz keeps two frames of every phrase (the joint positions half-way and at the end) for the cameras."""+from __future__ import annotations++import hashlib+import json+import os++import numpy as np++HERE = os.path.dirname(os.path.abspath(__file__))+DATA = os.path.join(HERE, "phrases")+INTENTIONS = ("lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw")+OUTCOMES = ("A", "B", "AB", "none") # the table's ends: a touch for A alone, for B alone, a double, none+STEP_S = 0.01 # the control step: a delay step, the halt step k+++class Table:+ """phrases/table.json: {"intentions", "gap_m", "jitter_steps", "max_s", "source", "phrases": [[a, b, dA, dB, res,+ k, why], ...]} (k: the control step of the halt, null for a phrase cut at max_s)"""++ def __init__(self, path=DATA):+ with open(os.path.join(path, "table.json"), "rb") as f:+ raw = f.read()+ self.sha = hashlib.sha256(raw).hexdigest()+ d = json.loads(raw)+ self.names = tuple(d["intentions"])+ if self.names != INTENTIONS:+ raise ValueError(f"table intentions {self.names} != {INTENTIONS}")+ self.idx = {s: i for i, s in enumerate(self.names)}+ self.J = int(d["jitter_steps"])+ self.gap_m, self.max_s = float(d["gap_m"]), float(d["max_s"])+ self.meta = {k: d[k] for k in ("gap_m", "jitter_steps", "max_s", "source") if k in d}+ self.row: dict = {}+ for n, (a, b, dA, dB, res, k, why) in enumerate(d["phrases"]):+ self.row[(a, b, int(dA), int(dB))] = (n, res, k, why)+ want = len(self.names) ** 2 * self.J ** 2+ if len(self.row) != want or any(r[1] not in OUTCOMES for r in self.row.values()):+ raise ValueError(f"table has {len(self.row)} phrases, needs {want} with outcomes in {OUTCOMES}")+ self.path = path+ self._frames = None++ def seconds(self, k):+ return self.max_s if k is None else (k + 1) * STEP_S++ def get(self, a, b, dA, dB):+ """the phrase with A's intention a after dA steps and B's b after dB: {res, k, why, s, row}"""+ n, res, k, why = self.row[(a, b, dA, dB)]+ return dict(res=res, k=k, why=why, s=round(self.seconds(k), 2), row=n)++ def counts(self):+ """C[i, j] = [touches for me alone, for the other alone, doubles, none] when I play i and the other j, over+ both ends and all delays (2 J^2 phrases)"""+ n = len(self.names)+ C = np.zeros((n, n, 4))+ for (a, b, _, _), (_, res, _, _) in self.row.items():+ i, j, o = self.idx[a], self.idx[b], OUTCOMES.index(res)+ C[i, j, o] += 1 # I am on end A+ C[j, i, (1, 0, 2, 3)[o]] += 1 # I am on end B: A's touch is the other's+ return C++ def frames(self, row):+ """(steps [2], qpos [2, nq]) of the phrase's two frames (half-way, the end), on the table's ends"""+ if self._frames is None:+ z = np.load(os.path.join(self.path, "frames.npz"))+ self._frames = (z["steps"], z["qpos"], z["guard"])+ return self._frames[0][row], self._frames[1][row]++ def guard_qpos(self):+ """both fencers on guard GAP_M apart, before the first phrase"""+ self.frames(0)+ return self._frames[2]+++_TABLE: dict = {}+++def table(path=DATA) -> Table:+ if path not in _TABLE:+ _TABLE[path] = Table(path)+ return _TABLE[path]+++def draw(seed, n, J):+ """phrase n's chance: (the first fencer's delay, the second's, the first on the table's end A)"""+ g = np.random.default_rng([int(seed), 21, int(n)])+ d = g.integers(0, J, 2)+ return int(d[0]), int(d[1]), bool(g.random() < 0.5)+++def play(t: Table, i_first, i_second, seed, n):+ """phrase n with the first fencer's intention i_first and the second's i_second (names): the table's phrase with+ this phrase's delays and ends; res from the first fencer's view: 'first' | 'second' | 'double' | 'none'"""+ d1, d2, first_on_a = draw(seed, n, t.J)+ if first_on_a:+ p = t.get(i_first, i_second, d1, d2)+ res = {"A": "first", "B": "second", "AB": "double", "none": "none"}[p["res"]]+ else:+ p = t.get(i_second, i_first, d2, d1)+ res = {"A": "second", "B": "first", "AB": "double", "none": "none"}[p["res"]]+ return dict(res=res, k=p["k"], why=p["why"], s=p["s"], row=p["row"], first_delay_ms=10 * d1,+ second_delay_ms=10 * d2, first_end="A" if first_on_a else "B")diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases/frames.npz b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases/frames.npznew file mode 100644index 0000000000..19eee9e93cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases/frames.npz differdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases/table.json b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases/table.jsonnew file mode 100644index 0000000000..ec54ddb263--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/phrases/table.json@@ -0,0 +1,2918 @@+{"source": "exact.py: every phrase played once in the fencing-6 world (frozen copy of fencing-screen 6711a4f4), SONIC skills (tactic.py), gap 1.95 m", "gap_m": 1.95, "jitter_steps": 6, "max_s": 3.0, "intentions": ["lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw"], "phrases": [+["lunge", "lunge", 0, 0, "none", null, "time"],+["lunge", "lunge", 0, 1, "A", 168, "touch"],+["lunge", "lunge", 0, 2, "AB", 181, "touch"],+["lunge", "lunge", 0, 3, "A", 182, "touch"],+["lunge", "lunge", 0, 4, "none", null, "time"],+["lunge", "lunge", 0, 5, "B", 185, "touch"],+["lunge", "lunge", 1, 0, "none", null, "time"],+["lunge", "lunge", 1, 1, "none", null, "time"],+["lunge", "lunge", 1, 2, "none", null, "time"],+["lunge", "lunge", 1, 3, "none", null, "time"],+["lunge", "lunge", 1, 4, "none", null, "time"],+["lunge", "lunge", 1, 5, "none", null, "time"],+["lunge", "lunge", 2, 0, "none", null, "time"],+["lunge", "lunge", 2, 1, "none", null, "time"],+["lunge", "lunge", 2, 2, "B", 246, "touch"],+["lunge", "lunge", 2, 3, "none", null, "time"],+["lunge", "lunge", 2, 4, "B", 218, "touch"],+["lunge", "lunge", 2, 5, "A", 171, "touch"],+["lunge", "lunge", 3, 0, "A", 47, "touch"],+["lunge", "lunge", 3, 1, "B", 166, "touch"],+["lunge", "lunge", 3, 2, "A", 186, "touch"],+["lunge", "lunge", 3, 3, "A", 170, "touch"],+["lunge", "lunge", 3, 4, "none", null, "time"],+["lunge", "lunge", 3, 5, "none", null, "time"],+["lunge", "lunge", 4, 0, "none", null, "time"],+["lunge", "lunge", 4, 1, "none", null, "time"],+["lunge", "lunge", 4, 2, "B", 239, "touch"],+["lunge", "lunge", 4, 3, "none", null, "time"],+["lunge", "lunge", 4, 4, "none", null, "time"],+["lunge", "lunge", 4, 5, "none", null, "time"],+["lunge", "lunge", 5, 0, "A", 47, "touch"],+["lunge", "lunge", 5, 1, "none", null, "time"],+["lunge", "lunge", 5, 2, "B", 170, "touch"],+["lunge", "lunge", 5, 3, "none", null, "time"],+["lunge", "lunge", 5, 4, "none", null, "time"],+["lunge", "lunge", 5, 5, "A", 169, "touch"],+["lunge", "low", 0, 0, "AB", 39, "touch"],+["lunge", "low", 0, 1, "AB", 39, "touch"],+["lunge", "low", 0, 2, "AB", 40, "touch"],+["lunge", "low", 0, 3, "AB", 41, "touch"],+["lunge", "low", 0, 4, "AB", 42, "touch"],+["lunge", "low", 0, 5, "AB", 42, "touch"],+["lunge", "low", 1, 0, "AB", 39, "touch"],+["lunge", "low", 1, 1, "AB", 40, "touch"],+["lunge", "low", 1, 2, "AB", 41, "touch"],+["lunge", "low", 1, 3, "AB", 41, "touch"],+["lunge", "low", 1, 4, "AB", 42, "touch"],+["lunge", "low", 1, 5, "AB", 43, "touch"],+["lunge", "low", 2, 0, "AB", 39, "touch"],+["lunge", "low", 2, 1, "AB", 40, "touch"],+["lunge", "low", 2, 2, "AB", 41, "touch"],+["lunge", "low", 2, 3, "AB", 41, "touch"],+["lunge", "low", 2, 4, "AB", 42, "touch"],+["lunge", "low", 2, 5, "AB", 43, "touch"],+["lunge", "low", 3, 0, "AB", 41, "touch"],+["lunge", "low", 3, 1, "AB", 42, "touch"],+["lunge", "low", 3, 2, "AB", 41, "touch"],+["lunge", "low", 3, 3, "AB", 42, "touch"],+["lunge", "low", 3, 4, "AB", 43, "touch"],+["lunge", "low", 3, 5, "AB", 43, "touch"],+["lunge", "low", 4, 0, "AB", 40, "touch"],+["lunge", "low", 4, 1, "AB", 40, "touch"],+["lunge", "low", 4, 2, "AB", 41, "touch"],+["lunge", "low", 4, 3, "AB", 42, "touch"],+["lunge", "low", 4, 4, "AB", 43, "touch"],+["lunge", "low", 4, 5, "AB", 43, "touch"],+["lunge", "low", 5, 0, "A", 45, "touch"],+["lunge", "low", 5, 1, "AB", 42, "touch"],+["lunge", "low", 5, 2, "AB", 42, "touch"],+["lunge", "low", 5, 3, "AB", 43, "touch"],+["lunge", "low", 5, 4, "AB", 44, "touch"],+["lunge", "low", 5, 5, "AB", 44, "touch"],+["lunge", "line", 0, 0, "B", 31, "touch"],+["lunge", "line", 0, 1, "A", 154, "touch"],+["lunge", "line", 0, 2, "A", 136, "touch"],+["lunge", "line", 0, 3, "none", null, "time"],+["lunge", "line", 0, 4, "A", 31, "touch"],+["lunge", "line", 0, 5, "A", 31, "touch"],+["lunge", "line", 1, 0, "A", 71, "touch"],+["lunge", "line", 1, 1, "A", 69, "touch"],+["lunge", "line", 1, 2, "B", 33, "touch"],+["lunge", "line", 1, 3, "A", 69, "touch"],+["lunge", "line", 1, 4, "A", 70, "touch"],+["lunge", "line", 1, 5, "A", 70, "touch"],+["lunge", "line", 2, 0, "B", 32, "touch"],+["lunge", "line", 2, 1, "A", 77, "touch"],+["lunge", "line", 2, 2, "B", 33, "touch"],+["lunge", "line", 2, 3, "A", 135, "touch"],+["lunge", "line", 2, 4, "A", 136, "touch"],+["lunge", "line", 2, 5, "A", 138, "touch"],+["lunge", "line", 3, 0, "A", 73, "touch"],+["lunge", "line", 3, 1, "A", 72, "touch"],+["lunge", "line", 3, 2, "A", 73, "touch"],+["lunge", "line", 3, 3, "A", 72, "touch"],+["lunge", "line", 3, 4, "A", 72, "touch"],+["lunge", "line", 3, 5, "A", 72, "touch"],+["lunge", "line", 4, 0, "A", 82, "touch"],+["lunge", "line", 4, 1, "none", null, "time"],+["lunge", "line", 4, 2, "B", 34, "touch"],+["lunge", "line", 4, 3, "B", 34, "touch"],+["lunge", "line", 4, 4, "B", 35, "touch"],+["lunge", "line", 4, 5, "A", 140, "touch"],+["lunge", "line", 5, 0, "A", 75, "touch"],+["lunge", "line", 5, 1, "A", 74, "touch"],+["lunge", "line", 5, 2, "A", 75, "touch"],+["lunge", "line", 5, 3, "A", 74, "touch"],+["lunge", "line", 5, 4, "A", 74, "touch"],+["lunge", "line", 5, 5, "A", 74, "touch"],+["lunge", "rline", 0, 0, "B", 124, "touch"],+["lunge", "rline", 0, 1, "B", 124, "touch"],+["lunge", "rline", 0, 2, "B", 124, "touch"],+["lunge", "rline", 0, 3, "B", 124, "touch"],+["lunge", "rline", 0, 4, "B", 124, "touch"],+["lunge", "rline", 0, 5, "B", 124, "touch"],+["lunge", "rline", 1, 0, "none", null, "time"],+["lunge", "rline", 1, 1, "none", null, "time"],+["lunge", "rline", 1, 2, "none", null, "time"],+["lunge", "rline", 1, 3, "none", null, "time"],+["lunge", "rline", 1, 4, "none", null, "time"],+["lunge", "rline", 1, 5, "none", null, "time"],+["lunge", "rline", 2, 0, "none", null, "time"],+["lunge", "rline", 2, 1, "none", null, "time"],+["lunge", "rline", 2, 2, "none", null, "time"],+["lunge", "rline", 2, 3, "none", null, "time"],+["lunge", "rline", 2, 4, "none", null, "time"],+["lunge", "rline", 2, 5, "none", null, "time"],+["lunge", "rline", 3, 0, "A", 80, "touch"],+["lunge", "rline", 3, 1, "A", 80, "touch"],+["lunge", "rline", 3, 2, "A", 80, "touch"],+["lunge", "rline", 3, 3, "A", 80, "touch"],+["lunge", "rline", 3, 4, "A", 80, "touch"],+["lunge", "rline", 3, 5, "A", 80, "touch"],+["lunge", "rline", 4, 0, "B", 98, "touch"],+["lunge", "rline", 4, 1, "B", 98, "touch"],+["lunge", "rline", 4, 2, "B", 98, "touch"],+["lunge", "rline", 4, 3, "B", 98, "touch"],+["lunge", "rline", 4, 4, "B", 98, "touch"],+["lunge", "rline", 4, 5, "B", 98, "touch"],+["lunge", "rline", 5, 0, "A", 81, "touch"],+["lunge", "rline", 5, 1, "A", 81, "touch"],+["lunge", "rline", 5, 2, "A", 81, "touch"],+["lunge", "rline", 5, 3, "A", 81, "touch"],+["lunge", "rline", 5, 4, "A", 81, "touch"],+["lunge", "rline", 5, 5, "A", 81, "touch"],+["lunge", "stop", 0, 0, "A", 75, "touch"],+["lunge", "stop", 0, 1, "A", 75, "touch"],+["lunge", "stop", 0, 2, "A", 75, "touch"],+["lunge", "stop", 0, 3, "A", 75, "touch"],+["lunge", "stop", 0, 4, "A", 75, "touch"],+["lunge", "stop", 0, 5, "A", 75, "touch"],+["lunge", "stop", 1, 0, "A", 71, "touch"],+["lunge", "stop", 1, 1, "A", 71, "touch"],+["lunge", "stop", 1, 2, "A", 71, "touch"],+["lunge", "stop", 1, 3, "A", 71, "touch"],+["lunge", "stop", 1, 4, "A", 71, "touch"],+["lunge", "stop", 1, 5, "A", 71, "touch"],+["lunge", "stop", 2, 0, "A", 76, "touch"],+["lunge", "stop", 2, 1, "A", 76, "touch"],+["lunge", "stop", 2, 2, "A", 76, "touch"],+["lunge", "stop", 2, 3, "A", 76, "touch"],+["lunge", "stop", 2, 4, "A", 76, "touch"],+["lunge", "stop", 2, 5, "A", 76, "touch"],+["lunge", "stop", 3, 0, "A", 73, "touch"],+["lunge", "stop", 3, 1, "A", 73, "touch"],+["lunge", "stop", 3, 2, "A", 73, "touch"],+["lunge", "stop", 3, 3, "A", 73, "touch"],+["lunge", "stop", 3, 4, "A", 73, "touch"],+["lunge", "stop", 3, 5, "A", 73, "touch"],+["lunge", "stop", 4, 0, "A", 79, "touch"],+["lunge", "stop", 4, 1, "A", 79, "touch"],+["lunge", "stop", 4, 2, "A", 79, "touch"],+["lunge", "stop", 4, 3, "A", 79, "touch"],+["lunge", "stop", 4, 4, "A", 79, "touch"],+["lunge", "stop", 4, 5, "A", 79, "touch"],+["lunge", "stop", 5, 0, "A", 75, "touch"],+["lunge", "stop", 5, 1, "A", 75, "touch"],+["lunge", "stop", 5, 2, "A", 75, "touch"],+["lunge", "stop", 5, 3, "A", 75, "touch"],+["lunge", "stop", 5, 4, "A", 75, "touch"],+["lunge", "stop", 5, 5, "A", 75, "touch"],+["lunge", "counter", 0, 0, "B", 55, "touch"],+["lunge", "counter", 0, 1, "B", 55, "touch"],+["lunge", "counter", 0, 2, "B", 55, "touch"],+["lunge", "counter", 0, 3, "B", 55, "touch"],+["lunge", "counter", 0, 4, "B", 55, "touch"],+["lunge", "counter", 0, 5, "B", 55, "touch"],+["lunge", "counter", 1, 0, "B", 54, "touch"],+["lunge", "counter", 1, 1, "B", 54, "touch"],+["lunge", "counter", 1, 2, "B", 54, "touch"],+["lunge", "counter", 1, 3, "B", 54, "touch"],+["lunge", "counter", 1, 4, "B", 54, "touch"],+["lunge", "counter", 1, 5, "B", 54, "touch"],+["lunge", "counter", 2, 0, "B", 57, "touch"],+["lunge", "counter", 2, 1, "B", 57, "touch"],+["lunge", "counter", 2, 2, "B", 57, "touch"],+["lunge", "counter", 2, 3, "B", 57, "touch"],+["lunge", "counter", 2, 4, "B", 57, "touch"],+["lunge", "counter", 2, 5, "B", 57, "touch"],+["lunge", "counter", 3, 0, "B", 55, "touch"],+["lunge", "counter", 3, 1, "B", 55, "touch"],+["lunge", "counter", 3, 2, "B", 55, "touch"],+["lunge", "counter", 3, 3, "B", 55, "touch"],+["lunge", "counter", 3, 4, "B", 55, "touch"],+["lunge", "counter", 3, 5, "B", 55, "touch"],+["lunge", "counter", 4, 0, "B", 57, "touch"],+["lunge", "counter", 4, 1, "B", 57, "touch"],+["lunge", "counter", 4, 2, "B", 57, "touch"],+["lunge", "counter", 4, 3, "B", 57, "touch"],+["lunge", "counter", 4, 4, "B", 57, "touch"],+["lunge", "counter", 4, 5, "B", 57, "touch"],+["lunge", "counter", 5, 0, "B", 58, "touch"],+["lunge", "counter", 5, 1, "B", 58, "touch"],+["lunge", "counter", 5, 2, "B", 58, "touch"],+["lunge", "counter", 5, 3, "B", 58, "touch"],+["lunge", "counter", 5, 4, "B", 58, "touch"],+["lunge", "counter", 5, 5, "B", 58, "touch"],+["lunge", "delay", 0, 0, "B", 69, "touch"],+["lunge", "delay", 0, 1, "B", 70, "touch"],+["lunge", "delay", 0, 2, "B", 71, "touch"],+["lunge", "delay", 0, 3, "AB", 67, "touch"],+["lunge", "delay", 0, 4, "AB", 68, "touch"],+["lunge", "delay", 0, 5, "AB", 69, "touch"],+["lunge", "delay", 1, 0, "AB", 64, "touch"],+["lunge", "delay", 1, 1, "AB", 65, "touch"],+["lunge", "delay", 1, 2, "AB", 66, "touch"],+["lunge", "delay", 1, 3, "AB", 68, "touch"],+["lunge", "delay", 1, 4, "AB", 68, "touch"],+["lunge", "delay", 1, 5, "A", 69, "touch"],+["lunge", "delay", 2, 0, "B", 68, "touch"],+["lunge", "delay", 2, 1, "B", 70, "touch"],+["lunge", "delay", 2, 2, "B", 71, "touch"],+["lunge", "delay", 2, 3, "B", 72, "touch"],+["lunge", "delay", 2, 4, "B", 73, "touch"],+["lunge", "delay", 2, 5, "AB", 69, "touch"],+["lunge", "delay", 3, 0, "B", 69, "touch"],+["lunge", "delay", 3, 1, "B", 70, "touch"],+["lunge", "delay", 3, 2, "B", 71, "touch"],+["lunge", "delay", 3, 3, "AB", 67, "touch"],+["lunge", "delay", 3, 4, "AB", 68, "touch"],+["lunge", "delay", 3, 5, "AB", 69, "touch"],+["lunge", "delay", 4, 0, "B", 69, "touch"],+["lunge", "delay", 4, 1, "B", 70, "touch"],+["lunge", "delay", 4, 2, "B", 71, "touch"],+["lunge", "delay", 4, 3, "B", 72, "touch"],+["lunge", "delay", 4, 4, "B", 73, "touch"],+["lunge", "delay", 4, 5, "B", 74, "touch"],+["lunge", "delay", 5, 0, "B", 69, "touch"],+["lunge", "delay", 5, 1, "B", 70, "touch"],+["lunge", "delay", 5, 2, "B", 71, "touch"],+["lunge", "delay", 5, 3, "B", 72, "touch"],+["lunge", "delay", 5, 4, "B", 72, "touch"],+["lunge", "delay", 5, 5, "AB", 70, "touch"],+["lunge", "retreat", 0, 0, "none", null, "time"],+["lunge", "retreat", 0, 1, "A", 73, "touch"],+["lunge", "retreat", 0, 2, "A", 73, "touch"],+["lunge", "retreat", 0, 3, "none", null, "time"],+["lunge", "retreat", 0, 4, "none", null, "time"],+["lunge", "retreat", 0, 5, "A", 72, "touch"],+["lunge", "retreat", 1, 0, "A", 69, "touch"],+["lunge", "retreat", 1, 1, "A", 69, "touch"],+["lunge", "retreat", 1, 2, "A", 69, "touch"],+["lunge", "retreat", 1, 3, "A", 69, "touch"],+["lunge", "retreat", 1, 4, "A", 69, "touch"],+["lunge", "retreat", 1, 5, "A", 68, "touch"],+["lunge", "retreat", 2, 0, "none", null, "time"],+["lunge", "retreat", 2, 1, "A", 75, "touch"],+["lunge", "retreat", 2, 2, "A", 75, "touch"],+["lunge", "retreat", 2, 3, "none", null, "time"],+["lunge", "retreat", 2, 4, "none", null, "time"],+["lunge", "retreat", 2, 5, "none", null, "time"],+["lunge", "retreat", 3, 0, "A", 72, "touch"],+["lunge", "retreat", 3, 1, "A", 71, "touch"],+["lunge", "retreat", 3, 2, "A", 71, "touch"],+["lunge", "retreat", 3, 3, "A", 71, "touch"],+["lunge", "retreat", 3, 4, "A", 71, "touch"],+["lunge", "retreat", 3, 5, "A", 70, "touch"],+["lunge", "retreat", 4, 0, "none", null, "time"],+["lunge", "retreat", 4, 1, "none", null, "time"],+["lunge", "retreat", 4, 2, "none", null, "time"],+["lunge", "retreat", 4, 3, "none", null, "time"],+["lunge", "retreat", 4, 4, "none", null, "time"],+["lunge", "retreat", 4, 5, "none", null, "time"],+["lunge", "retreat", 5, 0, "A", 74, "touch"],+["lunge", "retreat", 5, 1, "A", 74, "touch"],+["lunge", "retreat", 5, 2, "A", 74, "touch"],+["lunge", "retreat", 5, 3, "A", 73, "touch"],+["lunge", "retreat", 5, 4, "A", 73, "touch"],+["lunge", "retreat", 5, 5, "A", 73, "touch"],+["lunge", "draw", 0, 0, "A", 73, "touch"],+["lunge", "draw", 0, 1, "A", 73, "touch"],+["lunge", "draw", 0, 2, "A", 73, "touch"],+["lunge", "draw", 0, 3, "A", 73, "touch"],+["lunge", "draw", 0, 4, "A", 73, "touch"],+["lunge", "draw", 0, 5, "A", 131, "touch"],+["lunge", "draw", 1, 0, "A", 70, "touch"],+["lunge", "draw", 1, 1, "A", 70, "touch"],+["lunge", "draw", 1, 2, "A", 70, "touch"],+["lunge", "draw", 1, 3, "A", 70, "touch"],+["lunge", "draw", 1, 4, "A", 70, "touch"],+["lunge", "draw", 1, 5, "A", 70, "touch"],+["lunge", "draw", 2, 0, "B", 96, "touch"],+["lunge", "draw", 2, 1, "A", 75, "touch"],+["lunge", "draw", 2, 2, "A", 75, "touch"],+["lunge", "draw", 2, 3, "A", 75, "touch"],+["lunge", "draw", 2, 4, "A", 75, "touch"],+["lunge", "draw", 2, 5, "A", 75, "touch"],+["lunge", "draw", 3, 0, "B", 62, "touch"],+["lunge", "draw", 3, 1, "B", 62, "touch"],+["lunge", "draw", 3, 2, "B", 62, "touch"],+["lunge", "draw", 3, 3, "A", 72, "touch"],+["lunge", "draw", 3, 4, "A", 72, "touch"],+["lunge", "draw", 3, 5, "A", 72, "touch"],+["lunge", "draw", 4, 0, "A", 76, "touch"],+["lunge", "draw", 4, 1, "B", 97, "touch"],+["lunge", "draw", 4, 2, "B", 97, "touch"],+["lunge", "draw", 4, 3, "A", 75, "touch"],+["lunge", "draw", 4, 4, "A", 75, "touch"],+["lunge", "draw", 4, 5, "A", 76, "touch"],+["lunge", "draw", 5, 0, "A", 74, "touch"],+["lunge", "draw", 5, 1, "B", 63, "touch"],+["lunge", "draw", 5, 2, "B", 63, "touch"],+["lunge", "draw", 5, 3, "B", 64, "touch"],+["lunge", "draw", 5, 4, "B", 64, "touch"],+["lunge", "draw", 5, 5, "A", 74, "touch"],+["low", "lunge", 0, 0, "AB", 39, "touch"],+["low", "lunge", 0, 1, "AB", 40, "touch"],+["low", "lunge", 0, 2, "AB", 39, "touch"],+["low", "lunge", 0, 3, "AB", 40, "touch"],+["low", "lunge", 0, 4, "AB", 40, "touch"],+["low", "lunge", 0, 5, "B", 46, "touch"],+["low", "lunge", 1, 0, "AB", 39, "touch"],+["low", "lunge", 1, 1, "AB", 40, "touch"],+["low", "lunge", 1, 2, "AB", 40, "touch"],+["low", "lunge", 1, 3, "AB", 41, "touch"],+["low", "lunge", 1, 4, "AB", 40, "touch"],+["low", "lunge", 1, 5, "AB", 42, "touch"],+["low", "lunge", 2, 0, "AB", 40, "touch"],+["low", "lunge", 2, 1, "AB", 41, "touch"],+["low", "lunge", 2, 2, "AB", 41, "touch"],+["low", "lunge", 2, 3, "AB", 41, "touch"],+["low", "lunge", 2, 4, "AB", 41, "touch"],+["low", "lunge", 2, 5, "AB", 42, "touch"],+["low", "lunge", 3, 0, "AB", 41, "touch"],+["low", "lunge", 3, 1, "AB", 41, "touch"],+["low", "lunge", 3, 2, "AB", 42, "touch"],+["low", "lunge", 3, 3, "AB", 42, "touch"],+["low", "lunge", 3, 4, "AB", 42, "touch"],+["low", "lunge", 3, 5, "AB", 43, "touch"],+["low", "lunge", 4, 0, "AB", 42, "touch"],+["low", "lunge", 4, 1, "AB", 42, "touch"],+["low", "lunge", 4, 2, "AB", 42, "touch"],+["low", "lunge", 4, 3, "AB", 43, "touch"],+["low", "lunge", 4, 4, "AB", 43, "touch"],+["low", "lunge", 4, 5, "AB", 43, "touch"],+["low", "lunge", 5, 0, "AB", 42, "touch"],+["low", "lunge", 5, 1, "AB", 43, "touch"],+["low", "lunge", 5, 2, "AB", 43, "touch"],+["low", "lunge", 5, 3, "AB", 43, "touch"],+["low", "lunge", 5, 4, "AB", 43, "touch"],+["low", "lunge", 5, 5, "AB", 44, "touch"],+["low", "low", 0, 0, "AB", 37, "touch"],+["low", "low", 0, 1, "B", 42, "touch"],+["low", "low", 0, 2, "AB", 38, "touch"],+["low", "low", 0, 3, "B", 43, "touch"],+["low", "low", 0, 4, "AB", 39, "touch"],+["low", "low", 0, 5, "A", 44, "touch"],+["low", "low", 1, 0, "AB", 38, "touch"],+["low", "low", 1, 1, "AB", 39, "touch"],+["low", "low", 1, 2, "AB", 39, "touch"],+["low", "low", 1, 3, "AB", 39, "touch"],+["low", "low", 1, 4, "AB", 40, "touch"],+["low", "low", 1, 5, "AB", 40, "touch"],+["low", "low", 2, 0, "AB", 38, "touch"],+["low", "low", 2, 1, "AB", 40, "touch"],+["low", "low", 2, 2, "AB", 39, "touch"],+["low", "low", 2, 3, "AB", 40, "touch"],+["low", "low", 2, 4, "AB", 40, "touch"],+["low", "low", 2, 5, "AB", 41, "touch"],+["low", "low", 3, 0, "AB", 38, "touch"],+["low", "low", 3, 1, "AB", 39, "touch"],+["low", "low", 3, 2, "AB", 40, "touch"],+["low", "low", 3, 3, "AB", 40, "touch"],+["low", "low", 3, 4, "AB", 41, "touch"],+["low", "low", 3, 5, "AB", 42, "touch"],+["low", "low", 4, 0, "AB", 39, "touch"],+["low", "low", 4, 1, "AB", 40, "touch"],+["low", "low", 4, 2, "AB", 40, "touch"],+["low", "low", 4, 3, "AB", 41, "touch"],+["low", "low", 4, 4, "AB", 41, "touch"],+["low", "low", 4, 5, "AB", 42, "touch"],+["low", "low", 5, 0, "A", 44, "touch"],+["low", "low", 5, 1, "AB", 40, "touch"],+["low", "low", 5, 2, "AB", 41, "touch"],+["low", "low", 5, 3, "AB", 41, "touch"],+["low", "low", 5, 4, "AB", 41, "touch"],+["low", "low", 5, 5, "AB", 42, "touch"],+["low", "line", 0, 0, "none", null, "time"],+["low", "line", 0, 1, "none", null, "time"],+["low", "line", 0, 2, "A", 147, "touch"],+["low", "line", 0, 3, "none", null, "time"],+["low", "line", 0, 4, "A", 149, "touch"],+["low", "line", 0, 5, "none", null, "time"],+["low", "line", 1, 0, "none", null, "time"],+["low", "line", 1, 1, "A", 160, "touch"],+["low", "line", 1, 2, "A", 119, "touch"],+["low", "line", 1, 3, "A", 169, "touch"],+["low", "line", 1, 4, "A", 156, "touch"],+["low", "line", 1, 5, "A", 162, "touch"],+["low", "line", 2, 0, "none", null, "time"],+["low", "line", 2, 1, "none", null, "time"],+["low", "line", 2, 2, "A", 146, "touch"],+["low", "line", 2, 3, "none", null, "time"],+["low", "line", 2, 4, "A", 147, "touch"],+["low", "line", 2, 5, "none", null, "time"],+["low", "line", 3, 0, "none", null, "time"],+["low", "line", 3, 1, "A", 164, "touch"],+["low", "line", 3, 2, "A", 168, "touch"],+["low", "line", 3, 3, "none", null, "time"],+["low", "line", 3, 4, "none", null, "time"],+["low", "line", 3, 5, "A", 164, "touch"],+["low", "line", 4, 0, "none", null, "time"],+["low", "line", 4, 1, "none", null, "time"],+["low", "line", 4, 2, "none", null, "time"],+["low", "line", 4, 3, "A", 157, "touch"],+["low", "line", 4, 4, "A", 151, "touch"],+["low", "line", 4, 5, "A", 165, "touch"],+["low", "line", 5, 0, "A", 174, "touch"],+["low", "line", 5, 1, "A", 166, "touch"],+["low", "line", 5, 2, "A", 169, "touch"],+["low", "line", 5, 3, "none", null, "time"],+["low", "line", 5, 4, "A", 172, "touch"],+["low", "line", 5, 5, "none", null, "time"],+["low", "rline", 0, 0, "none", null, "time"],+["low", "rline", 0, 1, "none", null, "time"],+["low", "rline", 0, 2, "none", null, "time"],+["low", "rline", 0, 3, "none", null, "time"],+["low", "rline", 0, 4, "none", null, "time"],+["low", "rline", 0, 5, "none", null, "time"],+["low", "rline", 1, 0, "B", 89, "touch"],+["low", "rline", 1, 1, "B", 89, "touch"],+["low", "rline", 1, 2, "B", 89, "touch"],+["low", "rline", 1, 3, "B", 89, "touch"],+["low", "rline", 1, 4, "B", 89, "touch"],+["low", "rline", 1, 5, "B", 89, "touch"],+["low", "rline", 2, 0, "A", 149, "touch"],+["low", "rline", 2, 1, "A", 149, "touch"],+["low", "rline", 2, 2, "A", 149, "touch"],+["low", "rline", 2, 3, "A", 149, "touch"],+["low", "rline", 2, 4, "A", 149, "touch"],+["low", "rline", 2, 5, "A", 149, "touch"],+["low", "rline", 3, 0, "B", 94, "touch"],+["low", "rline", 3, 1, "B", 94, "touch"],+["low", "rline", 3, 2, "B", 94, "touch"],+["low", "rline", 3, 3, "B", 94, "touch"],+["low", "rline", 3, 4, "B", 94, "touch"],+["low", "rline", 3, 5, "B", 94, "touch"],+["low", "rline", 4, 0, "none", null, "time"],+["low", "rline", 4, 1, "none", null, "time"],+["low", "rline", 4, 2, "none", null, "time"],+["low", "rline", 4, 3, "none", null, "time"],+["low", "rline", 4, 4, "none", null, "time"],+["low", "rline", 4, 5, "none", null, "time"],+["low", "rline", 5, 0, "B", 114, "touch"],+["low", "rline", 5, 1, "B", 114, "touch"],+["low", "rline", 5, 2, "B", 114, "touch"],+["low", "rline", 5, 3, "B", 114, "touch"],+["low", "rline", 5, 4, "B", 114, "touch"],+["low", "rline", 5, 5, "B", 114, "touch"],+["low", "stop", 0, 0, "B", 62, "touch"],+["low", "stop", 0, 1, "B", 62, "touch"],+["low", "stop", 0, 2, "B", 62, "touch"],+["low", "stop", 0, 3, "B", 62, "touch"],+["low", "stop", 0, 4, "B", 62, "touch"],+["low", "stop", 0, 5, "B", 62, "touch"],+["low", "stop", 1, 0, "A", 70, "touch"],+["low", "stop", 1, 1, "A", 70, "touch"],+["low", "stop", 1, 2, "A", 70, "touch"],+["low", "stop", 1, 3, "A", 70, "touch"],+["low", "stop", 1, 4, "A", 70, "touch"],+["low", "stop", 1, 5, "A", 70, "touch"],+["low", "stop", 2, 0, "A", 173, "touch"],+["low", "stop", 2, 1, "A", 173, "touch"],+["low", "stop", 2, 2, "A", 173, "touch"],+["low", "stop", 2, 3, "A", 173, "touch"],+["low", "stop", 2, 4, "A", 173, "touch"],+["low", "stop", 2, 5, "A", 173, "touch"],+["low", "stop", 3, 0, "B", 61, "touch"],+["low", "stop", 3, 1, "B", 61, "touch"],+["low", "stop", 3, 2, "B", 61, "touch"],+["low", "stop", 3, 3, "B", 61, "touch"],+["low", "stop", 3, 4, "B", 61, "touch"],+["low", "stop", 3, 5, "B", 61, "touch"],+["low", "stop", 4, 0, "B", 64, "touch"],+["low", "stop", 4, 1, "B", 64, "touch"],+["low", "stop", 4, 2, "B", 64, "touch"],+["low", "stop", 4, 3, "B", 64, "touch"],+["low", "stop", 4, 4, "B", 64, "touch"],+["low", "stop", 4, 5, "B", 64, "touch"],+["low", "stop", 5, 0, "B", 67, "touch"],+["low", "stop", 5, 1, "B", 67, "touch"],+["low", "stop", 5, 2, "B", 67, "touch"],+["low", "stop", 5, 3, "B", 67, "touch"],+["low", "stop", 5, 4, "B", 67, "touch"],+["low", "stop", 5, 5, "B", 67, "touch"],+["low", "counter", 0, 0, "B", 50, "touch"],+["low", "counter", 0, 1, "B", 50, "touch"],+["low", "counter", 0, 2, "B", 50, "touch"],+["low", "counter", 0, 3, "B", 50, "touch"],+["low", "counter", 0, 4, "B", 50, "touch"],+["low", "counter", 0, 5, "B", 50, "touch"],+["low", "counter", 1, 0, "B", 53, "touch"],+["low", "counter", 1, 1, "B", 53, "touch"],+["low", "counter", 1, 2, "B", 53, "touch"],+["low", "counter", 1, 3, "B", 53, "touch"],+["low", "counter", 1, 4, "B", 53, "touch"],+["low", "counter", 1, 5, "B", 53, "touch"],+["low", "counter", 2, 0, "B", 52, "touch"],+["low", "counter", 2, 1, "B", 52, "touch"],+["low", "counter", 2, 2, "B", 52, "touch"],+["low", "counter", 2, 3, "B", 52, "touch"],+["low", "counter", 2, 4, "B", 52, "touch"],+["low", "counter", 2, 5, "B", 52, "touch"],+["low", "counter", 3, 0, "B", 55, "touch"],+["low", "counter", 3, 1, "B", 55, "touch"],+["low", "counter", 3, 2, "B", 55, "touch"],+["low", "counter", 3, 3, "B", 55, "touch"],+["low", "counter", 3, 4, "B", 55, "touch"],+["low", "counter", 3, 5, "B", 55, "touch"],+["low", "counter", 4, 0, "B", 55, "touch"],+["low", "counter", 4, 1, "B", 55, "touch"],+["low", "counter", 4, 2, "B", 55, "touch"],+["low", "counter", 4, 3, "B", 55, "touch"],+["low", "counter", 4, 4, "B", 55, "touch"],+["low", "counter", 4, 5, "B", 55, "touch"],+["low", "counter", 5, 0, "B", 57, "touch"],+["low", "counter", 5, 1, "B", 57, "touch"],+["low", "counter", 5, 2, "B", 57, "touch"],+["low", "counter", 5, 3, "B", 57, "touch"],+["low", "counter", 5, 4, "B", 57, "touch"],+["low", "counter", 5, 5, "B", 57, "touch"],+["low", "delay", 0, 0, "B", 68, "touch"],+["low", "delay", 0, 1, "B", 70, "touch"],+["low", "delay", 0, 2, "B", 70, "touch"],+["low", "delay", 0, 3, "B", 71, "touch"],+["low", "delay", 0, 4, "B", 72, "touch"],+["low", "delay", 0, 5, "B", 73, "touch"],+["low", "delay", 1, 0, "B", 69, "touch"],+["low", "delay", 1, 1, "B", 70, "touch"],+["low", "delay", 1, 2, "B", 71, "touch"],+["low", "delay", 1, 3, "B", 72, "touch"],+["low", "delay", 1, 4, "B", 72, "touch"],+["low", "delay", 1, 5, "B", 73, "touch"],+["low", "delay", 2, 0, "B", 69, "touch"],+["low", "delay", 2, 1, "B", 70, "touch"],+["low", "delay", 2, 2, "B", 71, "touch"],+["low", "delay", 2, 3, "B", 71, "touch"],+["low", "delay", 2, 4, "B", 72, "touch"],+["low", "delay", 2, 5, "B", 73, "touch"],+["low", "delay", 3, 0, "B", 69, "touch"],+["low", "delay", 3, 1, "B", 69, "touch"],+["low", "delay", 3, 2, "B", 71, "touch"],+["low", "delay", 3, 3, "B", 72, "touch"],+["low", "delay", 3, 4, "B", 73, "touch"],+["low", "delay", 3, 5, "B", 73, "touch"],+["low", "delay", 4, 0, "B", 69, "touch"],+["low", "delay", 4, 1, "B", 70, "touch"],+["low", "delay", 4, 2, "B", 71, "touch"],+["low", "delay", 4, 3, "B", 72, "touch"],+["low", "delay", 4, 4, "B", 72, "touch"],+["low", "delay", 4, 5, "B", 73, "touch"],+["low", "delay", 5, 0, "B", 69, "touch"],+["low", "delay", 5, 1, "B", 70, "touch"],+["low", "delay", 5, 2, "B", 71, "touch"],+["low", "delay", 5, 3, "B", 72, "touch"],+["low", "delay", 5, 4, "B", 72, "touch"],+["low", "delay", 5, 5, "B", 74, "touch"],+["low", "retreat", 0, 0, "A", 49, "touch"],+["low", "retreat", 0, 1, "A", 49, "touch"],+["low", "retreat", 0, 2, "A", 49, "touch"],+["low", "retreat", 0, 3, "A", 49, "touch"],+["low", "retreat", 0, 4, "A", 49, "touch"],+["low", "retreat", 0, 5, "A", 49, "touch"],+["low", "retreat", 1, 0, "A", 85, "touch"],+["low", "retreat", 1, 1, "none", null, "time"],+["low", "retreat", 1, 2, "none", null, "time"],+["low", "retreat", 1, 3, "A", 88, "touch"],+["low", "retreat", 1, 4, "A", 88, "touch"],+["low", "retreat", 1, 5, "A", 91, "touch"],+["low", "retreat", 2, 0, "A", 52, "touch"],+["low", "retreat", 2, 1, "A", 51, "touch"],+["low", "retreat", 2, 2, "A", 51, "touch"],+["low", "retreat", 2, 3, "A", 51, "touch"],+["low", "retreat", 2, 4, "A", 51, "touch"],+["low", "retreat", 2, 5, "A", 51, "touch"],+["low", "retreat", 3, 0, "none", null, "time"],+["low", "retreat", 3, 1, "none", null, "time"],+["low", "retreat", 3, 2, "none", null, "time"],+["low", "retreat", 3, 3, "none", null, "time"],+["low", "retreat", 3, 4, "none", null, "time"],+["low", "retreat", 3, 5, "none", null, "time"],+["low", "retreat", 4, 0, "A", 54, "touch"],+["low", "retreat", 4, 1, "A", 54, "touch"],+["low", "retreat", 4, 2, "A", 54, "touch"],+["low", "retreat", 4, 3, "A", 53, "touch"],+["low", "retreat", 4, 4, "A", 53, "touch"],+["low", "retreat", 4, 5, "A", 53, "touch"],+["low", "retreat", 5, 0, "none", null, "time"],+["low", "retreat", 5, 1, "none", null, "time"],+["low", "retreat", 5, 2, "none", null, "time"],+["low", "retreat", 5, 3, "none", null, "time"],+["low", "retreat", 5, 4, "none", null, "time"],+["low", "retreat", 5, 5, "none", null, "time"],+["low", "draw", 0, 0, "B", 57, "touch"],+["low", "draw", 0, 1, "B", 58, "touch"],+["low", "draw", 0, 2, "B", 58, "touch"],+["low", "draw", 0, 3, "B", 60, "touch"],+["low", "draw", 0, 4, "B", 60, "touch"],+["low", "draw", 0, 5, "B", 60, "touch"],+["low", "draw", 1, 0, "A", 106, "touch"],+["low", "draw", 1, 1, "none", null, "time"],+["low", "draw", 1, 2, "none", null, "time"],+["low", "draw", 1, 3, "B", 59, "touch"],+["low", "draw", 1, 4, "B", 59, "touch"],+["low", "draw", 1, 5, "B", 60, "touch"],+["low", "draw", 2, 0, "B", 59, "touch"],+["low", "draw", 2, 1, "B", 60, "touch"],+["low", "draw", 2, 2, "B", 60, "touch"],+["low", "draw", 2, 3, "B", 61, "touch"],+["low", "draw", 2, 4, "B", 61, "touch"],+["low", "draw", 2, 5, "B", 61, "touch"],+["low", "draw", 3, 0, "B", 61, "touch"],+["low", "draw", 3, 1, "B", 59, "touch"],+["low", "draw", 3, 2, "B", 59, "touch"],+["low", "draw", 3, 3, "none", null, "time"],+["low", "draw", 3, 4, "none", null, "time"],+["low", "draw", 3, 5, "B", 61, "touch"],+["low", "draw", 4, 0, "B", 62, "touch"],+["low", "draw", 4, 1, "A", 105, "touch"],+["low", "draw", 4, 2, "A", 105, "touch"],+["low", "draw", 4, 3, "B", 262, "touch"],+["low", "draw", 4, 4, "B", 262, "touch"],+["low", "draw", 4, 5, "B", 61, "touch"],+["low", "draw", 5, 0, "B", 256, "touch"],+["low", "draw", 5, 1, "B", 62, "touch"],+["low", "draw", 5, 2, "B", 62, "touch"],+["low", "draw", 5, 3, "B", 61, "touch"],+["low", "draw", 5, 4, "B", 61, "touch"],+["low", "draw", 5, 5, "B", 62, "touch"],+["line", "lunge", 0, 0, "A", 31, "touch"],+["line", "lunge", 0, 1, "B", 71, "touch"],+["line", "lunge", 0, 2, "A", 32, "touch"],+["line", "lunge", 0, 3, "B", 73, "touch"],+["line", "lunge", 0, 4, "B", 130, "touch"],+["line", "lunge", 0, 5, "B", 75, "touch"],+["line", "lunge", 1, 0, "none", null, "time"],+["line", "lunge", 1, 1, "B", 70, "touch"],+["line", "lunge", 1, 2, "B", 144, "touch"],+["line", "lunge", 1, 3, "B", 72, "touch"],+["line", "lunge", 1, 4, "B", 153, "touch"],+["line", "lunge", 1, 5, "B", 74, "touch"],+["line", "lunge", 2, 0, "none", null, "time"],+["line", "lunge", 2, 1, "A", 33, "touch"],+["line", "lunge", 2, 2, "A", 33, "touch"],+["line", "lunge", 2, 3, "B", 72, "touch"],+["line", "lunge", 2, 4, "A", 34, "touch"],+["line", "lunge", 2, 5, "B", 75, "touch"],+["line", "lunge", 3, 0, "B", 31, "touch"],+["line", "lunge", 3, 1, "B", 69, "touch"],+["line", "lunge", 3, 2, "B", 136, "touch"],+["line", "lunge", 3, 3, "B", 72, "touch"],+["line", "lunge", 3, 4, "A", 34, "touch"],+["line", "lunge", 3, 5, "B", 75, "touch"],+["line", "lunge", 4, 0, "B", 31, "touch"],+["line", "lunge", 4, 1, "A", 35, "touch"],+["line", "lunge", 4, 2, "B", 131, "touch"],+["line", "lunge", 4, 3, "A", 35, "touch"],+["line", "lunge", 4, 4, "A", 35, "touch"],+["line", "lunge", 4, 5, "B", 75, "touch"],+["line", "lunge", 5, 0, "B", 31, "touch"],+["line", "lunge", 5, 1, "B", 70, "touch"],+["line", "lunge", 5, 2, "B", 33, "touch"],+["line", "lunge", 5, 3, "B", 72, "touch"],+["line", "lunge", 5, 4, "B", 122, "touch"],+["line", "lunge", 5, 5, "B", 74, "touch"],+["line", "low", 0, 0, "B", 147, "touch"],+["line", "low", 0, 1, "B", 166, "touch"],+["line", "low", 0, 2, "B", 147, "touch"],+["line", "low", 0, 3, "B", 166, "touch"],+["line", "low", 0, 4, "none", null, "time"],+["line", "low", 0, 5, "none", null, "time"],+["line", "low", 1, 0, "none", null, "time"],+["line", "low", 1, 1, "B", 106, "touch"],+["line", "low", 1, 2, "none", null, "time"],+["line", "low", 1, 3, "none", null, "time"],+["line", "low", 1, 4, "none", null, "time"],+["line", "low", 1, 5, "none", null, "time"],+["line", "low", 2, 0, "B", 149, "touch"],+["line", "low", 2, 1, "B", 103, "touch"],+["line", "low", 2, 2, "none", null, "time"],+["line", "low", 2, 3, "none", null, "time"],+["line", "low", 2, 4, "B", 149, "touch"],+["line", "low", 2, 5, "none", null, "time"],+["line", "low", 3, 0, "B", 155, "touch"],+["line", "low", 3, 1, "none", null, "time"],+["line", "low", 3, 2, "none", null, "time"],+["line", "low", 3, 3, "B", 103, "touch"],+["line", "low", 3, 4, "none", null, "time"],+["line", "low", 3, 5, "none", null, "time"],+["line", "low", 4, 0, "B", 147, "touch"],+["line", "low", 4, 1, "none", null, "time"],+["line", "low", 4, 2, "B", 153, "touch"],+["line", "low", 4, 3, "B", 175, "touch"],+["line", "low", 4, 4, "none", null, "time"],+["line", "low", 4, 5, "none", null, "time"],+["line", "low", 5, 0, "none", null, "time"],+["line", "low", 5, 1, "B", 164, "touch"],+["line", "low", 5, 2, "none", null, "time"],+["line", "low", 5, 3, "B", 164, "touch"],+["line", "low", 5, 4, "none", null, "time"],+["line", "low", 5, 5, "none", null, "time"],+["line", "line", 0, 0, "none", null, "time"],+["line", "line", 0, 1, "none", null, "time"],+["line", "line", 0, 2, "none", null, "time"],+["line", "line", 0, 3, "none", null, "time"],+["line", "line", 0, 4, "none", null, "time"],+["line", "line", 0, 5, "none", null, "time"],+["line", "line", 1, 0, "none", null, "time"],+["line", "line", 1, 1, "none", null, "time"],+["line", "line", 1, 2, "none", null, "time"],+["line", "line", 1, 3, "none", null, "time"],+["line", "line", 1, 4, "none", null, "time"],+["line", "line", 1, 5, "none", null, "time"],+["line", "line", 2, 0, "none", null, "time"],+["line", "line", 2, 1, "none", null, "time"],+["line", "line", 2, 2, "none", null, "time"],+["line", "line", 2, 3, "none", null, "time"],+["line", "line", 2, 4, "none", null, "time"],+["line", "line", 2, 5, "none", null, "time"],+["line", "line", 3, 0, "none", null, "time"],+["line", "line", 3, 1, "none", null, "time"],+["line", "line", 3, 2, "none", null, "time"],+["line", "line", 3, 3, "none", null, "time"],+["line", "line", 3, 4, "none", null, "time"],+["line", "line", 3, 5, "none", null, "time"],+["line", "line", 4, 0, "none", null, "time"],+["line", "line", 4, 1, "none", null, "time"],+["line", "line", 4, 2, "none", null, "time"],+["line", "line", 4, 3, "none", null, "time"],+["line", "line", 4, 4, "none", null, "time"],+["line", "line", 4, 5, "none", null, "time"],+["line", "line", 5, 0, "none", null, "time"],+["line", "line", 5, 1, "none", null, "time"],+["line", "line", 5, 2, "none", null, "time"],+["line", "line", 5, 3, "none", null, "time"],+["line", "line", 5, 4, "none", null, "time"],+["line", "line", 5, 5, "none", null, "time"],+["line", "rline", 0, 0, "none", null, "time"],+["line", "rline", 0, 1, "none", null, "time"],+["line", "rline", 0, 2, "none", null, "time"],+["line", "rline", 0, 3, "none", null, "time"],+["line", "rline", 0, 4, "none", null, "time"],+["line", "rline", 0, 5, "none", null, "time"],+["line", "rline", 1, 0, "none", null, "time"],+["line", "rline", 1, 1, "none", null, "time"],+["line", "rline", 1, 2, "none", null, "time"],+["line", "rline", 1, 3, "none", null, "time"],+["line", "rline", 1, 4, "none", null, "time"],+["line", "rline", 1, 5, "none", null, "time"],+["line", "rline", 2, 0, "none", null, "time"],+["line", "rline", 2, 1, "none", null, "time"],+["line", "rline", 2, 2, "none", null, "time"],+["line", "rline", 2, 3, "none", null, "time"],+["line", "rline", 2, 4, "none", null, "time"],+["line", "rline", 2, 5, "none", null, "time"],+["line", "rline", 3, 0, "none", null, "time"],+["line", "rline", 3, 1, "none", null, "time"],+["line", "rline", 3, 2, "none", null, "time"],+["line", "rline", 3, 3, "none", null, "time"],+["line", "rline", 3, 4, "none", null, "time"],+["line", "rline", 3, 5, "none", null, "time"],+["line", "rline", 4, 0, "none", null, "time"],+["line", "rline", 4, 1, "none", null, "time"],+["line", "rline", 4, 2, "none", null, "time"],+["line", "rline", 4, 3, "none", null, "time"],+["line", "rline", 4, 4, "none", null, "time"],+["line", "rline", 4, 5, "none", null, "time"],+["line", "rline", 5, 0, "none", null, "time"],+["line", "rline", 5, 1, "none", null, "time"],+["line", "rline", 5, 2, "none", null, "time"],+["line", "rline", 5, 3, "none", null, "time"],+["line", "rline", 5, 4, "none", null, "time"],+["line", "rline", 5, 5, "none", null, "time"],+["line", "stop", 0, 0, "none", null, "time"],+["line", "stop", 0, 1, "none", null, "time"],+["line", "stop", 0, 2, "none", null, "time"],+["line", "stop", 0, 3, "none", null, "time"],+["line", "stop", 0, 4, "none", null, "time"],+["line", "stop", 0, 5, "none", null, "time"],+["line", "stop", 1, 0, "none", null, "time"],+["line", "stop", 1, 1, "none", null, "time"],+["line", "stop", 1, 2, "none", null, "time"],+["line", "stop", 1, 3, "none", null, "time"],+["line", "stop", 1, 4, "none", null, "time"],+["line", "stop", 1, 5, "none", null, "time"],+["line", "stop", 2, 0, "none", null, "time"],+["line", "stop", 2, 1, "none", null, "time"],+["line", "stop", 2, 2, "none", null, "time"],+["line", "stop", 2, 3, "none", null, "time"],+["line", "stop", 2, 4, "none", null, "time"],+["line", "stop", 2, 5, "none", null, "time"],+["line", "stop", 3, 0, "none", null, "time"],+["line", "stop", 3, 1, "none", null, "time"],+["line", "stop", 3, 2, "none", null, "time"],+["line", "stop", 3, 3, "none", null, "time"],+["line", "stop", 3, 4, "none", null, "time"],+["line", "stop", 3, 5, "none", null, "time"],+["line", "stop", 4, 0, "none", null, "time"],+["line", "stop", 4, 1, "none", null, "time"],+["line", "stop", 4, 2, "none", null, "time"],+["line", "stop", 4, 3, "none", null, "time"],+["line", "stop", 4, 4, "none", null, "time"],+["line", "stop", 4, 5, "none", null, "time"],+["line", "stop", 5, 0, "none", null, "time"],+["line", "stop", 5, 1, "none", null, "time"],+["line", "stop", 5, 2, "none", null, "time"],+["line", "stop", 5, 3, "none", null, "time"],+["line", "stop", 5, 4, "none", null, "time"],+["line", "stop", 5, 5, "none", null, "time"],+["line", "counter", 0, 0, "none", null, "time"],+["line", "counter", 0, 1, "none", null, "time"],+["line", "counter", 0, 2, "none", null, "time"],+["line", "counter", 0, 3, "none", null, "time"],+["line", "counter", 0, 4, "none", null, "time"],+["line", "counter", 0, 5, "none", null, "time"],+["line", "counter", 1, 0, "none", null, "time"],+["line", "counter", 1, 1, "none", null, "time"],+["line", "counter", 1, 2, "none", null, "time"],+["line", "counter", 1, 3, "none", null, "time"],+["line", "counter", 1, 4, "none", null, "time"],+["line", "counter", 1, 5, "none", null, "time"],+["line", "counter", 2, 0, "none", null, "time"],+["line", "counter", 2, 1, "none", null, "time"],+["line", "counter", 2, 2, "none", null, "time"],+["line", "counter", 2, 3, "none", null, "time"],+["line", "counter", 2, 4, "none", null, "time"],+["line", "counter", 2, 5, "none", null, "time"],+["line", "counter", 3, 0, "none", null, "time"],+["line", "counter", 3, 1, "none", null, "time"],+["line", "counter", 3, 2, "none", null, "time"],+["line", "counter", 3, 3, "none", null, "time"],+["line", "counter", 3, 4, "none", null, "time"],+["line", "counter", 3, 5, "none", null, "time"],+["line", "counter", 4, 0, "none", null, "time"],+["line", "counter", 4, 1, "none", null, "time"],+["line", "counter", 4, 2, "none", null, "time"],+["line", "counter", 4, 3, "none", null, "time"],+["line", "counter", 4, 4, "none", null, "time"],+["line", "counter", 4, 5, "none", null, "time"],+["line", "counter", 5, 0, "none", null, "time"],+["line", "counter", 5, 1, "none", null, "time"],+["line", "counter", 5, 2, "none", null, "time"],+["line", "counter", 5, 3, "none", null, "time"],+["line", "counter", 5, 4, "none", null, "time"],+["line", "counter", 5, 5, "none", null, "time"],+["line", "delay", 0, 0, "B", 107, "touch"],+["line", "delay", 0, 1, "B", 108, "touch"],+["line", "delay", 0, 2, "B", 110, "touch"],+["line", "delay", 0, 3, "B", 111, "touch"],+["line", "delay", 0, 4, "B", 111, "touch"],+["line", "delay", 0, 5, "B", 112, "touch"],+["line", "delay", 1, 0, "B", 108, "touch"],+["line", "delay", 1, 1, "B", 108, "touch"],+["line", "delay", 1, 2, "B", 108, "touch"],+["line", "delay", 1, 3, "B", 110, "touch"],+["line", "delay", 1, 4, "B", 111, "touch"],+["line", "delay", 1, 5, "B", 113, "touch"],+["line", "delay", 2, 0, "B", 72, "touch"],+["line", "delay", 2, 1, "B", 108, "touch"],+["line", "delay", 2, 2, "B", 110, "touch"],+["line", "delay", 2, 3, "B", 110, "touch"],+["line", "delay", 2, 4, "B", 117, "touch"],+["line", "delay", 2, 5, "B", 112, "touch"],+["line", "delay", 3, 0, "B", 106, "touch"],+["line", "delay", 3, 1, "B", 108, "touch"],+["line", "delay", 3, 2, "B", 108, "touch"],+["line", "delay", 3, 3, "B", 110, "touch"],+["line", "delay", 3, 4, "B", 110, "touch"],+["line", "delay", 3, 5, "B", 112, "touch"],+["line", "delay", 4, 0, "B", 107, "touch"],+["line", "delay", 4, 1, "B", 108, "touch"],+["line", "delay", 4, 2, "B", 110, "touch"],+["line", "delay", 4, 3, "B", 110, "touch"],+["line", "delay", 4, 4, "B", 112, "touch"],+["line", "delay", 4, 5, "B", 111, "touch"],+["line", "delay", 5, 0, "B", 108, "touch"],+["line", "delay", 5, 1, "B", 108, "touch"],+["line", "delay", 5, 2, "B", 109, "touch"],+["line", "delay", 5, 3, "B", 109, "touch"],+["line", "delay", 5, 4, "B", 110, "touch"],+["line", "delay", 5, 5, "B", 112, "touch"],+["line", "retreat", 0, 0, "none", null, "time"],+["line", "retreat", 0, 1, "none", null, "time"],+["line", "retreat", 0, 2, "none", null, "time"],+["line", "retreat", 0, 3, "none", null, "time"],+["line", "retreat", 0, 4, "none", null, "time"],+["line", "retreat", 0, 5, "none", null, "time"],+["line", "retreat", 1, 0, "none", null, "time"],+["line", "retreat", 1, 1, "none", null, "time"],+["line", "retreat", 1, 2, "none", null, "time"],+["line", "retreat", 1, 3, "none", null, "time"],+["line", "retreat", 1, 4, "none", null, "time"],+["line", "retreat", 1, 5, "none", null, "time"],+["line", "retreat", 2, 0, "none", null, "time"],+["line", "retreat", 2, 1, "none", null, "time"],+["line", "retreat", 2, 2, "none", null, "time"],+["line", "retreat", 2, 3, "none", null, "time"],+["line", "retreat", 2, 4, "none", null, "time"],+["line", "retreat", 2, 5, "none", null, "time"],+["line", "retreat", 3, 0, "none", null, "time"],+["line", "retreat", 3, 1, "none", null, "time"],+["line", "retreat", 3, 2, "none", null, "time"],+["line", "retreat", 3, 3, "none", null, "time"],+["line", "retreat", 3, 4, "none", null, "time"],+["line", "retreat", 3, 5, "none", null, "time"],+["line", "retreat", 4, 0, "none", null, "time"],+["line", "retreat", 4, 1, "none", null, "time"],+["line", "retreat", 4, 2, "none", null, "time"],+["line", "retreat", 4, 3, "none", null, "time"],+["line", "retreat", 4, 4, "none", null, "time"],+["line", "retreat", 4, 5, "none", null, "time"],+["line", "retreat", 5, 0, "none", null, "time"],+["line", "retreat", 5, 1, "none", null, "time"],+["line", "retreat", 5, 2, "none", null, "time"],+["line", "retreat", 5, 3, "none", null, "time"],+["line", "retreat", 5, 4, "none", null, "time"],+["line", "retreat", 5, 5, "none", null, "time"],+["line", "draw", 0, 0, "none", null, "time"],+["line", "draw", 0, 1, "none", null, "time"],+["line", "draw", 0, 2, "none", null, "time"],+["line", "draw", 0, 3, "none", null, "time"],+["line", "draw", 0, 4, "none", null, "time"],+["line", "draw", 0, 5, "none", null, "time"],+["line", "draw", 1, 0, "none", null, "time"],+["line", "draw", 1, 1, "none", null, "time"],+["line", "draw", 1, 2, "none", null, "time"],+["line", "draw", 1, 3, "none", null, "time"],+["line", "draw", 1, 4, "none", null, "time"],+["line", "draw", 1, 5, "none", null, "time"],+["line", "draw", 2, 0, "none", null, "time"],+["line", "draw", 2, 1, "none", null, "time"],+["line", "draw", 2, 2, "none", null, "time"],+["line", "draw", 2, 3, "none", null, "time"],+["line", "draw", 2, 4, "none", null, "time"],+["line", "draw", 2, 5, "none", null, "time"],+["line", "draw", 3, 0, "none", null, "time"],+["line", "draw", 3, 1, "none", null, "time"],+["line", "draw", 3, 2, "none", null, "time"],+["line", "draw", 3, 3, "none", null, "time"],+["line", "draw", 3, 4, "none", null, "time"],+["line", "draw", 3, 5, "none", null, "time"],+["line", "draw", 4, 0, "none", null, "time"],+["line", "draw", 4, 1, "none", null, "time"],+["line", "draw", 4, 2, "none", null, "time"],+["line", "draw", 4, 3, "none", null, "time"],+["line", "draw", 4, 4, "none", null, "time"],+["line", "draw", 4, 5, "none", null, "time"],+["line", "draw", 5, 0, "none", null, "time"],+["line", "draw", 5, 1, "none", null, "time"],+["line", "draw", 5, 2, "none", null, "time"],+["line", "draw", 5, 3, "none", null, "time"],+["line", "draw", 5, 4, "none", null, "time"],+["line", "draw", 5, 5, "none", null, "time"],+["rline", "lunge", 0, 0, "A", 85, "touch"],+["rline", "lunge", 0, 1, "B", 114, "touch"],+["rline", "lunge", 0, 2, "B", 156, "touch"],+["rline", "lunge", 0, 3, "none", null, "time"],+["rline", "lunge", 0, 4, "none", null, "time"],+["rline", "lunge", 0, 5, "B", 82, "touch"],+["rline", "lunge", 1, 0, "A", 85, "touch"],+["rline", "lunge", 1, 1, "B", 114, "touch"],+["rline", "lunge", 1, 2, "B", 156, "touch"],+["rline", "lunge", 1, 3, "none", null, "time"],+["rline", "lunge", 1, 4, "none", null, "time"],+["rline", "lunge", 1, 5, "B", 82, "touch"],+["rline", "lunge", 2, 0, "A", 85, "touch"],+["rline", "lunge", 2, 1, "B", 114, "touch"],+["rline", "lunge", 2, 2, "B", 156, "touch"],+["rline", "lunge", 2, 3, "none", null, "time"],+["rline", "lunge", 2, 4, "none", null, "time"],+["rline", "lunge", 2, 5, "B", 82, "touch"],+["rline", "lunge", 3, 0, "A", 85, "touch"],+["rline", "lunge", 3, 1, "B", 114, "touch"],+["rline", "lunge", 3, 2, "B", 156, "touch"],+["rline", "lunge", 3, 3, "none", null, "time"],+["rline", "lunge", 3, 4, "none", null, "time"],+["rline", "lunge", 3, 5, "B", 82, "touch"],+["rline", "lunge", 4, 0, "A", 85, "touch"],+["rline", "lunge", 4, 1, "B", 114, "touch"],+["rline", "lunge", 4, 2, "B", 156, "touch"],+["rline", "lunge", 4, 3, "none", null, "time"],+["rline", "lunge", 4, 4, "none", null, "time"],+["rline", "lunge", 4, 5, "B", 82, "touch"],+["rline", "lunge", 5, 0, "A", 85, "touch"],+["rline", "lunge", 5, 1, "B", 114, "touch"],+["rline", "lunge", 5, 2, "B", 156, "touch"],+["rline", "lunge", 5, 3, "none", null, "time"],+["rline", "lunge", 5, 4, "none", null, "time"],+["rline", "lunge", 5, 5, "B", 82, "touch"],+["rline", "low", 0, 0, "B", 145, "touch"],+["rline", "low", 0, 1, "A", 114, "touch"],+["rline", "low", 0, 2, "none", null, "time"],+["rline", "low", 0, 3, "B", 143, "touch"],+["rline", "low", 0, 4, "none", null, "time"],+["rline", "low", 0, 5, "A", 118, "touch"],+["rline", "low", 1, 0, "B", 145, "touch"],+["rline", "low", 1, 1, "A", 114, "touch"],+["rline", "low", 1, 2, "none", null, "time"],+["rline", "low", 1, 3, "B", 143, "touch"],+["rline", "low", 1, 4, "none", null, "time"],+["rline", "low", 1, 5, "A", 118, "touch"],+["rline", "low", 2, 0, "B", 145, "touch"],+["rline", "low", 2, 1, "A", 114, "touch"],+["rline", "low", 2, 2, "none", null, "time"],+["rline", "low", 2, 3, "B", 143, "touch"],+["rline", "low", 2, 4, "none", null, "time"],+["rline", "low", 2, 5, "A", 118, "touch"],+["rline", "low", 3, 0, "B", 145, "touch"],+["rline", "low", 3, 1, "A", 114, "touch"],+["rline", "low", 3, 2, "none", null, "time"],+["rline", "low", 3, 3, "B", 143, "touch"],+["rline", "low", 3, 4, "none", null, "time"],+["rline", "low", 3, 5, "A", 118, "touch"],+["rline", "low", 4, 0, "B", 145, "touch"],+["rline", "low", 4, 1, "A", 114, "touch"],+["rline", "low", 4, 2, "none", null, "time"],+["rline", "low", 4, 3, "B", 143, "touch"],+["rline", "low", 4, 4, "none", null, "time"],+["rline", "low", 4, 5, "A", 118, "touch"],+["rline", "low", 5, 0, "B", 145, "touch"],+["rline", "low", 5, 1, "A", 114, "touch"],+["rline", "low", 5, 2, "none", null, "time"],+["rline", "low", 5, 3, "B", 143, "touch"],+["rline", "low", 5, 4, "none", null, "time"],+["rline", "low", 5, 5, "A", 118, "touch"],+["rline", "line", 0, 0, "none", null, "time"],+["rline", "line", 0, 1, "none", null, "time"],+["rline", "line", 0, 2, "none", null, "time"],+["rline", "line", 0, 3, "none", null, "time"],+["rline", "line", 0, 4, "none", null, "time"],+["rline", "line", 0, 5, "none", null, "time"],+["rline", "line", 1, 0, "none", null, "time"],+["rline", "line", 1, 1, "none", null, "time"],+["rline", "line", 1, 2, "none", null, "time"],+["rline", "line", 1, 3, "none", null, "time"],+["rline", "line", 1, 4, "none", null, "time"],+["rline", "line", 1, 5, "none", null, "time"],+["rline", "line", 2, 0, "none", null, "time"],+["rline", "line", 2, 1, "none", null, "time"],+["rline", "line", 2, 2, "none", null, "time"],+["rline", "line", 2, 3, "none", null, "time"],+["rline", "line", 2, 4, "none", null, "time"],+["rline", "line", 2, 5, "none", null, "time"],+["rline", "line", 3, 0, "none", null, "time"],+["rline", "line", 3, 1, "none", null, "time"],+["rline", "line", 3, 2, "none", null, "time"],+["rline", "line", 3, 3, "none", null, "time"],+["rline", "line", 3, 4, "none", null, "time"],+["rline", "line", 3, 5, "none", null, "time"],+["rline", "line", 4, 0, "none", null, "time"],+["rline", "line", 4, 1, "none", null, "time"],+["rline", "line", 4, 2, "none", null, "time"],+["rline", "line", 4, 3, "none", null, "time"],+["rline", "line", 4, 4, "none", null, "time"],+["rline", "line", 4, 5, "none", null, "time"],+["rline", "line", 5, 0, "none", null, "time"],+["rline", "line", 5, 1, "none", null, "time"],+["rline", "line", 5, 2, "none", null, "time"],+["rline", "line", 5, 3, "none", null, "time"],+["rline", "line", 5, 4, "none", null, "time"],+["rline", "line", 5, 5, "none", null, "time"],+["rline", "rline", 0, 0, "none", null, "time"],+["rline", "rline", 0, 1, "none", null, "time"],+["rline", "rline", 0, 2, "none", null, "time"],+["rline", "rline", 0, 3, "none", null, "time"],+["rline", "rline", 0, 4, "none", null, "time"],+["rline", "rline", 0, 5, "none", null, "time"],+["rline", "rline", 1, 0, "none", null, "time"],+["rline", "rline", 1, 1, "none", null, "time"],+["rline", "rline", 1, 2, "none", null, "time"],+["rline", "rline", 1, 3, "none", null, "time"],+["rline", "rline", 1, 4, "none", null, "time"],+["rline", "rline", 1, 5, "none", null, "time"],+["rline", "rline", 2, 0, "none", null, "time"],+["rline", "rline", 2, 1, "none", null, "time"],+["rline", "rline", 2, 2, "none", null, "time"],+["rline", "rline", 2, 3, "none", null, "time"],+["rline", "rline", 2, 4, "none", null, "time"],+["rline", "rline", 2, 5, "none", null, "time"],+["rline", "rline", 3, 0, "none", null, "time"],+["rline", "rline", 3, 1, "none", null, "time"],+["rline", "rline", 3, 2, "none", null, "time"],+["rline", "rline", 3, 3, "none", null, "time"],+["rline", "rline", 3, 4, "none", null, "time"],+["rline", "rline", 3, 5, "none", null, "time"],+["rline", "rline", 4, 0, "none", null, "time"],+["rline", "rline", 4, 1, "none", null, "time"],+["rline", "rline", 4, 2, "none", null, "time"],+["rline", "rline", 4, 3, "none", null, "time"],+["rline", "rline", 4, 4, "none", null, "time"],+["rline", "rline", 4, 5, "none", null, "time"],+["rline", "rline", 5, 0, "none", null, "time"],+["rline", "rline", 5, 1, "none", null, "time"],+["rline", "rline", 5, 2, "none", null, "time"],+["rline", "rline", 5, 3, "none", null, "time"],+["rline", "rline", 5, 4, "none", null, "time"],+["rline", "rline", 5, 5, "none", null, "time"],+["rline", "stop", 0, 0, "none", null, "time"],+["rline", "stop", 0, 1, "none", null, "time"],+["rline", "stop", 0, 2, "none", null, "time"],+["rline", "stop", 0, 3, "none", null, "time"],+["rline", "stop", 0, 4, "none", null, "time"],+["rline", "stop", 0, 5, "none", null, "time"],+["rline", "stop", 1, 0, "none", null, "time"],+["rline", "stop", 1, 1, "none", null, "time"],+["rline", "stop", 1, 2, "none", null, "time"],+["rline", "stop", 1, 3, "none", null, "time"],+["rline", "stop", 1, 4, "none", null, "time"],+["rline", "stop", 1, 5, "none", null, "time"],+["rline", "stop", 2, 0, "none", null, "time"],+["rline", "stop", 2, 1, "none", null, "time"],+["rline", "stop", 2, 2, "none", null, "time"],+["rline", "stop", 2, 3, "none", null, "time"],+["rline", "stop", 2, 4, "none", null, "time"],+["rline", "stop", 2, 5, "none", null, "time"],+["rline", "stop", 3, 0, "none", null, "time"],+["rline", "stop", 3, 1, "none", null, "time"],+["rline", "stop", 3, 2, "none", null, "time"],+["rline", "stop", 3, 3, "none", null, "time"],+["rline", "stop", 3, 4, "none", null, "time"],+["rline", "stop", 3, 5, "none", null, "time"],+["rline", "stop", 4, 0, "none", null, "time"],+["rline", "stop", 4, 1, "none", null, "time"],+["rline", "stop", 4, 2, "none", null, "time"],+["rline", "stop", 4, 3, "none", null, "time"],+["rline", "stop", 4, 4, "none", null, "time"],+["rline", "stop", 4, 5, "none", null, "time"],+["rline", "stop", 5, 0, "none", null, "time"],+["rline", "stop", 5, 1, "none", null, "time"],+["rline", "stop", 5, 2, "none", null, "time"],+["rline", "stop", 5, 3, "none", null, "time"],+["rline", "stop", 5, 4, "none", null, "time"],+["rline", "stop", 5, 5, "none", null, "time"],+["rline", "counter", 0, 0, "none", null, "time"],+["rline", "counter", 0, 1, "none", null, "time"],+["rline", "counter", 0, 2, "none", null, "time"],+["rline", "counter", 0, 3, "none", null, "time"],+["rline", "counter", 0, 4, "none", null, "time"],+["rline", "counter", 0, 5, "none", null, "time"],+["rline", "counter", 1, 0, "none", null, "time"],+["rline", "counter", 1, 1, "none", null, "time"],+["rline", "counter", 1, 2, "none", null, "time"],+["rline", "counter", 1, 3, "none", null, "time"],+["rline", "counter", 1, 4, "none", null, "time"],+["rline", "counter", 1, 5, "none", null, "time"],+["rline", "counter", 2, 0, "none", null, "time"],+["rline", "counter", 2, 1, "none", null, "time"],+["rline", "counter", 2, 2, "none", null, "time"],+["rline", "counter", 2, 3, "none", null, "time"],+["rline", "counter", 2, 4, "none", null, "time"],+["rline", "counter", 2, 5, "none", null, "time"],+["rline", "counter", 3, 0, "none", null, "time"],+["rline", "counter", 3, 1, "none", null, "time"],+["rline", "counter", 3, 2, "none", null, "time"],+["rline", "counter", 3, 3, "none", null, "time"],+["rline", "counter", 3, 4, "none", null, "time"],+["rline", "counter", 3, 5, "none", null, "time"],+["rline", "counter", 4, 0, "none", null, "time"],+["rline", "counter", 4, 1, "none", null, "time"],+["rline", "counter", 4, 2, "none", null, "time"],+["rline", "counter", 4, 3, "none", null, "time"],+["rline", "counter", 4, 4, "none", null, "time"],+["rline", "counter", 4, 5, "none", null, "time"],+["rline", "counter", 5, 0, "none", null, "time"],+["rline", "counter", 5, 1, "none", null, "time"],+["rline", "counter", 5, 2, "none", null, "time"],+["rline", "counter", 5, 3, "none", null, "time"],+["rline", "counter", 5, 4, "none", null, "time"],+["rline", "counter", 5, 5, "none", null, "time"],+["rline", "delay", 0, 0, "none", null, "time"],+["rline", "delay", 0, 1, "B", 152, "touch"],+["rline", "delay", 0, 2, "none", null, "time"],+["rline", "delay", 0, 3, "B", 125, "touch"],+["rline", "delay", 0, 4, "none", null, "time"],+["rline", "delay", 0, 5, "B", 160, "touch"],+["rline", "delay", 1, 0, "none", null, "time"],+["rline", "delay", 1, 1, "B", 152, "touch"],+["rline", "delay", 1, 2, "none", null, "time"],+["rline", "delay", 1, 3, "B", 125, "touch"],+["rline", "delay", 1, 4, "none", null, "time"],+["rline", "delay", 1, 5, "B", 160, "touch"],+["rline", "delay", 2, 0, "none", null, "time"],+["rline", "delay", 2, 1, "B", 152, "touch"],+["rline", "delay", 2, 2, "none", null, "time"],+["rline", "delay", 2, 3, "B", 125, "touch"],+["rline", "delay", 2, 4, "none", null, "time"],+["rline", "delay", 2, 5, "B", 160, "touch"],+["rline", "delay", 3, 0, "none", null, "time"],+["rline", "delay", 3, 1, "B", 152, "touch"],+["rline", "delay", 3, 2, "none", null, "time"],+["rline", "delay", 3, 3, "B", 125, "touch"],+["rline", "delay", 3, 4, "none", null, "time"],+["rline", "delay", 3, 5, "B", 160, "touch"],+["rline", "delay", 4, 0, "none", null, "time"],+["rline", "delay", 4, 1, "B", 152, "touch"],+["rline", "delay", 4, 2, "none", null, "time"],+["rline", "delay", 4, 3, "B", 125, "touch"],+["rline", "delay", 4, 4, "none", null, "time"],+["rline", "delay", 4, 5, "B", 160, "touch"],+["rline", "delay", 5, 0, "none", null, "time"],+["rline", "delay", 5, 1, "B", 152, "touch"],+["rline", "delay", 5, 2, "none", null, "time"],+["rline", "delay", 5, 3, "B", 125, "touch"],+["rline", "delay", 5, 4, "none", null, "time"],+["rline", "delay", 5, 5, "B", 160, "touch"],+["rline", "retreat", 0, 0, "none", null, "time"],+["rline", "retreat", 0, 1, "none", null, "time"],+["rline", "retreat", 0, 2, "none", null, "time"],+["rline", "retreat", 0, 3, "none", null, "time"],+["rline", "retreat", 0, 4, "none", null, "time"],+["rline", "retreat", 0, 5, "none", null, "time"],+["rline", "retreat", 1, 0, "none", null, "time"],+["rline", "retreat", 1, 1, "none", null, "time"],+["rline", "retreat", 1, 2, "none", null, "time"],+["rline", "retreat", 1, 3, "none", null, "time"],+["rline", "retreat", 1, 4, "none", null, "time"],+["rline", "retreat", 1, 5, "none", null, "time"],+["rline", "retreat", 2, 0, "none", null, "time"],+["rline", "retreat", 2, 1, "none", null, "time"],+["rline", "retreat", 2, 2, "none", null, "time"],+["rline", "retreat", 2, 3, "none", null, "time"],+["rline", "retreat", 2, 4, "none", null, "time"],+["rline", "retreat", 2, 5, "none", null, "time"],+["rline", "retreat", 3, 0, "none", null, "time"],+["rline", "retreat", 3, 1, "none", null, "time"],+["rline", "retreat", 3, 2, "none", null, "time"],+["rline", "retreat", 3, 3, "none", null, "time"],+["rline", "retreat", 3, 4, "none", null, "time"],+["rline", "retreat", 3, 5, "none", null, "time"],+["rline", "retreat", 4, 0, "none", null, "time"],+["rline", "retreat", 4, 1, "none", null, "time"],+["rline", "retreat", 4, 2, "none", null, "time"],+["rline", "retreat", 4, 3, "none", null, "time"],+["rline", "retreat", 4, 4, "none", null, "time"],+["rline", "retreat", 4, 5, "none", null, "time"],+["rline", "retreat", 5, 0, "none", null, "time"],+["rline", "retreat", 5, 1, "none", null, "time"],+["rline", "retreat", 5, 2, "none", null, "time"],+["rline", "retreat", 5, 3, "none", null, "time"],+["rline", "retreat", 5, 4, "none", null, "time"],+["rline", "retreat", 5, 5, "none", null, "time"],+["rline", "draw", 0, 0, "none", null, "time"],+["rline", "draw", 0, 1, "none", null, "time"],+["rline", "draw", 0, 2, "none", null, "time"],+["rline", "draw", 0, 3, "none", null, "time"],+["rline", "draw", 0, 4, "none", null, "time"],+["rline", "draw", 0, 5, "none", null, "time"],+["rline", "draw", 1, 0, "none", null, "time"],+["rline", "draw", 1, 1, "none", null, "time"],+["rline", "draw", 1, 2, "none", null, "time"],+["rline", "draw", 1, 3, "none", null, "time"],+["rline", "draw", 1, 4, "none", null, "time"],+["rline", "draw", 1, 5, "none", null, "time"],+["rline", "draw", 2, 0, "none", null, "time"],+["rline", "draw", 2, 1, "none", null, "time"],+["rline", "draw", 2, 2, "none", null, "time"],+["rline", "draw", 2, 3, "none", null, "time"],+["rline", "draw", 2, 4, "none", null, "time"],+["rline", "draw", 2, 5, "none", null, "time"],+["rline", "draw", 3, 0, "none", null, "time"],+["rline", "draw", 3, 1, "none", null, "time"],+["rline", "draw", 3, 2, "none", null, "time"],+["rline", "draw", 3, 3, "none", null, "time"],+["rline", "draw", 3, 4, "none", null, "time"],+["rline", "draw", 3, 5, "none", null, "time"],+["rline", "draw", 4, 0, "none", null, "time"],+["rline", "draw", 4, 1, "none", null, "time"],+["rline", "draw", 4, 2, "none", null, "time"],+["rline", "draw", 4, 3, "none", null, "time"],+["rline", "draw", 4, 4, "none", null, "time"],+["rline", "draw", 4, 5, "none", null, "time"],+["rline", "draw", 5, 0, "none", null, "time"],+["rline", "draw", 5, 1, "none", null, "time"],+["rline", "draw", 5, 2, "none", null, "time"],+["rline", "draw", 5, 3, "none", null, "time"],+["rline", "draw", 5, 4, "none", null, "time"],+["rline", "draw", 5, 5, "none", null, "time"],+["stop", "lunge", 0, 0, "B", 74, "touch"],+["stop", "lunge", 0, 1, "B", 70, "touch"],+["stop", "lunge", 0, 2, "B", 76, "touch"],+["stop", "lunge", 0, 3, "B", 73, "touch"],+["stop", "lunge", 0, 4, "B", 76, "touch"],+["stop", "lunge", 0, 5, "B", 75, "touch"],+["stop", "lunge", 1, 0, "B", 74, "touch"],+["stop", "lunge", 1, 1, "B", 70, "touch"],+["stop", "lunge", 1, 2, "B", 76, "touch"],+["stop", "lunge", 1, 3, "B", 73, "touch"],+["stop", "lunge", 1, 4, "B", 76, "touch"],+["stop", "lunge", 1, 5, "B", 75, "touch"],+["stop", "lunge", 2, 0, "B", 74, "touch"],+["stop", "lunge", 2, 1, "B", 70, "touch"],+["stop", "lunge", 2, 2, "B", 76, "touch"],+["stop", "lunge", 2, 3, "B", 73, "touch"],+["stop", "lunge", 2, 4, "B", 76, "touch"],+["stop", "lunge", 2, 5, "B", 75, "touch"],+["stop", "lunge", 3, 0, "B", 74, "touch"],+["stop", "lunge", 3, 1, "B", 70, "touch"],+["stop", "lunge", 3, 2, "B", 76, "touch"],+["stop", "lunge", 3, 3, "B", 73, "touch"],+["stop", "lunge", 3, 4, "B", 76, "touch"],+["stop", "lunge", 3, 5, "B", 75, "touch"],+["stop", "lunge", 4, 0, "B", 74, "touch"],+["stop", "lunge", 4, 1, "B", 70, "touch"],+["stop", "lunge", 4, 2, "B", 76, "touch"],+["stop", "lunge", 4, 3, "B", 73, "touch"],+["stop", "lunge", 4, 4, "B", 76, "touch"],+["stop", "lunge", 4, 5, "B", 75, "touch"],+["stop", "lunge", 5, 0, "B", 74, "touch"],+["stop", "lunge", 5, 1, "B", 70, "touch"],+["stop", "lunge", 5, 2, "B", 76, "touch"],+["stop", "lunge", 5, 3, "B", 73, "touch"],+["stop", "lunge", 5, 4, "B", 76, "touch"],+["stop", "lunge", 5, 5, "B", 75, "touch"],+["stop", "low", 0, 0, "A", 119, "touch"],+["stop", "low", 0, 1, "A", 151, "touch"],+["stop", "low", 0, 2, "A", 60, "touch"],+["stop", "low", 0, 3, "A", 65, "touch"],+["stop", "low", 0, 4, "A", 63, "touch"],+["stop", "low", 0, 5, "A", 128, "touch"],+["stop", "low", 1, 0, "A", 119, "touch"],+["stop", "low", 1, 1, "A", 151, "touch"],+["stop", "low", 1, 2, "A", 60, "touch"],+["stop", "low", 1, 3, "A", 65, "touch"],+["stop", "low", 1, 4, "A", 63, "touch"],+["stop", "low", 1, 5, "A", 128, "touch"],+["stop", "low", 2, 0, "A", 119, "touch"],+["stop", "low", 2, 1, "A", 151, "touch"],+["stop", "low", 2, 2, "A", 60, "touch"],+["stop", "low", 2, 3, "A", 65, "touch"],+["stop", "low", 2, 4, "A", 63, "touch"],+["stop", "low", 2, 5, "A", 128, "touch"],+["stop", "low", 3, 0, "A", 119, "touch"],+["stop", "low", 3, 1, "A", 151, "touch"],+["stop", "low", 3, 2, "A", 60, "touch"],+["stop", "low", 3, 3, "A", 65, "touch"],+["stop", "low", 3, 4, "A", 63, "touch"],+["stop", "low", 3, 5, "A", 128, "touch"],+["stop", "low", 4, 0, "A", 119, "touch"],+["stop", "low", 4, 1, "A", 151, "touch"],+["stop", "low", 4, 2, "A", 60, "touch"],+["stop", "low", 4, 3, "A", 65, "touch"],+["stop", "low", 4, 4, "A", 63, "touch"],+["stop", "low", 4, 5, "A", 128, "touch"],+["stop", "low", 5, 0, "A", 119, "touch"],+["stop", "low", 5, 1, "A", 151, "touch"],+["stop", "low", 5, 2, "A", 60, "touch"],+["stop", "low", 5, 3, "A", 65, "touch"],+["stop", "low", 5, 4, "A", 63, "touch"],+["stop", "low", 5, 5, "A", 128, "touch"],+["stop", "line", 0, 0, "none", null, "time"],+["stop", "line", 0, 1, "none", null, "time"],+["stop", "line", 0, 2, "none", null, "time"],+["stop", "line", 0, 3, "none", null, "time"],+["stop", "line", 0, 4, "none", null, "time"],+["stop", "line", 0, 5, "none", null, "time"],+["stop", "line", 1, 0, "none", null, "time"],+["stop", "line", 1, 1, "none", null, "time"],+["stop", "line", 1, 2, "none", null, "time"],+["stop", "line", 1, 3, "none", null, "time"],+["stop", "line", 1, 4, "none", null, "time"],+["stop", "line", 1, 5, "none", null, "time"],+["stop", "line", 2, 0, "none", null, "time"],+["stop", "line", 2, 1, "none", null, "time"],+["stop", "line", 2, 2, "none", null, "time"],+["stop", "line", 2, 3, "none", null, "time"],+["stop", "line", 2, 4, "none", null, "time"],+["stop", "line", 2, 5, "none", null, "time"],+["stop", "line", 3, 0, "none", null, "time"],+["stop", "line", 3, 1, "none", null, "time"],+["stop", "line", 3, 2, "none", null, "time"],+["stop", "line", 3, 3, "none", null, "time"],+["stop", "line", 3, 4, "none", null, "time"],+["stop", "line", 3, 5, "none", null, "time"],+["stop", "line", 4, 0, "none", null, "time"],+["stop", "line", 4, 1, "none", null, "time"],+["stop", "line", 4, 2, "none", null, "time"],+["stop", "line", 4, 3, "none", null, "time"],+["stop", "line", 4, 4, "none", null, "time"],+["stop", "line", 4, 5, "none", null, "time"],+["stop", "line", 5, 0, "none", null, "time"],+["stop", "line", 5, 1, "none", null, "time"],+["stop", "line", 5, 2, "none", null, "time"],+["stop", "line", 5, 3, "none", null, "time"],+["stop", "line", 5, 4, "none", null, "time"],+["stop", "line", 5, 5, "none", null, "time"],+["stop", "rline", 0, 0, "none", null, "time"],+["stop", "rline", 0, 1, "none", null, "time"],+["stop", "rline", 0, 2, "none", null, "time"],+["stop", "rline", 0, 3, "none", null, "time"],+["stop", "rline", 0, 4, "none", null, "time"],+["stop", "rline", 0, 5, "none", null, "time"],+["stop", "rline", 1, 0, "none", null, "time"],+["stop", "rline", 1, 1, "none", null, "time"],+["stop", "rline", 1, 2, "none", null, "time"],+["stop", "rline", 1, 3, "none", null, "time"],+["stop", "rline", 1, 4, "none", null, "time"],+["stop", "rline", 1, 5, "none", null, "time"],+["stop", "rline", 2, 0, "none", null, "time"],+["stop", "rline", 2, 1, "none", null, "time"],+["stop", "rline", 2, 2, "none", null, "time"],+["stop", "rline", 2, 3, "none", null, "time"],+["stop", "rline", 2, 4, "none", null, "time"],+["stop", "rline", 2, 5, "none", null, "time"],+["stop", "rline", 3, 0, "none", null, "time"],+["stop", "rline", 3, 1, "none", null, "time"],+["stop", "rline", 3, 2, "none", null, "time"],+["stop", "rline", 3, 3, "none", null, "time"],+["stop", "rline", 3, 4, "none", null, "time"],+["stop", "rline", 3, 5, "none", null, "time"],+["stop", "rline", 4, 0, "none", null, "time"],+["stop", "rline", 4, 1, "none", null, "time"],+["stop", "rline", 4, 2, "none", null, "time"],+["stop", "rline", 4, 3, "none", null, "time"],+["stop", "rline", 4, 4, "none", null, "time"],+["stop", "rline", 4, 5, "none", null, "time"],+["stop", "rline", 5, 0, "none", null, "time"],+["stop", "rline", 5, 1, "none", null, "time"],+["stop", "rline", 5, 2, "none", null, "time"],+["stop", "rline", 5, 3, "none", null, "time"],+["stop", "rline", 5, 4, "none", null, "time"],+["stop", "rline", 5, 5, "none", null, "time"],+["stop", "stop", 0, 0, "none", null, "time"],+["stop", "stop", 0, 1, "none", null, "time"],+["stop", "stop", 0, 2, "none", null, "time"],+["stop", "stop", 0, 3, "none", null, "time"],+["stop", "stop", 0, 4, "none", null, "time"],+["stop", "stop", 0, 5, "none", null, "time"],+["stop", "stop", 1, 0, "none", null, "time"],+["stop", "stop", 1, 1, "none", null, "time"],+["stop", "stop", 1, 2, "none", null, "time"],+["stop", "stop", 1, 3, "none", null, "time"],+["stop", "stop", 1, 4, "none", null, "time"],+["stop", "stop", 1, 5, "none", null, "time"],+["stop", "stop", 2, 0, "none", null, "time"],+["stop", "stop", 2, 1, "none", null, "time"],+["stop", "stop", 2, 2, "none", null, "time"],+["stop", "stop", 2, 3, "none", null, "time"],+["stop", "stop", 2, 4, "none", null, "time"],+["stop", "stop", 2, 5, "none", null, "time"],+["stop", "stop", 3, 0, "none", null, "time"],+["stop", "stop", 3, 1, "none", null, "time"],+["stop", "stop", 3, 2, "none", null, "time"],+["stop", "stop", 3, 3, "none", null, "time"],+["stop", "stop", 3, 4, "none", null, "time"],+["stop", "stop", 3, 5, "none", null, "time"],+["stop", "stop", 4, 0, "none", null, "time"],+["stop", "stop", 4, 1, "none", null, "time"],+["stop", "stop", 4, 2, "none", null, "time"],+["stop", "stop", 4, 3, "none", null, "time"],+["stop", "stop", 4, 4, "none", null, "time"],+["stop", "stop", 4, 5, "none", null, "time"],+["stop", "stop", 5, 0, "none", null, "time"],+["stop", "stop", 5, 1, "none", null, "time"],+["stop", "stop", 5, 2, "none", null, "time"],+["stop", "stop", 5, 3, "none", null, "time"],+["stop", "stop", 5, 4, "none", null, "time"],+["stop", "stop", 5, 5, "none", null, "time"],+["stop", "counter", 0, 0, "none", null, "time"],+["stop", "counter", 0, 1, "none", null, "time"],+["stop", "counter", 0, 2, "none", null, "time"],+["stop", "counter", 0, 3, "none", null, "time"],+["stop", "counter", 0, 4, "none", null, "time"],+["stop", "counter", 0, 5, "none", null, "time"],+["stop", "counter", 1, 0, "none", null, "time"],+["stop", "counter", 1, 1, "none", null, "time"],+["stop", "counter", 1, 2, "none", null, "time"],+["stop", "counter", 1, 3, "none", null, "time"],+["stop", "counter", 1, 4, "none", null, "time"],+["stop", "counter", 1, 5, "none", null, "time"],+["stop", "counter", 2, 0, "none", null, "time"],+["stop", "counter", 2, 1, "none", null, "time"],+["stop", "counter", 2, 2, "none", null, "time"],+["stop", "counter", 2, 3, "none", null, "time"],+["stop", "counter", 2, 4, "none", null, "time"],+["stop", "counter", 2, 5, "none", null, "time"],+["stop", "counter", 3, 0, "none", null, "time"],+["stop", "counter", 3, 1, "none", null, "time"],+["stop", "counter", 3, 2, "none", null, "time"],+["stop", "counter", 3, 3, "none", null, "time"],+["stop", "counter", 3, 4, "none", null, "time"],+["stop", "counter", 3, 5, "none", null, "time"],+["stop", "counter", 4, 0, "none", null, "time"],+["stop", "counter", 4, 1, "none", null, "time"],+["stop", "counter", 4, 2, "none", null, "time"],+["stop", "counter", 4, 3, "none", null, "time"],+["stop", "counter", 4, 4, "none", null, "time"],+["stop", "counter", 4, 5, "none", null, "time"],+["stop", "counter", 5, 0, "none", null, "time"],+["stop", "counter", 5, 1, "none", null, "time"],+["stop", "counter", 5, 2, "none", null, "time"],+["stop", "counter", 5, 3, "none", null, "time"],+["stop", "counter", 5, 4, "none", null, "time"],+["stop", "counter", 5, 5, "none", null, "time"],+["stop", "delay", 0, 0, "B", 111, "touch"],+["stop", "delay", 0, 1, "B", 111, "touch"],+["stop", "delay", 0, 2, "B", 114, "touch"],+["stop", "delay", 0, 3, "B", 113, "touch"],+["stop", "delay", 0, 4, "B", 116, "touch"],+["stop", "delay", 0, 5, "B", 115, "touch"],+["stop", "delay", 1, 0, "B", 111, "touch"],+["stop", "delay", 1, 1, "B", 111, "touch"],+["stop", "delay", 1, 2, "B", 114, "touch"],+["stop", "delay", 1, 3, "B", 113, "touch"],+["stop", "delay", 1, 4, "B", 116, "touch"],+["stop", "delay", 1, 5, "B", 115, "touch"],+["stop", "delay", 2, 0, "B", 111, "touch"],+["stop", "delay", 2, 1, "B", 111, "touch"],+["stop", "delay", 2, 2, "B", 114, "touch"],+["stop", "delay", 2, 3, "B", 113, "touch"],+["stop", "delay", 2, 4, "B", 116, "touch"],+["stop", "delay", 2, 5, "B", 115, "touch"],+["stop", "delay", 3, 0, "B", 111, "touch"],+["stop", "delay", 3, 1, "B", 111, "touch"],+["stop", "delay", 3, 2, "B", 114, "touch"],+["stop", "delay", 3, 3, "B", 113, "touch"],+["stop", "delay", 3, 4, "B", 116, "touch"],+["stop", "delay", 3, 5, "B", 115, "touch"],+["stop", "delay", 4, 0, "B", 111, "touch"],+["stop", "delay", 4, 1, "B", 111, "touch"],+["stop", "delay", 4, 2, "B", 114, "touch"],+["stop", "delay", 4, 3, "B", 113, "touch"],+["stop", "delay", 4, 4, "B", 116, "touch"],+["stop", "delay", 4, 5, "B", 115, "touch"],+["stop", "delay", 5, 0, "B", 111, "touch"],+["stop", "delay", 5, 1, "B", 111, "touch"],+["stop", "delay", 5, 2, "B", 114, "touch"],+["stop", "delay", 5, 3, "B", 113, "touch"],+["stop", "delay", 5, 4, "B", 116, "touch"],+["stop", "delay", 5, 5, "B", 115, "touch"],+["stop", "retreat", 0, 0, "none", null, "time"],+["stop", "retreat", 0, 1, "none", null, "time"],+["stop", "retreat", 0, 2, "none", null, "time"],+["stop", "retreat", 0, 3, "none", null, "time"],+["stop", "retreat", 0, 4, "none", null, "time"],+["stop", "retreat", 0, 5, "none", null, "time"],+["stop", "retreat", 1, 0, "none", null, "time"],+["stop", "retreat", 1, 1, "none", null, "time"],+["stop", "retreat", 1, 2, "none", null, "time"],+["stop", "retreat", 1, 3, "none", null, "time"],+["stop", "retreat", 1, 4, "none", null, "time"],+["stop", "retreat", 1, 5, "none", null, "time"],+["stop", "retreat", 2, 0, "none", null, "time"],+["stop", "retreat", 2, 1, "none", null, "time"],+["stop", "retreat", 2, 2, "none", null, "time"],+["stop", "retreat", 2, 3, "none", null, "time"],+["stop", "retreat", 2, 4, "none", null, "time"],+["stop", "retreat", 2, 5, "none", null, "time"],+["stop", "retreat", 3, 0, "none", null, "time"],+["stop", "retreat", 3, 1, "none", null, "time"],+["stop", "retreat", 3, 2, "none", null, "time"],+["stop", "retreat", 3, 3, "none", null, "time"],+["stop", "retreat", 3, 4, "none", null, "time"],+["stop", "retreat", 3, 5, "none", null, "time"],+["stop", "retreat", 4, 0, "none", null, "time"],+["stop", "retreat", 4, 1, "none", null, "time"],+["stop", "retreat", 4, 2, "none", null, "time"],+["stop", "retreat", 4, 3, "none", null, "time"],+["stop", "retreat", 4, 4, "none", null, "time"],+["stop", "retreat", 4, 5, "none", null, "time"],+["stop", "retreat", 5, 0, "none", null, "time"],+["stop", "retreat", 5, 1, "none", null, "time"],+["stop", "retreat", 5, 2, "none", null, "time"],+["stop", "retreat", 5, 3, "none", null, "time"],+["stop", "retreat", 5, 4, "none", null, "time"],+["stop", "retreat", 5, 5, "none", null, "time"],+["stop", "draw", 0, 0, "none", null, "time"],+["stop", "draw", 0, 1, "none", null, "time"],+["stop", "draw", 0, 2, "none", null, "time"],+["stop", "draw", 0, 3, "none", null, "time"],+["stop", "draw", 0, 4, "none", null, "time"],+["stop", "draw", 0, 5, "none", null, "time"],+["stop", "draw", 1, 0, "none", null, "time"],+["stop", "draw", 1, 1, "none", null, "time"],+["stop", "draw", 1, 2, "none", null, "time"],+["stop", "draw", 1, 3, "none", null, "time"],+["stop", "draw", 1, 4, "none", null, "time"],+["stop", "draw", 1, 5, "none", null, "time"],+["stop", "draw", 2, 0, "none", null, "time"],+["stop", "draw", 2, 1, "none", null, "time"],+["stop", "draw", 2, 2, "none", null, "time"],+["stop", "draw", 2, 3, "none", null, "time"],+["stop", "draw", 2, 4, "none", null, "time"],+["stop", "draw", 2, 5, "none", null, "time"],+["stop", "draw", 3, 0, "none", null, "time"],+["stop", "draw", 3, 1, "none", null, "time"],+["stop", "draw", 3, 2, "none", null, "time"],+["stop", "draw", 3, 3, "none", null, "time"],+["stop", "draw", 3, 4, "none", null, "time"],+["stop", "draw", 3, 5, "none", null, "time"],+["stop", "draw", 4, 0, "none", null, "time"],+["stop", "draw", 4, 1, "none", null, "time"],+["stop", "draw", 4, 2, "none", null, "time"],+["stop", "draw", 4, 3, "none", null, "time"],+["stop", "draw", 4, 4, "none", null, "time"],+["stop", "draw", 4, 5, "none", null, "time"],+["stop", "draw", 5, 0, "none", null, "time"],+["stop", "draw", 5, 1, "none", null, "time"],+["stop", "draw", 5, 2, "none", null, "time"],+["stop", "draw", 5, 3, "none", null, "time"],+["stop", "draw", 5, 4, "none", null, "time"],+["stop", "draw", 5, 5, "none", null, "time"],+["counter", "lunge", 0, 0, "A", 55, "touch"],+["counter", "lunge", 0, 1, "A", 54, "touch"],+["counter", "lunge", 0, 2, "A", 57, "touch"],+["counter", "lunge", 0, 3, "A", 56, "touch"],+["counter", "lunge", 0, 4, "A", 56, "touch"],+["counter", "lunge", 0, 5, "A", 58, "touch"],+["counter", "lunge", 1, 0, "A", 55, "touch"],+["counter", "lunge", 1, 1, "A", 54, "touch"],+["counter", "lunge", 1, 2, "A", 57, "touch"],+["counter", "lunge", 1, 3, "A", 56, "touch"],+["counter", "lunge", 1, 4, "A", 56, "touch"],+["counter", "lunge", 1, 5, "A", 58, "touch"],+["counter", "lunge", 2, 0, "A", 55, "touch"],+["counter", "lunge", 2, 1, "A", 54, "touch"],+["counter", "lunge", 2, 2, "A", 57, "touch"],+["counter", "lunge", 2, 3, "A", 56, "touch"],+["counter", "lunge", 2, 4, "A", 56, "touch"],+["counter", "lunge", 2, 5, "A", 58, "touch"],+["counter", "lunge", 3, 0, "A", 55, "touch"],+["counter", "lunge", 3, 1, "A", 54, "touch"],+["counter", "lunge", 3, 2, "A", 57, "touch"],+["counter", "lunge", 3, 3, "A", 56, "touch"],+["counter", "lunge", 3, 4, "A", 56, "touch"],+["counter", "lunge", 3, 5, "A", 58, "touch"],+["counter", "lunge", 4, 0, "A", 55, "touch"],+["counter", "lunge", 4, 1, "A", 54, "touch"],+["counter", "lunge", 4, 2, "A", 57, "touch"],+["counter", "lunge", 4, 3, "A", 56, "touch"],+["counter", "lunge", 4, 4, "A", 56, "touch"],+["counter", "lunge", 4, 5, "A", 58, "touch"],+["counter", "lunge", 5, 0, "A", 55, "touch"],+["counter", "lunge", 5, 1, "A", 54, "touch"],+["counter", "lunge", 5, 2, "A", 57, "touch"],+["counter", "lunge", 5, 3, "A", 56, "touch"],+["counter", "lunge", 5, 4, "A", 56, "touch"],+["counter", "lunge", 5, 5, "A", 58, "touch"],+["counter", "low", 0, 0, "none", null, "time"],+["counter", "low", 0, 1, "A", 53, "touch"],+["counter", "low", 0, 2, "none", null, "time"],+["counter", "low", 0, 3, "A", 55, "touch"],+["counter", "low", 0, 4, "A", 55, "touch"],+["counter", "low", 0, 5, "A", 57, "touch"],+["counter", "low", 1, 0, "none", null, "time"],+["counter", "low", 1, 1, "A", 53, "touch"],+["counter", "low", 1, 2, "none", null, "time"],+["counter", "low", 1, 3, "A", 55, "touch"],+["counter", "low", 1, 4, "A", 55, "touch"],+["counter", "low", 1, 5, "A", 57, "touch"],+["counter", "low", 2, 0, "none", null, "time"],+["counter", "low", 2, 1, "A", 53, "touch"],+["counter", "low", 2, 2, "none", null, "time"],+["counter", "low", 2, 3, "A", 55, "touch"],+["counter", "low", 2, 4, "A", 55, "touch"],+["counter", "low", 2, 5, "A", 57, "touch"],+["counter", "low", 3, 0, "none", null, "time"],+["counter", "low", 3, 1, "A", 53, "touch"],+["counter", "low", 3, 2, "none", null, "time"],+["counter", "low", 3, 3, "A", 55, "touch"],+["counter", "low", 3, 4, "A", 55, "touch"],+["counter", "low", 3, 5, "A", 57, "touch"],+["counter", "low", 4, 0, "none", null, "time"],+["counter", "low", 4, 1, "A", 53, "touch"],+["counter", "low", 4, 2, "none", null, "time"],+["counter", "low", 4, 3, "A", 55, "touch"],+["counter", "low", 4, 4, "A", 55, "touch"],+["counter", "low", 4, 5, "A", 57, "touch"],+["counter", "low", 5, 0, "none", null, "time"],+["counter", "low", 5, 1, "A", 53, "touch"],+["counter", "low", 5, 2, "none", null, "time"],+["counter", "low", 5, 3, "A", 55, "touch"],+["counter", "low", 5, 4, "A", 55, "touch"],+["counter", "low", 5, 5, "A", 57, "touch"],+["counter", "line", 0, 0, "none", null, "time"],+["counter", "line", 0, 1, "none", null, "time"],+["counter", "line", 0, 2, "none", null, "time"],+["counter", "line", 0, 3, "none", null, "time"],+["counter", "line", 0, 4, "none", null, "time"],+["counter", "line", 0, 5, "none", null, "time"],+["counter", "line", 1, 0, "none", null, "time"],+["counter", "line", 1, 1, "none", null, "time"],+["counter", "line", 1, 2, "none", null, "time"],+["counter", "line", 1, 3, "none", null, "time"],+["counter", "line", 1, 4, "none", null, "time"],+["counter", "line", 1, 5, "none", null, "time"],+["counter", "line", 2, 0, "none", null, "time"],+["counter", "line", 2, 1, "none", null, "time"],+["counter", "line", 2, 2, "none", null, "time"],+["counter", "line", 2, 3, "none", null, "time"],+["counter", "line", 2, 4, "none", null, "time"],+["counter", "line", 2, 5, "none", null, "time"],+["counter", "line", 3, 0, "none", null, "time"],+["counter", "line", 3, 1, "none", null, "time"],+["counter", "line", 3, 2, "none", null, "time"],+["counter", "line", 3, 3, "none", null, "time"],+["counter", "line", 3, 4, "none", null, "time"],+["counter", "line", 3, 5, "none", null, "time"],+["counter", "line", 4, 0, "none", null, "time"],+["counter", "line", 4, 1, "none", null, "time"],+["counter", "line", 4, 2, "none", null, "time"],+["counter", "line", 4, 3, "none", null, "time"],+["counter", "line", 4, 4, "none", null, "time"],+["counter", "line", 4, 5, "none", null, "time"],+["counter", "line", 5, 0, "none", null, "time"],+["counter", "line", 5, 1, "none", null, "time"],+["counter", "line", 5, 2, "none", null, "time"],+["counter", "line", 5, 3, "none", null, "time"],+["counter", "line", 5, 4, "none", null, "time"],+["counter", "line", 5, 5, "none", null, "time"],+["counter", "rline", 0, 0, "none", null, "time"],+["counter", "rline", 0, 1, "none", null, "time"],+["counter", "rline", 0, 2, "none", null, "time"],+["counter", "rline", 0, 3, "none", null, "time"],+["counter", "rline", 0, 4, "none", null, "time"],+["counter", "rline", 0, 5, "none", null, "time"],+["counter", "rline", 1, 0, "none", null, "time"],+["counter", "rline", 1, 1, "none", null, "time"],+["counter", "rline", 1, 2, "none", null, "time"],+["counter", "rline", 1, 3, "none", null, "time"],+["counter", "rline", 1, 4, "none", null, "time"],+["counter", "rline", 1, 5, "none", null, "time"],+["counter", "rline", 2, 0, "none", null, "time"],+["counter", "rline", 2, 1, "none", null, "time"],+["counter", "rline", 2, 2, "none", null, "time"],+["counter", "rline", 2, 3, "none", null, "time"],+["counter", "rline", 2, 4, "none", null, "time"],+["counter", "rline", 2, 5, "none", null, "time"],+["counter", "rline", 3, 0, "none", null, "time"],+["counter", "rline", 3, 1, "none", null, "time"],+["counter", "rline", 3, 2, "none", null, "time"],+["counter", "rline", 3, 3, "none", null, "time"],+["counter", "rline", 3, 4, "none", null, "time"],+["counter", "rline", 3, 5, "none", null, "time"],+["counter", "rline", 4, 0, "none", null, "time"],+["counter", "rline", 4, 1, "none", null, "time"],+["counter", "rline", 4, 2, "none", null, "time"],+["counter", "rline", 4, 3, "none", null, "time"],+["counter", "rline", 4, 4, "none", null, "time"],+["counter", "rline", 4, 5, "none", null, "time"],+["counter", "rline", 5, 0, "none", null, "time"],+["counter", "rline", 5, 1, "none", null, "time"],+["counter", "rline", 5, 2, "none", null, "time"],+["counter", "rline", 5, 3, "none", null, "time"],+["counter", "rline", 5, 4, "none", null, "time"],+["counter", "rline", 5, 5, "none", null, "time"],+["counter", "stop", 0, 0, "none", null, "time"],+["counter", "stop", 0, 1, "none", null, "time"],+["counter", "stop", 0, 2, "none", null, "time"],+["counter", "stop", 0, 3, "none", null, "time"],+["counter", "stop", 0, 4, "none", null, "time"],+["counter", "stop", 0, 5, "none", null, "time"],+["counter", "stop", 1, 0, "none", null, "time"],+["counter", "stop", 1, 1, "none", null, "time"],+["counter", "stop", 1, 2, "none", null, "time"],+["counter", "stop", 1, 3, "none", null, "time"],+["counter", "stop", 1, 4, "none", null, "time"],+["counter", "stop", 1, 5, "none", null, "time"],+["counter", "stop", 2, 0, "none", null, "time"],+["counter", "stop", 2, 1, "none", null, "time"],+["counter", "stop", 2, 2, "none", null, "time"],+["counter", "stop", 2, 3, "none", null, "time"],+["counter", "stop", 2, 4, "none", null, "time"],+["counter", "stop", 2, 5, "none", null, "time"],+["counter", "stop", 3, 0, "none", null, "time"],+["counter", "stop", 3, 1, "none", null, "time"],+["counter", "stop", 3, 2, "none", null, "time"],+["counter", "stop", 3, 3, "none", null, "time"],+["counter", "stop", 3, 4, "none", null, "time"],+["counter", "stop", 3, 5, "none", null, "time"],+["counter", "stop", 4, 0, "none", null, "time"],+["counter", "stop", 4, 1, "none", null, "time"],+["counter", "stop", 4, 2, "none", null, "time"],+["counter", "stop", 4, 3, "none", null, "time"],+["counter", "stop", 4, 4, "none", null, "time"],+["counter", "stop", 4, 5, "none", null, "time"],+["counter", "stop", 5, 0, "none", null, "time"],+["counter", "stop", 5, 1, "none", null, "time"],+["counter", "stop", 5, 2, "none", null, "time"],+["counter", "stop", 5, 3, "none", null, "time"],+["counter", "stop", 5, 4, "none", null, "time"],+["counter", "stop", 5, 5, "none", null, "time"],+["counter", "counter", 0, 0, "none", null, "time"],+["counter", "counter", 0, 1, "none", null, "time"],+["counter", "counter", 0, 2, "none", null, "time"],+["counter", "counter", 0, 3, "none", null, "time"],+["counter", "counter", 0, 4, "none", null, "time"],+["counter", "counter", 0, 5, "none", null, "time"],+["counter", "counter", 1, 0, "none", null, "time"],+["counter", "counter", 1, 1, "none", null, "time"],+["counter", "counter", 1, 2, "none", null, "time"],+["counter", "counter", 1, 3, "none", null, "time"],+["counter", "counter", 1, 4, "none", null, "time"],+["counter", "counter", 1, 5, "none", null, "time"],+["counter", "counter", 2, 0, "none", null, "time"],+["counter", "counter", 2, 1, "none", null, "time"],+["counter", "counter", 2, 2, "none", null, "time"],+["counter", "counter", 2, 3, "none", null, "time"],+["counter", "counter", 2, 4, "none", null, "time"],+["counter", "counter", 2, 5, "none", null, "time"],+["counter", "counter", 3, 0, "none", null, "time"],+["counter", "counter", 3, 1, "none", null, "time"],+["counter", "counter", 3, 2, "none", null, "time"],+["counter", "counter", 3, 3, "none", null, "time"],+["counter", "counter", 3, 4, "none", null, "time"],+["counter", "counter", 3, 5, "none", null, "time"],+["counter", "counter", 4, 0, "none", null, "time"],+["counter", "counter", 4, 1, "none", null, "time"],+["counter", "counter", 4, 2, "none", null, "time"],+["counter", "counter", 4, 3, "none", null, "time"],+["counter", "counter", 4, 4, "none", null, "time"],+["counter", "counter", 4, 5, "none", null, "time"],+["counter", "counter", 5, 0, "none", null, "time"],+["counter", "counter", 5, 1, "none", null, "time"],+["counter", "counter", 5, 2, "none", null, "time"],+["counter", "counter", 5, 3, "none", null, "time"],+["counter", "counter", 5, 4, "none", null, "time"],+["counter", "counter", 5, 5, "none", null, "time"],+["counter", "delay", 0, 0, "A", 92, "touch"],+["counter", "delay", 0, 1, "A", 95, "touch"],+["counter", "delay", 0, 2, "A", 93, "touch"],+["counter", "delay", 0, 3, "A", 96, "touch"],+["counter", "delay", 0, 4, "A", 95, "touch"],+["counter", "delay", 0, 5, "B", 228, "touch"],+["counter", "delay", 1, 0, "A", 92, "touch"],+["counter", "delay", 1, 1, "A", 95, "touch"],+["counter", "delay", 1, 2, "A", 93, "touch"],+["counter", "delay", 1, 3, "A", 96, "touch"],+["counter", "delay", 1, 4, "A", 95, "touch"],+["counter", "delay", 1, 5, "B", 228, "touch"],+["counter", "delay", 2, 0, "A", 92, "touch"],+["counter", "delay", 2, 1, "A", 95, "touch"],+["counter", "delay", 2, 2, "A", 93, "touch"],+["counter", "delay", 2, 3, "A", 96, "touch"],+["counter", "delay", 2, 4, "A", 95, "touch"],+["counter", "delay", 2, 5, "B", 228, "touch"],+["counter", "delay", 3, 0, "A", 92, "touch"],+["counter", "delay", 3, 1, "A", 95, "touch"],+["counter", "delay", 3, 2, "A", 93, "touch"],+["counter", "delay", 3, 3, "A", 96, "touch"],+["counter", "delay", 3, 4, "A", 95, "touch"],+["counter", "delay", 3, 5, "B", 228, "touch"],+["counter", "delay", 4, 0, "A", 92, "touch"],+["counter", "delay", 4, 1, "A", 95, "touch"],+["counter", "delay", 4, 2, "A", 93, "touch"],+["counter", "delay", 4, 3, "A", 96, "touch"],+["counter", "delay", 4, 4, "A", 95, "touch"],+["counter", "delay", 4, 5, "B", 228, "touch"],+["counter", "delay", 5, 0, "A", 92, "touch"],+["counter", "delay", 5, 1, "A", 95, "touch"],+["counter", "delay", 5, 2, "A", 93, "touch"],+["counter", "delay", 5, 3, "A", 96, "touch"],+["counter", "delay", 5, 4, "A", 95, "touch"],+["counter", "delay", 5, 5, "B", 228, "touch"],+["counter", "retreat", 0, 0, "none", null, "time"],+["counter", "retreat", 0, 1, "none", null, "time"],+["counter", "retreat", 0, 2, "none", null, "time"],+["counter", "retreat", 0, 3, "none", null, "time"],+["counter", "retreat", 0, 4, "none", null, "time"],+["counter", "retreat", 0, 5, "none", null, "time"],+["counter", "retreat", 1, 0, "none", null, "time"],+["counter", "retreat", 1, 1, "none", null, "time"],+["counter", "retreat", 1, 2, "none", null, "time"],+["counter", "retreat", 1, 3, "none", null, "time"],+["counter", "retreat", 1, 4, "none", null, "time"],+["counter", "retreat", 1, 5, "none", null, "time"],+["counter", "retreat", 2, 0, "none", null, "time"],+["counter", "retreat", 2, 1, "none", null, "time"],+["counter", "retreat", 2, 2, "none", null, "time"],+["counter", "retreat", 2, 3, "none", null, "time"],+["counter", "retreat", 2, 4, "none", null, "time"],+["counter", "retreat", 2, 5, "none", null, "time"],+["counter", "retreat", 3, 0, "none", null, "time"],+["counter", "retreat", 3, 1, "none", null, "time"],+["counter", "retreat", 3, 2, "none", null, "time"],+["counter", "retreat", 3, 3, "none", null, "time"],+["counter", "retreat", 3, 4, "none", null, "time"],+["counter", "retreat", 3, 5, "none", null, "time"],+["counter", "retreat", 4, 0, "none", null, "time"],+["counter", "retreat", 4, 1, "none", null, "time"],+["counter", "retreat", 4, 2, "none", null, "time"],+["counter", "retreat", 4, 3, "none", null, "time"],+["counter", "retreat", 4, 4, "none", null, "time"],+["counter", "retreat", 4, 5, "none", null, "time"],+["counter", "retreat", 5, 0, "none", null, "time"],+["counter", "retreat", 5, 1, "none", null, "time"],+["counter", "retreat", 5, 2, "none", null, "time"],+["counter", "retreat", 5, 3, "none", null, "time"],+["counter", "retreat", 5, 4, "none", null, "time"],+["counter", "retreat", 5, 5, "none", null, "time"],+["counter", "draw", 0, 0, "B", 94, "touch"],+["counter", "draw", 0, 1, "B", 95, "touch"],+["counter", "draw", 0, 2, "B", 95, "touch"],+["counter", "draw", 0, 3, "B", 92, "touch"],+["counter", "draw", 0, 4, "B", 92, "touch"],+["counter", "draw", 0, 5, "B", 100, "touch"],+["counter", "draw", 1, 0, "B", 94, "touch"],+["counter", "draw", 1, 1, "B", 95, "touch"],+["counter", "draw", 1, 2, "B", 95, "touch"],+["counter", "draw", 1, 3, "B", 92, "touch"],+["counter", "draw", 1, 4, "B", 92, "touch"],+["counter", "draw", 1, 5, "B", 100, "touch"],+["counter", "draw", 2, 0, "B", 94, "touch"],+["counter", "draw", 2, 1, "B", 95, "touch"],+["counter", "draw", 2, 2, "B", 95, "touch"],+["counter", "draw", 2, 3, "B", 92, "touch"],+["counter", "draw", 2, 4, "B", 92, "touch"],+["counter", "draw", 2, 5, "B", 100, "touch"],+["counter", "draw", 3, 0, "B", 94, "touch"],+["counter", "draw", 3, 1, "B", 95, "touch"],+["counter", "draw", 3, 2, "B", 95, "touch"],+["counter", "draw", 3, 3, "B", 92, "touch"],+["counter", "draw", 3, 4, "B", 92, "touch"],+["counter", "draw", 3, 5, "B", 100, "touch"],+["counter", "draw", 4, 0, "B", 94, "touch"],+["counter", "draw", 4, 1, "B", 95, "touch"],+["counter", "draw", 4, 2, "B", 95, "touch"],+["counter", "draw", 4, 3, "B", 92, "touch"],+["counter", "draw", 4, 4, "B", 92, "touch"],+["counter", "draw", 4, 5, "B", 100, "touch"],+["counter", "draw", 5, 0, "B", 94, "touch"],+["counter", "draw", 5, 1, "B", 95, "touch"],+["counter", "draw", 5, 2, "B", 95, "touch"],+["counter", "draw", 5, 3, "B", 92, "touch"],+["counter", "draw", 5, 4, "B", 92, "touch"],+["counter", "draw", 5, 5, "B", 100, "touch"],+["delay", "lunge", 0, 0, "A", 69, "touch"],+["delay", "lunge", 0, 1, "AB", 64, "touch"],+["delay", "lunge", 0, 2, "A", 69, "touch"],+["delay", "lunge", 0, 3, "A", 69, "touch"],+["delay", "lunge", 0, 4, "A", 69, "touch"],+["delay", "lunge", 0, 5, "A", 69, "touch"],+["delay", "lunge", 1, 0, "A", 70, "touch"],+["delay", "lunge", 1, 1, "AB", 65, "touch"],+["delay", "lunge", 1, 2, "A", 70, "touch"],+["delay", "lunge", 1, 3, "A", 70, "touch"],+["delay", "lunge", 1, 4, "A", 70, "touch"],+["delay", "lunge", 1, 5, "A", 70, "touch"],+["delay", "lunge", 2, 0, "A", 71, "touch"],+["delay", "lunge", 2, 1, "AB", 66, "touch"],+["delay", "lunge", 2, 2, "A", 71, "touch"],+["delay", "lunge", 2, 3, "A", 71, "touch"],+["delay", "lunge", 2, 4, "AB", 67, "touch"],+["delay", "lunge", 2, 5, "A", 71, "touch"],+["delay", "lunge", 3, 0, "A", 72, "touch"],+["delay", "lunge", 3, 1, "AB", 67, "touch"],+["delay", "lunge", 3, 2, "AB", 68, "touch"],+["delay", "lunge", 3, 3, "AB", 67, "touch"],+["delay", "lunge", 3, 4, "AB", 68, "touch"],+["delay", "lunge", 3, 5, "A", 72, "touch"],+["delay", "lunge", 4, 0, "AB", 68, "touch"],+["delay", "lunge", 4, 1, "B", 68, "touch"],+["delay", "lunge", 4, 2, "AB", 68, "touch"],+["delay", "lunge", 4, 3, "AB", 68, "touch"],+["delay", "lunge", 4, 4, "AB", 69, "touch"],+["delay", "lunge", 4, 5, "AB", 68, "touch"],+["delay", "lunge", 5, 0, "AB", 69, "touch"],+["delay", "lunge", 5, 1, "B", 68, "touch"],+["delay", "lunge", 5, 2, "AB", 70, "touch"],+["delay", "lunge", 5, 3, "AB", 69, "touch"],+["delay", "lunge", 5, 4, "AB", 70, "touch"],+["delay", "lunge", 5, 5, "AB", 69, "touch"],+["delay", "low", 0, 0, "A", 69, "touch"],+["delay", "low", 0, 1, "A", 69, "touch"],+["delay", "low", 0, 2, "A", 68, "touch"],+["delay", "low", 0, 3, "A", 69, "touch"],+["delay", "low", 0, 4, "A", 69, "touch"],+["delay", "low", 0, 5, "A", 69, "touch"],+["delay", "low", 1, 0, "A", 69, "touch"],+["delay", "low", 1, 1, "A", 70, "touch"],+["delay", "low", 1, 2, "A", 70, "touch"],+["delay", "low", 1, 3, "A", 70, "touch"],+["delay", "low", 1, 4, "A", 70, "touch"],+["delay", "low", 1, 5, "A", 70, "touch"],+["delay", "low", 2, 0, "A", 70, "touch"],+["delay", "low", 2, 1, "A", 70, "touch"],+["delay", "low", 2, 2, "A", 71, "touch"],+["delay", "low", 2, 3, "A", 71, "touch"],+["delay", "low", 2, 4, "A", 71, "touch"],+["delay", "low", 2, 5, "A", 71, "touch"],+["delay", "low", 3, 0, "A", 71, "touch"],+["delay", "low", 3, 1, "A", 72, "touch"],+["delay", "low", 3, 2, "A", 71, "touch"],+["delay", "low", 3, 3, "A", 72, "touch"],+["delay", "low", 3, 4, "A", 72, "touch"],+["delay", "low", 3, 5, "A", 72, "touch"],+["delay", "low", 4, 0, "A", 72, "touch"],+["delay", "low", 4, 1, "A", 72, "touch"],+["delay", "low", 4, 2, "A", 72, "touch"],+["delay", "low", 4, 3, "A", 73, "touch"],+["delay", "low", 4, 4, "A", 72, "touch"],+["delay", "low", 4, 5, "A", 73, "touch"],+["delay", "low", 5, 0, "A", 73, "touch"],+["delay", "low", 5, 1, "A", 73, "touch"],+["delay", "low", 5, 2, "A", 73, "touch"],+["delay", "low", 5, 3, "A", 74, "touch"],+["delay", "low", 5, 4, "A", 74, "touch"],+["delay", "low", 5, 5, "A", 73, "touch"],+["delay", "line", 0, 0, "A", 109, "touch"],+["delay", "line", 0, 1, "A", 107, "touch"],+["delay", "line", 0, 2, "A", 108, "touch"],+["delay", "line", 0, 3, "A", 106, "touch"],+["delay", "line", 0, 4, "A", 107, "touch"],+["delay", "line", 0, 5, "A", 107, "touch"],+["delay", "line", 1, 0, "A", 109, "touch"],+["delay", "line", 1, 1, "A", 108, "touch"],+["delay", "line", 1, 2, "A", 108, "touch"],+["delay", "line", 1, 3, "A", 108, "touch"],+["delay", "line", 1, 4, "A", 108, "touch"],+["delay", "line", 1, 5, "A", 108, "touch"],+["delay", "line", 2, 0, "A", 109, "touch"],+["delay", "line", 2, 1, "A", 109, "touch"],+["delay", "line", 2, 2, "A", 108, "touch"],+["delay", "line", 2, 3, "A", 109, "touch"],+["delay", "line", 2, 4, "A", 110, "touch"],+["delay", "line", 2, 5, "A", 109, "touch"],+["delay", "line", 3, 0, "A", 110, "touch"],+["delay", "line", 3, 1, "A", 110, "touch"],+["delay", "line", 3, 2, "A", 109, "touch"],+["delay", "line", 3, 3, "A", 110, "touch"],+["delay", "line", 3, 4, "A", 110, "touch"],+["delay", "line", 3, 5, "A", 110, "touch"],+["delay", "line", 4, 0, "A", 117, "touch"],+["delay", "line", 4, 1, "A", 111, "touch"],+["delay", "line", 4, 2, "A", 110, "touch"],+["delay", "line", 4, 3, "A", 112, "touch"],+["delay", "line", 4, 4, "A", 111, "touch"],+["delay", "line", 4, 5, "A", 110, "touch"],+["delay", "line", 5, 0, "A", 113, "touch"],+["delay", "line", 5, 1, "A", 112, "touch"],+["delay", "line", 5, 2, "A", 112, "touch"],+["delay", "line", 5, 3, "A", 112, "touch"],+["delay", "line", 5, 4, "A", 112, "touch"],+["delay", "line", 5, 5, "A", 112, "touch"],+["delay", "rline", 0, 0, "A", 107, "touch"],+["delay", "rline", 0, 1, "A", 107, "touch"],+["delay", "rline", 0, 2, "A", 107, "touch"],+["delay", "rline", 0, 3, "A", 107, "touch"],+["delay", "rline", 0, 4, "A", 107, "touch"],+["delay", "rline", 0, 5, "A", 107, "touch"],+["delay", "rline", 1, 0, "A", 116, "touch"],+["delay", "rline", 1, 1, "A", 116, "touch"],+["delay", "rline", 1, 2, "A", 116, "touch"],+["delay", "rline", 1, 3, "A", 116, "touch"],+["delay", "rline", 1, 4, "A", 116, "touch"],+["delay", "rline", 1, 5, "A", 116, "touch"],+["delay", "rline", 2, 0, "A", 150, "touch"],+["delay", "rline", 2, 1, "A", 150, "touch"],+["delay", "rline", 2, 2, "A", 150, "touch"],+["delay", "rline", 2, 3, "A", 150, "touch"],+["delay", "rline", 2, 4, "A", 150, "touch"],+["delay", "rline", 2, 5, "A", 150, "touch"],+["delay", "rline", 3, 0, "none", null, "time"],+["delay", "rline", 3, 1, "none", null, "time"],+["delay", "rline", 3, 2, "none", null, "time"],+["delay", "rline", 3, 3, "none", null, "time"],+["delay", "rline", 3, 4, "none", null, "time"],+["delay", "rline", 3, 5, "none", null, "time"],+["delay", "rline", 4, 0, "none", null, "time"],+["delay", "rline", 4, 1, "none", null, "time"],+["delay", "rline", 4, 2, "none", null, "time"],+["delay", "rline", 4, 3, "none", null, "time"],+["delay", "rline", 4, 4, "none", null, "time"],+["delay", "rline", 4, 5, "none", null, "time"],+["delay", "rline", 5, 0, "A", 149, "touch"],+["delay", "rline", 5, 1, "A", 149, "touch"],+["delay", "rline", 5, 2, "A", 149, "touch"],+["delay", "rline", 5, 3, "A", 149, "touch"],+["delay", "rline", 5, 4, "A", 149, "touch"],+["delay", "rline", 5, 5, "A", 149, "touch"],+["delay", "stop", 0, 0, "A", 112, "touch"],+["delay", "stop", 0, 1, "A", 112, "touch"],+["delay", "stop", 0, 2, "A", 112, "touch"],+["delay", "stop", 0, 3, "A", 112, "touch"],+["delay", "stop", 0, 4, "A", 112, "touch"],+["delay", "stop", 0, 5, "A", 112, "touch"],+["delay", "stop", 1, 0, "A", 110, "touch"],+["delay", "stop", 1, 1, "A", 110, "touch"],+["delay", "stop", 1, 2, "A", 110, "touch"],+["delay", "stop", 1, 3, "A", 110, "touch"],+["delay", "stop", 1, 4, "A", 110, "touch"],+["delay", "stop", 1, 5, "A", 110, "touch"],+["delay", "stop", 2, 0, "A", 115, "touch"],+["delay", "stop", 2, 1, "A", 115, "touch"],+["delay", "stop", 2, 2, "A", 115, "touch"],+["delay", "stop", 2, 3, "A", 115, "touch"],+["delay", "stop", 2, 4, "A", 115, "touch"],+["delay", "stop", 2, 5, "A", 115, "touch"],+["delay", "stop", 3, 0, "A", 112, "touch"],+["delay", "stop", 3, 1, "A", 112, "touch"],+["delay", "stop", 3, 2, "A", 112, "touch"],+["delay", "stop", 3, 3, "A", 112, "touch"],+["delay", "stop", 3, 4, "A", 112, "touch"],+["delay", "stop", 3, 5, "A", 112, "touch"],+["delay", "stop", 4, 0, "A", 116, "touch"],+["delay", "stop", 4, 1, "A", 116, "touch"],+["delay", "stop", 4, 2, "A", 116, "touch"],+["delay", "stop", 4, 3, "A", 116, "touch"],+["delay", "stop", 4, 4, "A", 116, "touch"],+["delay", "stop", 4, 5, "A", 116, "touch"],+["delay", "stop", 5, 0, "A", 115, "touch"],+["delay", "stop", 5, 1, "A", 115, "touch"],+["delay", "stop", 5, 2, "A", 115, "touch"],+["delay", "stop", 5, 3, "A", 115, "touch"],+["delay", "stop", 5, 4, "A", 115, "touch"],+["delay", "stop", 5, 5, "A", 115, "touch"],+["delay", "counter", 0, 0, "B", 92, "touch"],+["delay", "counter", 0, 1, "B", 92, "touch"],+["delay", "counter", 0, 2, "B", 92, "touch"],+["delay", "counter", 0, 3, "B", 92, "touch"],+["delay", "counter", 0, 4, "B", 92, "touch"],+["delay", "counter", 0, 5, "B", 92, "touch"],+["delay", "counter", 1, 0, "B", 95, "touch"],+["delay", "counter", 1, 1, "B", 95, "touch"],+["delay", "counter", 1, 2, "B", 95, "touch"],+["delay", "counter", 1, 3, "B", 95, "touch"],+["delay", "counter", 1, 4, "B", 95, "touch"],+["delay", "counter", 1, 5, "B", 95, "touch"],+["delay", "counter", 2, 0, "B", 93, "touch"],+["delay", "counter", 2, 1, "B", 93, "touch"],+["delay", "counter", 2, 2, "B", 93, "touch"],+["delay", "counter", 2, 3, "B", 93, "touch"],+["delay", "counter", 2, 4, "B", 93, "touch"],+["delay", "counter", 2, 5, "B", 93, "touch"],+["delay", "counter", 3, 0, "B", 95, "touch"],+["delay", "counter", 3, 1, "B", 95, "touch"],+["delay", "counter", 3, 2, "B", 95, "touch"],+["delay", "counter", 3, 3, "B", 95, "touch"],+["delay", "counter", 3, 4, "B", 95, "touch"],+["delay", "counter", 3, 5, "B", 95, "touch"],+["delay", "counter", 4, 0, "B", 96, "touch"],+["delay", "counter", 4, 1, "B", 96, "touch"],+["delay", "counter", 4, 2, "B", 96, "touch"],+["delay", "counter", 4, 3, "B", 96, "touch"],+["delay", "counter", 4, 4, "B", 96, "touch"],+["delay", "counter", 4, 5, "B", 96, "touch"],+["delay", "counter", 5, 0, "B", 99, "touch"],+["delay", "counter", 5, 1, "B", 99, "touch"],+["delay", "counter", 5, 2, "B", 99, "touch"],+["delay", "counter", 5, 3, "B", 99, "touch"],+["delay", "counter", 5, 4, "B", 99, "touch"],+["delay", "counter", 5, 5, "B", 99, "touch"],+["delay", "delay", 0, 0, "A", 285, "touch"],+["delay", "delay", 0, 1, "none", null, "time"],+["delay", "delay", 0, 2, "B", 226, "touch"],+["delay", "delay", 0, 3, "none", null, "time"],+["delay", "delay", 0, 4, "none", null, "time"],+["delay", "delay", 0, 5, "none", null, "time"],+["delay", "delay", 1, 0, "none", null, "time"],+["delay", "delay", 1, 1, "A", 209, "touch"],+["delay", "delay", 1, 2, "none", null, "time"],+["delay", "delay", 1, 3, "none", null, "time"],+["delay", "delay", 1, 4, "A", 222, "touch"],+["delay", "delay", 1, 5, "A", 219, "touch"],+["delay", "delay", 2, 0, "AB", 278, "touch"],+["delay", "delay", 2, 1, "none", null, "time"],+["delay", "delay", 2, 2, "none", null, "time"],+["delay", "delay", 2, 3, "B", 220, "touch"],+["delay", "delay", 2, 4, "none", null, "time"],+["delay", "delay", 2, 5, "none", null, "time"],+["delay", "delay", 3, 0, "A", 220, "touch"],+["delay", "delay", 3, 1, "none", null, "time"],+["delay", "delay", 3, 2, "none", null, "time"],+["delay", "delay", 3, 3, "B", 212, "touch"],+["delay", "delay", 3, 4, "B", 210, "touch"],+["delay", "delay", 3, 5, "B", 223, "touch"],+["delay", "delay", 4, 0, "AB", 225, "touch"],+["delay", "delay", 4, 1, "none", null, "time"],+["delay", "delay", 4, 2, "B", 207, "touch"],+["delay", "delay", 4, 3, "B", 221, "touch"],+["delay", "delay", 4, 4, "A", 259, "touch"],+["delay", "delay", 4, 5, "none", null, "time"],+["delay", "delay", 5, 0, "B", 210, "touch"],+["delay", "delay", 5, 1, "B", 210, "touch"],+["delay", "delay", 5, 2, "none", null, "time"],+["delay", "delay", 5, 3, "none", null, "time"],+["delay", "delay", 5, 4, "A", 219, "touch"],+["delay", "delay", 5, 5, "none", null, "time"],+["delay", "retreat", 0, 0, "none", null, "time"],+["delay", "retreat", 0, 1, "none", null, "time"],+["delay", "retreat", 0, 2, "none", null, "time"],+["delay", "retreat", 0, 3, "none", null, "time"],+["delay", "retreat", 0, 4, "none", null, "time"],+["delay", "retreat", 0, 5, "none", null, "time"],+["delay", "retreat", 1, 0, "none", null, "time"],+["delay", "retreat", 1, 1, "none", null, "time"],+["delay", "retreat", 1, 2, "none", null, "time"],+["delay", "retreat", 1, 3, "none", null, "time"],+["delay", "retreat", 1, 4, "none", null, "time"],+["delay", "retreat", 1, 5, "none", null, "time"],+["delay", "retreat", 2, 0, "none", null, "time"],+["delay", "retreat", 2, 1, "none", null, "time"],+["delay", "retreat", 2, 2, "none", null, "time"],+["delay", "retreat", 2, 3, "none", null, "time"],+["delay", "retreat", 2, 4, "none", null, "time"],+["delay", "retreat", 2, 5, "none", null, "time"],+["delay", "retreat", 3, 0, "none", null, "time"],+["delay", "retreat", 3, 1, "none", null, "time"],+["delay", "retreat", 3, 2, "none", null, "time"],+["delay", "retreat", 3, 3, "none", null, "time"],+["delay", "retreat", 3, 4, "none", null, "time"],+["delay", "retreat", 3, 5, "none", null, "time"],+["delay", "retreat", 4, 0, "none", null, "time"],+["delay", "retreat", 4, 1, "none", null, "time"],+["delay", "retreat", 4, 2, "none", null, "time"],+["delay", "retreat", 4, 3, "none", null, "time"],+["delay", "retreat", 4, 4, "none", null, "time"],+["delay", "retreat", 4, 5, "none", null, "time"],+["delay", "retreat", 5, 0, "none", null, "time"],+["delay", "retreat", 5, 1, "none", null, "time"],+["delay", "retreat", 5, 2, "none", null, "time"],+["delay", "retreat", 5, 3, "none", null, "time"],+["delay", "retreat", 5, 4, "none", null, "time"],+["delay", "retreat", 5, 5, "none", null, "time"],+["delay", "draw", 0, 0, "B", 96, "touch"],+["delay", "draw", 0, 1, "A", 107, "touch"],+["delay", "draw", 0, 2, "A", 107, "touch"],+["delay", "draw", 0, 3, "A", 110, "touch"],+["delay", "draw", 0, 4, "A", 110, "touch"],+["delay", "draw", 0, 5, "A", 107, "touch"],+["delay", "draw", 1, 0, "B", 97, "touch"],+["delay", "draw", 1, 1, "B", 99, "touch"],+["delay", "draw", 1, 2, "B", 99, "touch"],+["delay", "draw", 1, 3, "B", 92, "touch"],+["delay", "draw", 1, 4, "B", 92, "touch"],+["delay", "draw", 1, 5, "B", 98, "touch"],+["delay", "draw", 2, 0, "B", 99, "touch"],+["delay", "draw", 2, 1, "B", 98, "touch"],+["delay", "draw", 2, 2, "B", 98, "touch"],+["delay", "draw", 2, 3, "B", 99, "touch"],+["delay", "draw", 2, 4, "B", 99, "touch"],+["delay", "draw", 2, 5, "B", 100, "touch"],+["delay", "draw", 3, 0, "B", 101, "touch"],+["delay", "draw", 3, 1, "B", 93, "touch"],+["delay", "draw", 3, 2, "B", 93, "touch"],+["delay", "draw", 3, 3, "B", 99, "touch"],+["delay", "draw", 3, 4, "B", 99, "touch"],+["delay", "draw", 3, 5, "B", 100, "touch"],+["delay", "draw", 4, 0, "B", 94, "touch"],+["delay", "draw", 4, 1, "A", 111, "touch"],+["delay", "draw", 4, 2, "A", 111, "touch"],+["delay", "draw", 4, 3, "B", 101, "touch"],+["delay", "draw", 4, 4, "B", 101, "touch"],+["delay", "draw", 4, 5, "B", 100, "touch"],+["delay", "draw", 5, 0, "B", 95, "touch"],+["delay", "draw", 5, 1, "B", 105, "touch"],+["delay", "draw", 5, 2, "B", 105, "touch"],+["delay", "draw", 5, 3, "B", 102, "touch"],+["delay", "draw", 5, 4, "B", 102, "touch"],+["delay", "draw", 5, 5, "B", 95, "touch"],+["retreat", "lunge", 0, 0, "B", 73, "touch"],+["retreat", "lunge", 0, 1, "B", 69, "touch"],+["retreat", "lunge", 0, 2, "none", null, "time"],+["retreat", "lunge", 0, 3, "B", 71, "touch"],+["retreat", "lunge", 0, 4, "none", null, "time"],+["retreat", "lunge", 0, 5, "B", 74, "touch"],+["retreat", "lunge", 1, 0, "none", null, "time"],+["retreat", "lunge", 1, 1, "B", 69, "touch"],+["retreat", "lunge", 1, 2, "none", null, "time"],+["retreat", "lunge", 1, 3, "B", 71, "touch"],+["retreat", "lunge", 1, 4, "none", null, "time"],+["retreat", "lunge", 1, 5, "B", 74, "touch"],+["retreat", "lunge", 2, 0, "none", null, "time"],+["retreat", "lunge", 2, 1, "B", 69, "touch"],+["retreat", "lunge", 2, 2, "none", null, "time"],+["retreat", "lunge", 2, 3, "B", 71, "touch"],+["retreat", "lunge", 2, 4, "none", null, "time"],+["retreat", "lunge", 2, 5, "B", 74, "touch"],+["retreat", "lunge", 3, 0, "B", 72, "touch"],+["retreat", "lunge", 3, 1, "B", 69, "touch"],+["retreat", "lunge", 3, 2, "none", null, "time"],+["retreat", "lunge", 3, 3, "B", 71, "touch"],+["retreat", "lunge", 3, 4, "none", null, "time"],+["retreat", "lunge", 3, 5, "B", 74, "touch"],+["retreat", "lunge", 4, 0, "B", 72, "touch"],+["retreat", "lunge", 4, 1, "B", 69, "touch"],+["retreat", "lunge", 4, 2, "none", null, "time"],+["retreat", "lunge", 4, 3, "B", 71, "touch"],+["retreat", "lunge", 4, 4, "none", null, "time"],+["retreat", "lunge", 4, 5, "B", 74, "touch"],+["retreat", "lunge", 5, 0, "B", 71, "touch"],+["retreat", "lunge", 5, 1, "B", 68, "touch"],+["retreat", "lunge", 5, 2, "B", 72, "touch"],+["retreat", "lunge", 5, 3, "B", 71, "touch"],+["retreat", "lunge", 5, 4, "B", 72, "touch"],+["retreat", "lunge", 5, 5, "B", 72, "touch"],+["retreat", "low", 0, 0, "none", null, "time"],+["retreat", "low", 0, 1, "none", null, "time"],+["retreat", "low", 0, 2, "none", null, "time"],+["retreat", "low", 0, 3, "none", null, "time"],+["retreat", "low", 0, 4, "B", 54, "touch"],+["retreat", "low", 0, 5, "none", null, "time"],+["retreat", "low", 1, 0, "none", null, "time"],+["retreat", "low", 1, 1, "B", 87, "touch"],+["retreat", "low", 1, 2, "B", 52, "touch"],+["retreat", "low", 1, 3, "none", null, "time"],+["retreat", "low", 1, 4, "none", null, "time"],+["retreat", "low", 1, 5, "none", null, "time"],+["retreat", "low", 2, 0, "none", null, "time"],+["retreat", "low", 2, 1, "B", 87, "touch"],+["retreat", "low", 2, 2, "B", 52, "touch"],+["retreat", "low", 2, 3, "none", null, "time"],+["retreat", "low", 2, 4, "none", null, "time"],+["retreat", "low", 2, 5, "none", null, "time"],+["retreat", "low", 3, 0, "none", null, "time"],+["retreat", "low", 3, 1, "B", 88, "touch"],+["retreat", "low", 3, 2, "B", 52, "touch"],+["retreat", "low", 3, 3, "B", 89, "touch"],+["retreat", "low", 3, 4, "B", 53, "touch"],+["retreat", "low", 3, 5, "none", null, "time"],+["retreat", "low", 4, 0, "none", null, "time"],+["retreat", "low", 4, 1, "B", 88, "touch"],+["retreat", "low", 4, 2, "B", 52, "touch"],+["retreat", "low", 4, 3, "B", 89, "touch"],+["retreat", "low", 4, 4, "B", 53, "touch"],+["retreat", "low", 4, 5, "none", null, "time"],+["retreat", "low", 5, 0, "none", null, "time"],+["retreat", "low", 5, 1, "B", 90, "touch"],+["retreat", "low", 5, 2, "B", 52, "touch"],+["retreat", "low", 5, 3, "none", null, "time"],+["retreat", "low", 5, 4, "B", 53, "touch"],+["retreat", "low", 5, 5, "B", 90, "touch"],+["retreat", "line", 0, 0, "none", null, "time"],+["retreat", "line", 0, 1, "none", null, "time"],+["retreat", "line", 0, 2, "none", null, "time"],+["retreat", "line", 0, 3, "none", null, "time"],+["retreat", "line", 0, 4, "none", null, "time"],+["retreat", "line", 0, 5, "none", null, "time"],+["retreat", "line", 1, 0, "none", null, "time"],+["retreat", "line", 1, 1, "none", null, "time"],+["retreat", "line", 1, 2, "none", null, "time"],+["retreat", "line", 1, 3, "none", null, "time"],+["retreat", "line", 1, 4, "none", null, "time"],+["retreat", "line", 1, 5, "none", null, "time"],+["retreat", "line", 2, 0, "none", null, "time"],+["retreat", "line", 2, 1, "none", null, "time"],+["retreat", "line", 2, 2, "none", null, "time"],+["retreat", "line", 2, 3, "none", null, "time"],+["retreat", "line", 2, 4, "none", null, "time"],+["retreat", "line", 2, 5, "none", null, "time"],+["retreat", "line", 3, 0, "none", null, "time"],+["retreat", "line", 3, 1, "none", null, "time"],+["retreat", "line", 3, 2, "none", null, "time"],+["retreat", "line", 3, 3, "none", null, "time"],+["retreat", "line", 3, 4, "none", null, "time"],+["retreat", "line", 3, 5, "none", null, "time"],+["retreat", "line", 4, 0, "none", null, "time"],+["retreat", "line", 4, 1, "none", null, "time"],+["retreat", "line", 4, 2, "none", null, "time"],+["retreat", "line", 4, 3, "none", null, "time"],+["retreat", "line", 4, 4, "none", null, "time"],+["retreat", "line", 4, 5, "none", null, "time"],+["retreat", "line", 5, 0, "none", null, "time"],+["retreat", "line", 5, 1, "none", null, "time"],+["retreat", "line", 5, 2, "none", null, "time"],+["retreat", "line", 5, 3, "none", null, "time"],+["retreat", "line", 5, 4, "none", null, "time"],+["retreat", "line", 5, 5, "none", null, "time"],+["retreat", "rline", 0, 0, "none", null, "time"],+["retreat", "rline", 0, 1, "none", null, "time"],+["retreat", "rline", 0, 2, "none", null, "time"],+["retreat", "rline", 0, 3, "none", null, "time"],+["retreat", "rline", 0, 4, "none", null, "time"],+["retreat", "rline", 0, 5, "none", null, "time"],+["retreat", "rline", 1, 0, "none", null, "time"],+["retreat", "rline", 1, 1, "none", null, "time"],+["retreat", "rline", 1, 2, "none", null, "time"],+["retreat", "rline", 1, 3, "none", null, "time"],+["retreat", "rline", 1, 4, "none", null, "time"],+["retreat", "rline", 1, 5, "none", null, "time"],+["retreat", "rline", 2, 0, "none", null, "time"],+["retreat", "rline", 2, 1, "none", null, "time"],+["retreat", "rline", 2, 2, "none", null, "time"],+["retreat", "rline", 2, 3, "none", null, "time"],+["retreat", "rline", 2, 4, "none", null, "time"],+["retreat", "rline", 2, 5, "none", null, "time"],+["retreat", "rline", 3, 0, "none", null, "time"],+["retreat", "rline", 3, 1, "none", null, "time"],+["retreat", "rline", 3, 2, "none", null, "time"],+["retreat", "rline", 3, 3, "none", null, "time"],+["retreat", "rline", 3, 4, "none", null, "time"],+["retreat", "rline", 3, 5, "none", null, "time"],+["retreat", "rline", 4, 0, "none", null, "time"],+["retreat", "rline", 4, 1, "none", null, "time"],+["retreat", "rline", 4, 2, "none", null, "time"],+["retreat", "rline", 4, 3, "none", null, "time"],+["retreat", "rline", 4, 4, "none", null, "time"],+["retreat", "rline", 4, 5, "none", null, "time"],+["retreat", "rline", 5, 0, "none", null, "time"],+["retreat", "rline", 5, 1, "none", null, "time"],+["retreat", "rline", 5, 2, "none", null, "time"],+["retreat", "rline", 5, 3, "none", null, "time"],+["retreat", "rline", 5, 4, "none", null, "time"],+["retreat", "rline", 5, 5, "none", null, "time"],+["retreat", "stop", 0, 0, "none", null, "time"],+["retreat", "stop", 0, 1, "none", null, "time"],+["retreat", "stop", 0, 2, "none", null, "time"],+["retreat", "stop", 0, 3, "none", null, "time"],+["retreat", "stop", 0, 4, "none", null, "time"],+["retreat", "stop", 0, 5, "none", null, "time"],+["retreat", "stop", 1, 0, "none", null, "time"],+["retreat", "stop", 1, 1, "none", null, "time"],+["retreat", "stop", 1, 2, "none", null, "time"],+["retreat", "stop", 1, 3, "none", null, "time"],+["retreat", "stop", 1, 4, "none", null, "time"],+["retreat", "stop", 1, 5, "none", null, "time"],+["retreat", "stop", 2, 0, "none", null, "time"],+["retreat", "stop", 2, 1, "none", null, "time"],+["retreat", "stop", 2, 2, "none", null, "time"],+["retreat", "stop", 2, 3, "none", null, "time"],+["retreat", "stop", 2, 4, "none", null, "time"],+["retreat", "stop", 2, 5, "none", null, "time"],+["retreat", "stop", 3, 0, "none", null, "time"],+["retreat", "stop", 3, 1, "none", null, "time"],+["retreat", "stop", 3, 2, "none", null, "time"],+["retreat", "stop", 3, 3, "none", null, "time"],+["retreat", "stop", 3, 4, "none", null, "time"],+["retreat", "stop", 3, 5, "none", null, "time"],+["retreat", "stop", 4, 0, "none", null, "time"],+["retreat", "stop", 4, 1, "none", null, "time"],+["retreat", "stop", 4, 2, "none", null, "time"],+["retreat", "stop", 4, 3, "none", null, "time"],+["retreat", "stop", 4, 4, "none", null, "time"],+["retreat", "stop", 4, 5, "none", null, "time"],+["retreat", "stop", 5, 0, "none", null, "time"],+["retreat", "stop", 5, 1, "none", null, "time"],+["retreat", "stop", 5, 2, "none", null, "time"],+["retreat", "stop", 5, 3, "none", null, "time"],+["retreat", "stop", 5, 4, "none", null, "time"],+["retreat", "stop", 5, 5, "none", null, "time"],+["retreat", "counter", 0, 0, "none", null, "time"],+["retreat", "counter", 0, 1, "none", null, "time"],+["retreat", "counter", 0, 2, "none", null, "time"],+["retreat", "counter", 0, 3, "none", null, "time"],+["retreat", "counter", 0, 4, "none", null, "time"],+["retreat", "counter", 0, 5, "none", null, "time"],+["retreat", "counter", 1, 0, "none", null, "time"],+["retreat", "counter", 1, 1, "none", null, "time"],+["retreat", "counter", 1, 2, "none", null, "time"],+["retreat", "counter", 1, 3, "none", null, "time"],+["retreat", "counter", 1, 4, "none", null, "time"],+["retreat", "counter", 1, 5, "none", null, "time"],+["retreat", "counter", 2, 0, "none", null, "time"],+["retreat", "counter", 2, 1, "none", null, "time"],+["retreat", "counter", 2, 2, "none", null, "time"],+["retreat", "counter", 2, 3, "none", null, "time"],+["retreat", "counter", 2, 4, "none", null, "time"],+["retreat", "counter", 2, 5, "none", null, "time"],+["retreat", "counter", 3, 0, "none", null, "time"],+["retreat", "counter", 3, 1, "none", null, "time"],+["retreat", "counter", 3, 2, "none", null, "time"],+["retreat", "counter", 3, 3, "none", null, "time"],+["retreat", "counter", 3, 4, "none", null, "time"],+["retreat", "counter", 3, 5, "none", null, "time"],+["retreat", "counter", 4, 0, "none", null, "time"],+["retreat", "counter", 4, 1, "none", null, "time"],+["retreat", "counter", 4, 2, "none", null, "time"],+["retreat", "counter", 4, 3, "none", null, "time"],+["retreat", "counter", 4, 4, "none", null, "time"],+["retreat", "counter", 4, 5, "none", null, "time"],+["retreat", "counter", 5, 0, "none", null, "time"],+["retreat", "counter", 5, 1, "none", null, "time"],+["retreat", "counter", 5, 2, "none", null, "time"],+["retreat", "counter", 5, 3, "none", null, "time"],+["retreat", "counter", 5, 4, "none", null, "time"],+["retreat", "counter", 5, 5, "none", null, "time"],+["retreat", "delay", 0, 0, "none", null, "time"],+["retreat", "delay", 0, 1, "none", null, "time"],+["retreat", "delay", 0, 2, "none", null, "time"],+["retreat", "delay", 0, 3, "none", null, "time"],+["retreat", "delay", 0, 4, "none", null, "time"],+["retreat", "delay", 0, 5, "none", null, "time"],+["retreat", "delay", 1, 0, "none", null, "time"],+["retreat", "delay", 1, 1, "none", null, "time"],+["retreat", "delay", 1, 2, "none", null, "time"],+["retreat", "delay", 1, 3, "none", null, "time"],+["retreat", "delay", 1, 4, "none", null, "time"],+["retreat", "delay", 1, 5, "none", null, "time"],+["retreat", "delay", 2, 0, "none", null, "time"],+["retreat", "delay", 2, 1, "none", null, "time"],+["retreat", "delay", 2, 2, "none", null, "time"],+["retreat", "delay", 2, 3, "none", null, "time"],+["retreat", "delay", 2, 4, "none", null, "time"],+["retreat", "delay", 2, 5, "none", null, "time"],+["retreat", "delay", 3, 0, "none", null, "time"],+["retreat", "delay", 3, 1, "none", null, "time"],+["retreat", "delay", 3, 2, "none", null, "time"],+["retreat", "delay", 3, 3, "none", null, "time"],+["retreat", "delay", 3, 4, "none", null, "time"],+["retreat", "delay", 3, 5, "none", null, "time"],+["retreat", "delay", 4, 0, "none", null, "time"],+["retreat", "delay", 4, 1, "none", null, "time"],+["retreat", "delay", 4, 2, "none", null, "time"],+["retreat", "delay", 4, 3, "none", null, "time"],+["retreat", "delay", 4, 4, "none", null, "time"],+["retreat", "delay", 4, 5, "none", null, "time"],+["retreat", "delay", 5, 0, "none", null, "time"],+["retreat", "delay", 5, 1, "none", null, "time"],+["retreat", "delay", 5, 2, "none", null, "time"],+["retreat", "delay", 5, 3, "none", null, "time"],+["retreat", "delay", 5, 4, "none", null, "time"],+["retreat", "delay", 5, 5, "none", null, "time"],+["retreat", "retreat", 0, 0, "none", null, "time"],+["retreat", "retreat", 0, 1, "none", null, "time"],+["retreat", "retreat", 0, 2, "none", null, "time"],+["retreat", "retreat", 0, 3, "none", null, "time"],+["retreat", "retreat", 0, 4, "none", null, "time"],+["retreat", "retreat", 0, 5, "none", null, "time"],+["retreat", "retreat", 1, 0, "none", null, "time"],+["retreat", "retreat", 1, 1, "none", null, "time"],+["retreat", "retreat", 1, 2, "none", null, "time"],+["retreat", "retreat", 1, 3, "none", null, "time"],+["retreat", "retreat", 1, 4, "none", null, "time"],+["retreat", "retreat", 1, 5, "none", null, "time"],+["retreat", "retreat", 2, 0, "none", null, "time"],+["retreat", "retreat", 2, 1, "none", null, "time"],+["retreat", "retreat", 2, 2, "none", null, "time"],+["retreat", "retreat", 2, 3, "none", null, "time"],+["retreat", "retreat", 2, 4, "none", null, "time"],+["retreat", "retreat", 2, 5, "none", null, "time"],+["retreat", "retreat", 3, 0, "none", null, "time"],+["retreat", "retreat", 3, 1, "none", null, "time"],+["retreat", "retreat", 3, 2, "none", null, "time"],+["retreat", "retreat", 3, 3, "none", null, "time"],+["retreat", "retreat", 3, 4, "none", null, "time"],+["retreat", "retreat", 3, 5, "none", null, "time"],+["retreat", "retreat", 4, 0, "none", null, "time"],+["retreat", "retreat", 4, 1, "none", null, "time"],+["retreat", "retreat", 4, 2, "none", null, "time"],+["retreat", "retreat", 4, 3, "none", null, "time"],+["retreat", "retreat", 4, 4, "none", null, "time"],+["retreat", "retreat", 4, 5, "none", null, "time"],+["retreat", "retreat", 5, 0, "none", null, "time"],+["retreat", "retreat", 5, 1, "none", null, "time"],+["retreat", "retreat", 5, 2, "none", null, "time"],+["retreat", "retreat", 5, 3, "none", null, "time"],+["retreat", "retreat", 5, 4, "none", null, "time"],+["retreat", "retreat", 5, 5, "none", null, "time"],+["retreat", "draw", 0, 0, "B", 173, "touch"],+["retreat", "draw", 0, 1, "B", 174, "touch"],+["retreat", "draw", 0, 2, "B", 174, "touch"],+["retreat", "draw", 0, 3, "B", 175, "touch"],+["retreat", "draw", 0, 4, "B", 175, "touch"],+["retreat", "draw", 0, 5, "B", 178, "touch"],+["retreat", "draw", 1, 0, "B", 175, "touch"],+["retreat", "draw", 1, 1, "B", 177, "touch"],+["retreat", "draw", 1, 2, "B", 177, "touch"],+["retreat", "draw", 1, 3, "B", 177, "touch"],+["retreat", "draw", 1, 4, "B", 177, "touch"],+["retreat", "draw", 1, 5, "B", 179, "touch"],+["retreat", "draw", 2, 0, "B", 175, "touch"],+["retreat", "draw", 2, 1, "B", 177, "touch"],+["retreat", "draw", 2, 2, "B", 177, "touch"],+["retreat", "draw", 2, 3, "B", 177, "touch"],+["retreat", "draw", 2, 4, "B", 177, "touch"],+["retreat", "draw", 2, 5, "B", 179, "touch"],+["retreat", "draw", 3, 0, "B", 176, "touch"],+["retreat", "draw", 3, 1, "B", 177, "touch"],+["retreat", "draw", 3, 2, "B", 177, "touch"],+["retreat", "draw", 3, 3, "B", 178, "touch"],+["retreat", "draw", 3, 4, "B", 178, "touch"],+["retreat", "draw", 3, 5, "B", 179, "touch"],+["retreat", "draw", 4, 0, "B", 176, "touch"],+["retreat", "draw", 4, 1, "B", 177, "touch"],+["retreat", "draw", 4, 2, "B", 177, "touch"],+["retreat", "draw", 4, 3, "B", 178, "touch"],+["retreat", "draw", 4, 4, "B", 178, "touch"],+["retreat", "draw", 4, 5, "B", 179, "touch"],+["retreat", "draw", 5, 0, "B", 177, "touch"],+["retreat", "draw", 5, 1, "B", 177, "touch"],+["retreat", "draw", 5, 2, "B", 177, "touch"],+["retreat", "draw", 5, 3, "B", 179, "touch"],+["retreat", "draw", 5, 4, "B", 179, "touch"],+["retreat", "draw", 5, 5, "B", 181, "touch"],+["draw", "lunge", 0, 0, "B", 73, "touch"],+["draw", "lunge", 0, 1, "A", 60, "touch"],+["draw", "lunge", 0, 2, "B", 74, "touch"],+["draw", "lunge", 0, 3, "A", 61, "touch"],+["draw", "lunge", 0, 4, "A", 98, "touch"],+["draw", "lunge", 0, 5, "A", 63, "touch"],+["draw", "lunge", 1, 0, "B", 125, "touch"],+["draw", "lunge", 1, 1, "A", 61, "touch"],+["draw", "lunge", 1, 2, "B", 74, "touch"],+["draw", "lunge", 1, 3, "A", 62, "touch"],+["draw", "lunge", 1, 4, "A", 98, "touch"],+["draw", "lunge", 1, 5, "A", 63, "touch"],+["draw", "lunge", 2, 0, "B", 125, "touch"],+["draw", "lunge", 2, 1, "A", 61, "touch"],+["draw", "lunge", 2, 2, "B", 74, "touch"],+["draw", "lunge", 2, 3, "A", 62, "touch"],+["draw", "lunge", 2, 4, "A", 98, "touch"],+["draw", "lunge", 2, 5, "A", 63, "touch"],+["draw", "lunge", 3, 0, "A", 174, "touch"],+["draw", "lunge", 3, 1, "B", 70, "touch"],+["draw", "lunge", 3, 2, "B", 74, "touch"],+["draw", "lunge", 3, 3, "B", 73, "touch"],+["draw", "lunge", 3, 4, "B", 75, "touch"],+["draw", "lunge", 3, 5, "A", 65, "touch"],+["draw", "lunge", 4, 0, "A", 174, "touch"],+["draw", "lunge", 4, 1, "B", 70, "touch"],+["draw", "lunge", 4, 2, "B", 74, "touch"],+["draw", "lunge", 4, 3, "B", 73, "touch"],+["draw", "lunge", 4, 4, "B", 75, "touch"],+["draw", "lunge", 4, 5, "A", 65, "touch"],+["draw", "lunge", 5, 0, "B", 140, "touch"],+["draw", "lunge", 5, 1, "B", 70, "touch"],+["draw", "lunge", 5, 2, "B", 74, "touch"],+["draw", "lunge", 5, 3, "B", 72, "touch"],+["draw", "lunge", 5, 4, "B", 76, "touch"],+["draw", "lunge", 5, 5, "B", 74, "touch"],+["draw", "low", 0, 0, "A", 60, "touch"],+["draw", "low", 0, 1, "A", 60, "touch"],+["draw", "low", 0, 2, "A", 59, "touch"],+["draw", "low", 0, 3, "none", null, "time"],+["draw", "low", 0, 4, "A", 62, "touch"],+["draw", "low", 0, 5, "A", 62, "touch"],+["draw", "low", 1, 0, "A", 58, "touch"],+["draw", "low", 1, 1, "none", null, "time"],+["draw", "low", 1, 2, "A", 59, "touch"],+["draw", "low", 1, 3, "B", 105, "touch"],+["draw", "low", 1, 4, "A", 61, "touch"],+["draw", "low", 1, 5, "A", 62, "touch"],+["draw", "low", 2, 0, "A", 58, "touch"],+["draw", "low", 2, 1, "none", null, "time"],+["draw", "low", 2, 2, "A", 59, "touch"],+["draw", "low", 2, 3, "B", 105, "touch"],+["draw", "low", 2, 4, "A", 61, "touch"],+["draw", "low", 2, 5, "A", 62, "touch"],+["draw", "low", 3, 0, "A", 60, "touch"],+["draw", "low", 3, 1, "none", null, "time"],+["draw", "low", 3, 2, "A", 60, "touch"],+["draw", "low", 3, 3, "A", 60, "touch"],+["draw", "low", 3, 4, "none", null, "time"],+["draw", "low", 3, 5, "A", 61, "touch"],+["draw", "low", 4, 0, "A", 60, "touch"],+["draw", "low", 4, 1, "none", null, "time"],+["draw", "low", 4, 2, "A", 60, "touch"],+["draw", "low", 4, 3, "A", 60, "touch"],+["draw", "low", 4, 4, "none", null, "time"],+["draw", "low", 4, 5, "A", 61, "touch"],+["draw", "low", 5, 0, "A", 61, "touch"],+["draw", "low", 5, 1, "A", 60, "touch"],+["draw", "low", 5, 2, "none", null, "time"],+["draw", "low", 5, 3, "A", 61, "touch"],+["draw", "low", 5, 4, "A", 61, "touch"],+["draw", "low", 5, 5, "A", 62, "touch"],+["draw", "line", 0, 0, "none", null, "time"],+["draw", "line", 0, 1, "none", null, "time"],+["draw", "line", 0, 2, "none", null, "time"],+["draw", "line", 0, 3, "none", null, "time"],+["draw", "line", 0, 4, "none", null, "time"],+["draw", "line", 0, 5, "none", null, "time"],+["draw", "line", 1, 0, "none", null, "time"],+["draw", "line", 1, 1, "none", null, "time"],+["draw", "line", 1, 2, "none", null, "time"],+["draw", "line", 1, 3, "none", null, "time"],+["draw", "line", 1, 4, "none", null, "time"],+["draw", "line", 1, 5, "none", null, "time"],+["draw", "line", 2, 0, "none", null, "time"],+["draw", "line", 2, 1, "none", null, "time"],+["draw", "line", 2, 2, "none", null, "time"],+["draw", "line", 2, 3, "none", null, "time"],+["draw", "line", 2, 4, "none", null, "time"],+["draw", "line", 2, 5, "none", null, "time"],+["draw", "line", 3, 0, "none", null, "time"],+["draw", "line", 3, 1, "none", null, "time"],+["draw", "line", 3, 2, "none", null, "time"],+["draw", "line", 3, 3, "none", null, "time"],+["draw", "line", 3, 4, "none", null, "time"],+["draw", "line", 3, 5, "none", null, "time"],+["draw", "line", 4, 0, "none", null, "time"],+["draw", "line", 4, 1, "none", null, "time"],+["draw", "line", 4, 2, "none", null, "time"],+["draw", "line", 4, 3, "none", null, "time"],+["draw", "line", 4, 4, "none", null, "time"],+["draw", "line", 4, 5, "none", null, "time"],+["draw", "line", 5, 0, "none", null, "time"],+["draw", "line", 5, 1, "none", null, "time"],+["draw", "line", 5, 2, "none", null, "time"],+["draw", "line", 5, 3, "none", null, "time"],+["draw", "line", 5, 4, "none", null, "time"],+["draw", "line", 5, 5, "none", null, "time"],+["draw", "rline", 0, 0, "none", null, "time"],+["draw", "rline", 0, 1, "none", null, "time"],+["draw", "rline", 0, 2, "none", null, "time"],+["draw", "rline", 0, 3, "none", null, "time"],+["draw", "rline", 0, 4, "none", null, "time"],+["draw", "rline", 0, 5, "none", null, "time"],+["draw", "rline", 1, 0, "none", null, "time"],+["draw", "rline", 1, 1, "none", null, "time"],+["draw", "rline", 1, 2, "none", null, "time"],+["draw", "rline", 1, 3, "none", null, "time"],+["draw", "rline", 1, 4, "none", null, "time"],+["draw", "rline", 1, 5, "none", null, "time"],+["draw", "rline", 2, 0, "none", null, "time"],+["draw", "rline", 2, 1, "none", null, "time"],+["draw", "rline", 2, 2, "none", null, "time"],+["draw", "rline", 2, 3, "none", null, "time"],+["draw", "rline", 2, 4, "none", null, "time"],+["draw", "rline", 2, 5, "none", null, "time"],+["draw", "rline", 3, 0, "none", null, "time"],+["draw", "rline", 3, 1, "none", null, "time"],+["draw", "rline", 3, 2, "none", null, "time"],+["draw", "rline", 3, 3, "none", null, "time"],+["draw", "rline", 3, 4, "none", null, "time"],+["draw", "rline", 3, 5, "none", null, "time"],+["draw", "rline", 4, 0, "none", null, "time"],+["draw", "rline", 4, 1, "none", null, "time"],+["draw", "rline", 4, 2, "none", null, "time"],+["draw", "rline", 4, 3, "none", null, "time"],+["draw", "rline", 4, 4, "none", null, "time"],+["draw", "rline", 4, 5, "none", null, "time"],+["draw", "rline", 5, 0, "none", null, "time"],+["draw", "rline", 5, 1, "none", null, "time"],+["draw", "rline", 5, 2, "none", null, "time"],+["draw", "rline", 5, 3, "none", null, "time"],+["draw", "rline", 5, 4, "none", null, "time"],+["draw", "rline", 5, 5, "none", null, "time"],+["draw", "stop", 0, 0, "none", null, "time"],+["draw", "stop", 0, 1, "none", null, "time"],+["draw", "stop", 0, 2, "none", null, "time"],+["draw", "stop", 0, 3, "none", null, "time"],+["draw", "stop", 0, 4, "none", null, "time"],+["draw", "stop", 0, 5, "none", null, "time"],+["draw", "stop", 1, 0, "none", null, "time"],+["draw", "stop", 1, 1, "none", null, "time"],+["draw", "stop", 1, 2, "none", null, "time"],+["draw", "stop", 1, 3, "none", null, "time"],+["draw", "stop", 1, 4, "none", null, "time"],+["draw", "stop", 1, 5, "none", null, "time"],+["draw", "stop", 2, 0, "none", null, "time"],+["draw", "stop", 2, 1, "none", null, "time"],+["draw", "stop", 2, 2, "none", null, "time"],+["draw", "stop", 2, 3, "none", null, "time"],+["draw", "stop", 2, 4, "none", null, "time"],+["draw", "stop", 2, 5, "none", null, "time"],+["draw", "stop", 3, 0, "none", null, "time"],+["draw", "stop", 3, 1, "none", null, "time"],+["draw", "stop", 3, 2, "none", null, "time"],+["draw", "stop", 3, 3, "none", null, "time"],+["draw", "stop", 3, 4, "none", null, "time"],+["draw", "stop", 3, 5, "none", null, "time"],+["draw", "stop", 4, 0, "none", null, "time"],+["draw", "stop", 4, 1, "none", null, "time"],+["draw", "stop", 4, 2, "none", null, "time"],+["draw", "stop", 4, 3, "none", null, "time"],+["draw", "stop", 4, 4, "none", null, "time"],+["draw", "stop", 4, 5, "none", null, "time"],+["draw", "stop", 5, 0, "none", null, "time"],+["draw", "stop", 5, 1, "none", null, "time"],+["draw", "stop", 5, 2, "none", null, "time"],+["draw", "stop", 5, 3, "none", null, "time"],+["draw", "stop", 5, 4, "none", null, "time"],+["draw", "stop", 5, 5, "none", null, "time"],+["draw", "counter", 0, 0, "A", 94, "touch"],+["draw", "counter", 0, 1, "A", 94, "touch"],+["draw", "counter", 0, 2, "A", 94, "touch"],+["draw", "counter", 0, 3, "A", 94, "touch"],+["draw", "counter", 0, 4, "A", 94, "touch"],+["draw", "counter", 0, 5, "A", 94, "touch"],+["draw", "counter", 1, 0, "A", 95, "touch"],+["draw", "counter", 1, 1, "A", 95, "touch"],+["draw", "counter", 1, 2, "A", 95, "touch"],+["draw", "counter", 1, 3, "A", 95, "touch"],+["draw", "counter", 1, 4, "A", 95, "touch"],+["draw", "counter", 1, 5, "A", 95, "touch"],+["draw", "counter", 2, 0, "A", 95, "touch"],+["draw", "counter", 2, 1, "A", 95, "touch"],+["draw", "counter", 2, 2, "A", 95, "touch"],+["draw", "counter", 2, 3, "A", 95, "touch"],+["draw", "counter", 2, 4, "A", 95, "touch"],+["draw", "counter", 2, 5, "A", 95, "touch"],+["draw", "counter", 3, 0, "A", 92, "touch"],+["draw", "counter", 3, 1, "A", 92, "touch"],+["draw", "counter", 3, 2, "A", 92, "touch"],+["draw", "counter", 3, 3, "A", 92, "touch"],+["draw", "counter", 3, 4, "A", 92, "touch"],+["draw", "counter", 3, 5, "A", 92, "touch"],+["draw", "counter", 4, 0, "A", 92, "touch"],+["draw", "counter", 4, 1, "A", 92, "touch"],+["draw", "counter", 4, 2, "A", 92, "touch"],+["draw", "counter", 4, 3, "A", 92, "touch"],+["draw", "counter", 4, 4, "A", 92, "touch"],+["draw", "counter", 4, 5, "A", 92, "touch"],+["draw", "counter", 5, 0, "A", 100, "touch"],+["draw", "counter", 5, 1, "A", 100, "touch"],+["draw", "counter", 5, 2, "A", 100, "touch"],+["draw", "counter", 5, 3, "A", 100, "touch"],+["draw", "counter", 5, 4, "A", 100, "touch"],+["draw", "counter", 5, 5, "A", 100, "touch"],+["draw", "delay", 0, 0, "A", 97, "touch"],+["draw", "delay", 0, 1, "B", 107, "touch"],+["draw", "delay", 0, 2, "A", 100, "touch"],+["draw", "delay", 0, 3, "A", 101, "touch"],+["draw", "delay", 0, 4, "A", 93, "touch"],+["draw", "delay", 0, 5, "A", 95, "touch"],+["draw", "delay", 1, 0, "A", 96, "touch"],+["draw", "delay", 1, 1, "A", 98, "touch"],+["draw", "delay", 1, 2, "B", 111, "touch"],+["draw", "delay", 1, 3, "A", 93, "touch"],+["draw", "delay", 1, 4, "A", 94, "touch"],+["draw", "delay", 1, 5, "A", 101, "touch"],+["draw", "delay", 2, 0, "A", 96, "touch"],+["draw", "delay", 2, 1, "A", 98, "touch"],+["draw", "delay", 2, 2, "B", 111, "touch"],+["draw", "delay", 2, 3, "A", 93, "touch"],+["draw", "delay", 2, 4, "A", 94, "touch"],+["draw", "delay", 2, 5, "A", 101, "touch"],+["draw", "delay", 3, 0, "B", 111, "touch"],+["draw", "delay", 3, 1, "A", 92, "touch"],+["draw", "delay", 3, 2, "A", 99, "touch"],+["draw", "delay", 3, 3, "A", 99, "touch"],+["draw", "delay", 3, 4, "B", 112, "touch"],+["draw", "delay", 3, 5, "A", 95, "touch"],+["draw", "delay", 4, 0, "B", 111, "touch"],+["draw", "delay", 4, 1, "A", 92, "touch"],+["draw", "delay", 4, 2, "A", 99, "touch"],+["draw", "delay", 4, 3, "A", 99, "touch"],+["draw", "delay", 4, 4, "B", 112, "touch"],+["draw", "delay", 4, 5, "A", 95, "touch"],+["draw", "delay", 5, 0, "B", 109, "touch"],+["draw", "delay", 5, 1, "A", 98, "touch"],+["draw", "delay", 5, 2, "B", 109, "touch"],+["draw", "delay", 5, 3, "A", 100, "touch"],+["draw", "delay", 5, 4, "A", 100, "touch"],+["draw", "delay", 5, 5, "A", 102, "touch"],+["draw", "retreat", 0, 0, "A", 173, "touch"],+["draw", "retreat", 0, 1, "A", 175, "touch"],+["draw", "retreat", 0, 2, "A", 175, "touch"],+["draw", "retreat", 0, 3, "A", 176, "touch"],+["draw", "retreat", 0, 4, "A", 176, "touch"],+["draw", "retreat", 0, 5, "A", 176, "touch"],+["draw", "retreat", 1, 0, "A", 174, "touch"],+["draw", "retreat", 1, 1, "A", 175, "touch"],+["draw", "retreat", 1, 2, "A", 175, "touch"],+["draw", "retreat", 1, 3, "A", 177, "touch"],+["draw", "retreat", 1, 4, "A", 177, "touch"],+["draw", "retreat", 1, 5, "A", 178, "touch"],+["draw", "retreat", 2, 0, "A", 174, "touch"],+["draw", "retreat", 2, 1, "A", 175, "touch"],+["draw", "retreat", 2, 2, "A", 175, "touch"],+["draw", "retreat", 2, 3, "A", 177, "touch"],+["draw", "retreat", 2, 4, "A", 177, "touch"],+["draw", "retreat", 2, 5, "A", 178, "touch"],+["draw", "retreat", 3, 0, "A", 175, "touch"],+["draw", "retreat", 3, 1, "A", 177, "touch"],+["draw", "retreat", 3, 2, "A", 177, "touch"],+["draw", "retreat", 3, 3, "A", 179, "touch"],+["draw", "retreat", 3, 4, "A", 179, "touch"],+["draw", "retreat", 3, 5, "A", 179, "touch"],+["draw", "retreat", 4, 0, "A", 175, "touch"],+["draw", "retreat", 4, 1, "A", 177, "touch"],+["draw", "retreat", 4, 2, "A", 177, "touch"],+["draw", "retreat", 4, 3, "A", 179, "touch"],+["draw", "retreat", 4, 4, "A", 179, "touch"],+["draw", "retreat", 4, 5, "A", 179, "touch"],+["draw", "retreat", 5, 0, "A", 178, "touch"],+["draw", "retreat", 5, 1, "A", 178, "touch"],+["draw", "retreat", 5, 2, "A", 178, "touch"],+["draw", "retreat", 5, 3, "A", 178, "touch"],+["draw", "retreat", 5, 4, "A", 178, "touch"],+["draw", "retreat", 5, 5, "A", 181, "touch"],+["draw", "draw", 0, 0, "A", 149, "touch"],+["draw", "draw", 0, 1, "A", 164, "touch"],+["draw", "draw", 0, 2, "A", 164, "touch"],+["draw", "draw", 0, 3, "B", 153, "touch"],+["draw", "draw", 0, 4, "B", 153, "touch"],+["draw", "draw", 0, 5, "B", 153, "touch"],+["draw", "draw", 1, 0, "B", 164, "touch"],+["draw", "draw", 1, 1, "B", 151, "touch"],+["draw", "draw", 1, 2, "B", 151, "touch"],+["draw", "draw", 1, 3, "A", 166, "touch"],+["draw", "draw", 1, 4, "A", 166, "touch"],+["draw", "draw", 1, 5, "B", 155, "touch"],+["draw", "draw", 2, 0, "B", 164, "touch"],+["draw", "draw", 2, 1, "B", 151, "touch"],+["draw", "draw", 2, 2, "B", 151, "touch"],+["draw", "draw", 2, 3, "A", 166, "touch"],+["draw", "draw", 2, 4, "A", 166, "touch"],+["draw", "draw", 2, 5, "B", 155, "touch"],+["draw", "draw", 3, 0, "A", 152, "touch"],+["draw", "draw", 3, 1, "B", 167, "touch"],+["draw", "draw", 3, 2, "B", 167, "touch"],+["draw", "draw", 3, 3, "AB", 273, "touch"],+["draw", "draw", 3, 4, "AB", 273, "touch"],+["draw", "draw", 3, 5, "B", 157, "touch"],+["draw", "draw", 4, 0, "A", 152, "touch"],+["draw", "draw", 4, 1, "B", 167, "touch"],+["draw", "draw", 4, 2, "B", 167, "touch"],+["draw", "draw", 4, 3, "AB", 273, "touch"],+["draw", "draw", 4, 4, "AB", 273, "touch"],+["draw", "draw", 4, 5, "B", 157, "touch"],+["draw", "draw", 5, 0, "B", 148, "touch"],+["draw", "draw", 5, 1, "B", 166, "touch"],+["draw", "draw", 5, 2, "B", 166, "touch"],+["draw", "draw", 5, 3, "B", 168, "touch"],+["draw", "draw", 5, 4, "B", 168, "touch"],+["draw", "draw", 5, 5, "A", 271, "touch"]+]}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/plugin.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/plugin.pynew file mode 100644index 0000000000..5f6d0d9ea7--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/plugin.py@@ -0,0 +1,295 @@+"""fencing (epee) on the v0.2 framework, the phrase-level sport since fencing-7 (the owner's decision of 2026-10-13):+the four groups of contract ② (core/sport.py) around the phrase table (phrases.py), the bout referee (bout.py) and the+scripted fencer (opponent.py).++ world + referee FencingMatch: turn protocol, one action = one fencer's intention for the next phrase. Format bout:+ seat A's intention; the scripted fencer (side B) chooses its own from what it has seen of the bout+ (never from A's choice), the phrase is played (phrases.play: the measured phrase with this phrase's+ delays and ends, drawn from the seed) and judged (bout.Bout.phrase), all inside apply. Format duel:+ the first player's intention is kept hidden, the other player's completes the phrase. The state+ digest covers the bout, the hidden intention, the scripted fencer and the table.+ actions one low level: phrase {intention} (sport.toml [modes]: the intention is the robot's whole command+ for a phrase, as a release command in the other turn sports)+ observation observe = the score, the clocks, the cards and every phrase so far from the seat's view (both+ intentions, both delays, the result); camera_job = the 2 x 2 tile image of the last phrase+ (cameras.py, drawn in the seat's render worker)+"""+from __future__ import annotations++import hashlib+import json+import os++import bout as BT+import cameras as CAM+import fencing as F+import opponent as OP+import phrases as PH+from core.sport import FINISHED, PLAYING, MatchBase, Phase, SchemaLayer++HERE = os.path.dirname(os.path.abspath(__file__))+REVISION = "fencing-7+core-0.2"+OPPONENT = "B" # the scripted fencer's side in format bout (it has no seat)+TIEBREAKS = ("touches", "passivity", "time", "deciding_touch", "priority")+INTENTION_DOC = {+ "lunge": "a lunge with the point at the opponent's chest",+ "low": "a lunge with the point at the opponent's front knee",+ "line": "the point in line at the opponent's chest, held",+ "rline": "on guard; the point raised into line when the opponent comes (its pelvis coming faster than 0.2 x the "+ "distance per second)",+ "stop": "on guard; a stop-hit at the opponent's sword hand when it comes within reach",+ "counter": "waits; when the opponent comes (its pelvis faster than 0.15 m/s towards you), a lunge at its chest",+ "delay": "a lunge at the opponent's chest 0.4 s late (after the opponent has shown its intention)",+ "retreat": "steps back for the whole phrase",+ "draw": "a short advance (0.3 s, one 0.15 m step) to draw the opponent's attack, then a lunge at its chest when it "+ "comes, as counter",+}+SCHEMA = {"phrase": {"intention": {"type": "enum", "values": list(PH.INTENTIONS),+ "doc": "your intention for the next phrase (`game spec` intentions)"}}}+RESULT_VIEW = {"double": "double", "none": "none"}+++def _res_code(res, me):+ """the decision programs' result code (opponent.Policy.observe): 1 = I scored alone, -1 = the other, 2 = double+ (also an annulled one), 0 = nothing"""+ return 2 if res == "double" else 0 if res == "none" else (1 if res == me else -1)+++class FencingMatch(MatchBase):+ def __init__(self, cfg):+ self.cfg = cfg+ self.table = PH.table()+ self.kn = OP.Knowledge(self.table.counts())+ self.single = len(cfg.side_list()) == 1+ self.level = self.opp = None+ if self.single:+ self.level = 1 if cfg.level is None else int(cfg.level)+ if self.level not in OP.LEVELS:+ raise ValueError(f"opponent level must be one of {sorted(OP.LEVELS)}")+ self.first, self.second = cfg.seats[0], OPPONENT+ self.opp = OP.Opponent(self.level, cfg.seed, self.kn)+ else:+ self.first = cfg.first if cfg.first in cfg.seats else cfg.seats[0]+ self.second = next(s for s in cfg.seats if s != self.first)+ self.bout = BT.Bout(cfg.seed, self.first, self.second)+ self.pending: dict = {} # format duel: the first player's hidden intention+ self.k = 0++ def other(self, side):+ return self.second if side == self.first else self.first++ # ---------------------------------------------------------------- world + referee+ def _phrase(self, choices):+ b = self.bout+ n = len(b.log)+ p = PH.play(self.table, choices[self.first], choices[self.second], self.cfg.seed, n)+ res = {"first": self.first, "second": self.second}.get(p["res"], p["res"])+ info = dict(intentions={self.first: choices[self.first], self.second: choices[self.second]},+ delays_ms={self.first: p["first_delay_ms"], self.second: p["second_delay_ms"]},+ ends={self.first: p["first_end"], self.second: "B" if p["first_end"] == "A" else "A"},+ why=p["why"], k=p["k"], row=p["row"])+ rec = b.phrase(res, p["s"], info)+ if self.opp is not None:+ idx = self.table.idx+ self.opp.observe(idx[choices[OPPONENT]], idx[choices[self.first]], _res_code(rec["res"], OPPONENT))+ return rec++ def apply(self, seat, cmd):+ i = cmd["intention"]+ self.k += 1+ if self.single:+ sc = self.bout.score+ j = self.table.names[self.opp.choose((sc[OPPONENT], sc[seat]))]+ rec = self._phrase({seat: i, OPPONENT: j})+ return self._result(seat, rec)+ self.pending[seat] = i+ if len(self.pending) < 2:+ return {"committed": i, "phrase": len(self.bout.log) + 1,+ "note": "kept hidden until the other fencer has chosen; the phrase is fenced then"}+ choices, self.pending = self.pending, {}+ rec = self._phrase(choices)+ return self._result(seat, rec)++ def _result(self, seat, rec):+ v = self._phrase_view(rec, seat)+ return {"phrase": v["n"], "you": v["you"], "opponent": v["opponent"], "result": v["result"],+ "score": v["score_after"], "bout_over": self.bout.over}++ def forfeit(self, seat, why):+ self.bout.forfeit(self.cfg.side_of(seat), why)+ return True++ def to_move(self):+ if self.bout.over:+ return None+ if self.single:+ return self.cfg.seats[0]+ return self.first if self.first not in self.pending else self.second++ def phase(self):+ return Phase(FINISHED, reason=self.bout.how or "bout_over") if self.bout.over else Phase(PLAYING)++ def unit(self):+ return len(self.bout.log)++ def scores(self):+ return dict(self.bout.score)++ def tiebreaks(self):+ """FIE t.38 and t.124 as bout.py decides it: 15 touches; the P-black card for unwillingness to fight; at time+ the fencer ahead; the deciding touch of the extra minute; the priority drawn by lot before it (the last rule+ always decides)."""+ rules = [(n, (lambda m, n=n: m.bout.winner if m.bout.how == n else None)) for n in TIEBREAKS[:-1]]+ return rules + [(TIEBREAKS[-1], lambda m: m.bout.winner)]++ def state_digest(self):+ st = dict(bout=self.bout.state(), pending=self.pending, k=self.k, table=self.table.sha,+ opp=None if self.opp is None else self.opp.state())+ return hashlib.sha256(json.dumps(st, sort_keys=True, default=str).encode()).hexdigest()++ # ---------------------------------------------------------------- actions+ def schema(self, seat):+ return SCHEMA++ # ---------------------------------------------------------------- observation+ def _phrase_view(self, r, seat):+ me = self.cfg.side_of(seat)+ ot = self.other(me)+ res = r["res"]+ result = "you" if res == me else "opponent" if res == ot else res+ if r.get("annulled"):+ result = "double, not counted at 14-14"+ out = {"n": r["n"], "you": r["intentions"][me], "opponent": r["intentions"][ot], "result": result,+ "seconds": r["s"], "your_delay_ms": r["delays_ms"][me], "opponent_delay_ms": r["delays_ms"][ot],+ "score_after": {"you": r["score"][me], "opponent": r["score"][ot]}}+ if r.get("cut_by_clock"):+ out["cut_by_clock"] = True+ if r.get("card"):+ out["card"] = r["card"] if r["card"] != "P-black" else \+ f"P-black to {'you' if r['black'] == me else 'the opponent'}"+ if r.get("extra_minute_starts"):+ out["extra_minute_starts"] = True+ return out++ def observe(self, seat, query=None):+ b, me = self.bout, self.cfg.side_of(seat)+ ot = self.other(me)+ out = {"score": {"you": b.score[me], "opponent": b.score[ot]}, "phrase": len(b.log) + 1,+ "fencing_time_s": round(b.t, 2), "time_left_s": b.time_left_s(), "extra_minute": b.extra,+ "priority": None if b.priority is None else ("you" if b.priority == me else "opponent"),+ "passivity": {"no_hit_s": b.no_hit_s(), "limit_s": BT.PASSIVE_S, "p_cards": b.p_calls},+ "phrases": [self._phrase_view(r, seat) for r in b.log]}+ if not self.single:+ out["committed"] = self.pending.get(me)+ return out++ def _snaps(self, seat):+ if not self.bout.log:+ q = self.table.guard_qpos()+ return [dict(label="on guard", qpos=q), dict(label="on guard", qpos=q)]+ r = self.bout.log[-1]+ steps, qs = self.table.frames(r["row"])+ seat_a = self.cfg.seats[0] if self.single else "A"+ turn = r["ends"].get(seat_a, "A") != "A" # seat A's fencer fenced from the table's end B+ m = _scene_model()+ out = []+ for s, q, what in zip(steps, qs, ("half-way", "end")):+ q = CAM.half_turn(m, q) if turn else q+ out.append(dict(label=f"phrase {r['n']} {what}: {(int(s) + 1) * PH.STEP_S:.2f} s", qpos=q))+ return out++ def camera_job(self, seat):+ job = {"seat": seat, "snaps": self._snaps(seat)}+ return job, dict(image_layout=CAM.IMAGE_LAYOUT, phrase=len(self.bout.log))++ def render_state(self):+ return {"qpos": [float(x) for x in self._snaps(self.cfg.seats[0])[-1]["qpos"]]}++ def final_fields(self):+ b = self.bout+ out = {"phrases": b.log, "extra_minute": b.extra, "priority": b.priority, "how": b.how,+ "fencing_time_s": round(b.t, 2), "first_player": self.first, "p_cards": b.p_calls,+ "touches": b.T, "table_sha256": self.table.sha}+ if self.single:+ out["level"] = self.level+ return out+++_MODEL: dict = {}+++def _scene_model():+ if "m" not in _MODEL:+ import mujoco as mj+ _MODEL["m"] = mj.MjModel.from_xml_string(F.scene_xml())+ return _MODEL["m"]+++_RENDER: dict = {}+++class Fencing:+ name = "fencing"+ protocol = "turn"+ revision = REVISION+ source_dirs = [HERE]+ workers = ("render",)++ def build(self, cfg):+ return FencingMatch(cfg)++ def action_layer(self, level):+ if level != "low":+ raise ValueError("fencing-7 has the low level only (sport.toml [modes]): the intention for a phrase")+ return SchemaLayer()++ def worker_init(self, kind, seat, cfg):+ r = CAM.Renderer(seat)+ q = PH.table().guard_qpos()+ r.render([dict(label="on guard", qpos=q)] * CAM.N_FRAMES) # the GL context before 'ready'+ return r++ def worker_call(self, obj, kind, job):+ if obj is None: # in-process (core/local.py): one renderer per seat+ obj = _RENDER.get(job["seat"]) or _RENDER.setdefault(job["seat"], CAM.Renderer(job["seat"]))+ return {"png": obj.render(job["snaps"])}++ def scene(self, cfg):+ from renderers.base import Scene+ return Scene(xml=F.scene_xml(), assets={})++ def spec(self, cfg, seat, match):+ t = PH.table()+ C = t.counts()+ names = t.names+ out = dict(+ cameras=CAM.cam_info(), image=CAM.IMAGE_LAYOUT,+ intentions={s: INTENTION_DOC[s] for s in names},+ phrase_table=dict(+ note=("your chances against each intention of the opponent: for each pair 'yours|theirs', the phrases "+ f"out of {int(C[0, 0].sum())} (both ends of the piste x {t.J} x {t.J} start delays) that end "+ "with a touch for you alone, for the opponent alone, a double, or no touch; every phrase draws "+ "its delays and ends from the seed, the same for both fencers"),+ columns=["you", "opponent", "double", "none"],+ counts={f"{a}|{b}": [int(x) for x in C[i, j]] for i, a in enumerate(names)+ for j, b in enumerate(names)}),+ phrase=dict(gap_m=t.gap_m, start_delay_ms=[0, 10 * (t.J - 1)], max_s=t.max_s,+ source="measured in the fencing-6 world (docs/screening/fencing/phrase/)"),+ bout=dict(touches=BT.TOUCHES, time_s=BT.regulation_s(BT.TOUCHES), extra_minute_s=BT.EXTRA_S,+ passivity_s=BT.PASSIVE_S))+ if len(cfg.side_list()) == 1:+ lv = int(cfg.level or 1)+ out["opponent"] = dict(level=lv, levels="1-2: level 2 is stronger",+ plays=("it chooses its intention before each phrase from what it has seen of the "+ "bout (both fencers' intentions and the results), never from yours for "+ "this phrase; it knows the phrase table"))+ else:+ out["first_player"] = cfg.first or "A"+ return out++ def players(self):+ import builtin_players as bp+ return {"reference": bp.Reference, "rival": bp.Rival, "random": bp.Random}+++SPORT = Fencing()diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/reference_check.py b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/reference_check.pynew file mode 100644index 0000000000..cb57b9f4c6--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/reference_check.py@@ -0,0 +1,42 @@+"""The reference check of tools/check stage 5 (docs/screening/README.md "Reference check", sport.toml [reference]):+one bout of the reference (builtin_players.Reference) against the scripted fencer at a level, played as the step-4+screening on the sport plays it (docs/screening/fencing/phrase/game/step4_sport.py): the player answers every phrase+from `game spec` and its state, the phrase is fenced at once.++ perception "truth" and "camera" are the same player on the same view: a seat's observation of a phrase is the+ referee's record of it (the intentions, the delays, the result: `state` phrases), and the reference+ reads nothing else; the images (a half-way and an end snapshot of the last phrase) carry no+ information the record does not, so none are drawn++Returns {"won", "scores": [ours, theirs], "perception", "report": {"touches": [ours, both], "phrases_won": [phrases+with our touch only, phrases]}}.+"""+from __future__ import annotations++import os+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+++def reference_match(format: str = "bout", level: int | None = 1, seed: int = 1, perception: str = "truth") -> dict:+ if perception not in ("truth", "camera"):+ raise ValueError(f"perception must be truth or camera, not {perception!r}")+ if format != "bout":+ raise ValueError("the opponent calibration is for format bout (the scripted fencer)")+ if HERE not in sys.path:+ sys.path.insert(0, HERE)+ import builtin_players as BP+ import plugin as PL+ from core.sport import MatchConfig++ cfg = MatchConfig(sport="fencing", format="bout", seats=("A",), seed=int(seed),+ level=1 if level is None else int(level), action_level="low")+ m = PL.SPORT.build(cfg)+ ref = BP.Reference({"seat": "A", "action_level": "low", **PL.SPORT.spec(cfg, "A", m)}, "A", int(seed))+ while not m.bout.over:+ m.apply("A", ref.act({"state": {"seat": "A", **m.observe("A")}}))+ ours, theirs = m.bout.score["A"], m.bout.score[m.other("A")]+ won = sum(m._phrase_view(r, "A")["result"] == "you" for r in m.bout.log)+ return {"won": m.bout.winner == "A", "scores": [ours, theirs], "perception": perception,+ "report": {"touches": [ours, ours + theirs], "phrases_won": [won, len(m.bout.log)]}}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/rules_check.md b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/rules_check.mdnew file mode 100644index 0000000000..9ed4fbc2da--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/rules_check.md@@ -0,0 +1,42 @@+# Fencing (epee): the rules check (fencing-7, the phrase-level sport)++Every article and value cited by the fencing tasks (README, prompt, code), checked against the two PDFs of the FIE+rules, edition of August 2026:++- Technical Rules: https://static.fie.org/uploads/40/204126-Technical%20rules%20August%202026%20ang.pdf+- Material Rules: https://static.fie.org/uploads/40/204156-book%20material%20August%202026%20ang.pdf++The bout (bout.py):++| Article | The rulebook says | Implemented | |+|---|---|---|---|+| t.22 | the fencers come on guard before 'Play!' | every phrase starts on guard, 1.95 m apart (pelvis to pelvis) | deviation D1 (the distance: closer than the on-guard lines) |+| t.37 | duration = effective fencing time between 'Play!' and 'Halt!' | each phrase takes its measured time to the halt (3 s without a touch) | match |+| t.39.1 | direct elimination: 15 hits, or three periods of three minutes with a one-minute rest between | 15 touches, 9 minutes of fencing time as one period | deviation D4 (no rests) |+| t.40.1-2 | the bout ends at 15 hits or after 9 minutes of effective fencing time; more hits wins | the same | match |+| t.40.3 | equal at the end of regulation time: one minute for a deciding hit, the winner if still equal drawn by lot before it | the same (the lot seeded by the seed, drawn for the first fencer) | match |+| t.38.1.b | (pools) at epee at 4-4 a double hit is not counted | at 14-14 a double is not counted | deviation D5 (no clause for 14-14 in direct elimination) |+| t.44.1 | at the end of time the apparatus is cut off; hits registered before count | a phrase whose touch would come after the end of time ends without it | match |+| t.92 | both hit and both registered: a double hit, one hit against each | the same; in the extra minute the scores stay equal and the minute goes on | match |+| t.124 (1, 3) | one minute of fencing without a hit: 'Halt!'; direct elimination: 1st time P-red to both, 2nd time P-black to the lower score (equal: the lower seeding, lots among fencers not ranked); no P-card at 14-14; the minute restarts after each hit, hit off the target, annulled hit, penalty hit and at each period; not when the scores are equal at the end of regulation time | 60 s of fencing time without a touch: 1st P-red to both (a penalty touch each), 2nd P-black to the lower score (equal: a seeded lot), no card at 14-14, the minute restarts after touches, doubles, annulled doubles and P-red cards; not in the extra minute | match (one period: D4; the lot: D9) |+| t.170 (0.5) | the P-cards of t.124 | the same | match |++The phrases (measured in fencing-6's world, docs/screening/fencing/phrase/):++| Article | The rulebook says | In the measured phrases | |+|---|---|---|---|+| t.24 | fencing at close quarters allowed while the weapons can be wielded | arms and blades touching: the phrase goes on | match |+| t.25, t.33-t.35, t.56.10 | corps a corps, a limit crossed, a fall halt the phrase; a hit during or after a fall is annulled | fencing-6's referee: such a phrase would end without a touch; none of the 2916 phrases did | deviation D3 |+| t.90.1 | epee: thrusting weapon, hits only with the point | only the point registers | match |+| t.91 | target: the whole body, clothing and equipment | the whole robot, not its epee | match (D2: the robot is the body) |+| t.93 / t.94.1, Annexe B (d) | hits on the ground, between points or on the guard are not registered / annulled | the point on the floor, the opponent's blade, guard or grip does not register | match |+| m.14 | the epee ready for use weighs less than 770 g | 0.455 kg (a standard-parts epee, bodies/hands/epee.xml) | match |+| m.16.3 | blade at most 90 cm | 0.90 m | match |+| m.17.1 | guard passes a 13.5 cm gauge, depth 3-5.5 cm | 13.5 cm diameter (a 1 cm disc: the library's epee) | match (diameter; depth: D10) |+| m.19.2 | the point registers under a pressure of more than 750 g | more than 7.35 N (750 g x 9.81 m/s^2) on the point along the blade | match |+| Annexe B, B. Epee (b) | under 40 ms between hits: a double; over 50 ms: one hit; tolerance between | 45 ms lockout | match |+| Annexe B, B. Epee (c) | hits of 2-10 ms registered; nothing under 2 ms | at least 2 ms (3 consecutive 1 ms samples) | match |++Deviations that are not in the rulebook's articles: the fencers are the robot library's Unitree G1 humanoids on+NVIDIA's SONIC whole-body policy, commanded by intentions (D8); the ends of the piste are drawn per phrase (D11); the+sport is a preview, a strategy special case accepted by the maintainers (D12).diff --git a/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/sport.toml b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/sport.tomlnew file mode 100644index 0000000000..2d08e2c03e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/environment/sim/sport/sport.toml@@ -0,0 +1,239 @@+# fencing (epee): one FIE direct-elimination bout between two robot fencers, fenced phrase by phrase (docs/framework_zh.md+# §4.2, §8). fencing-7 (the owner's decision of 2026-10-13): the phrase-level construction. Every phrase starts on guard;+# each fencer chooses an intention, executed by fixed skills on a Unitree G1 humanoid (NVIDIA's SONIC whole-body+# policy tracking our fencing motions, the point skill on the sword arm); the phrases were measured in the fencing-6+# world and are replayed from a table (phrases.py). Screening: docs/screening/fencing.md (section 6, "Phrase-level+# construction"). The simulator: phrases.py (the phrases), bout.py (the bout referee), opponent.py (the scripted+# fencer), fencing.py + cameras.py (the scene and the images). The declarations below are data: the core,+# tools/generate.py, tools/check and the prompt read them.+#+# A PREVIEW (the maintainers, Chi, 2026-10-14): accepted as a strategy special case, publishable and open to model runs,+# but not counted in the main board's capability statistics (deviation D12). It departs from the construction rules+# (docs/construction_zh.md P1/P2/P5, docs/framework_zh.md §6.3.1): the command is a tactical intention for a whole+# phrase, and four intentions (rline, stop, counter, draw) carry a fixed, published trigger; the agent's skill is+# choosing and reading the opponent, not moving the robot. tools/check stage 1 fails on [capabilities] (none of a1-a3+# is 2), declared honestly. A next version should bring distance and timing back (choosing the starting gap or the+# moment to go, or a free starting gap once our own footwork and lunge policy is trained).++[sport]+name = "fencing"+title = "Robot epee fencing"+summary = "two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time"+protocol = "turn"+revision = "fencing-7+core-0.2" # bump on any change that alters play (the phrase table, the rules, the opponent, the observation)+physics = "the phrases: MuJoCo 3.3.7 (1 ms physics steps, 10 ms control steps), two Unitree G1 of the robot library (bodies/unitree_g1, 29 DOF; Unitree's motor torque-speed curves through the library's output stage) with epees, robot x robot, blade x body and blade x blade contacts (bodies/contacts.py), NVIDIA SONIC (GR00T-WholeBodyControl b042411) on the legs, waist and free arm, the point skill on the sword arm, fencing-6's apparatus and phrase referee; each of the 2916 phrases measured once in that world (it is deterministic: 2799 earlier measurements of 1953 of the phrases all ended as in that run, with the same result at the same step) and replayed from sports/fencing/phrases/table.json"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"+publish = true # both formats are PREVIEW formats ([formats.*] preview = true, D12)+category = "robotics-sports-arena"++[body] # the robot library (bodies/README.md): the robot and its tool, for the scene+name = "unitree_g1"+hand = "epee" # bodies/hands/epee.xml (a real epee's mass, #88)+controllers = [] # the phrases are replayed; their controllers (SONIC, the point skill) ran when they were measured++[rulebook]+name = "FIE Technical Rules (t.) and Material Rules (m.), epee"+version = "August 2026"+url = "https://static.fie.org/uploads/40/204126-Technical%20rules%20August%202026%20ang.pdf"+articles = "on guard (t.22); fencing time (t.37); direct-elimination bout to 15 hits or three periods of three minutes with a one-minute rest, 9 minutes of effective fencing time; more hits wins; equal at time: one minute for a deciding hit, the winner if still equal drawn by lot before it (t.39, t.40); at 4-4 in a pool bout at epee a double hit is not counted (t.38.1.b); clock end (t.44); epee: point only, whole body target, double hits count for both (t.90-t.93); unwillingness to fight: one minute of fencing without a hit, P-red to both, then P-black to the lower score, no P-card at 14-14 (t.124, t.170 0.5); the epee under 770 g (m.14); point pressure more than 750 g (m.19.2); apparatus: hits of 2-10 ms registered, none under 2 ms, double-hit window 40-50 ms (Material Rules Annexe B, B. Epee); blade at most 90 cm (m.16.3), guard through a 13.5 cm gauge (m.17.1)"+material_rules = "https://static.fie.org/uploads/40/204156-book%20material%20August%202026%20ang.pdf"+rules_check = "sports/fencing/rules_check.md (every article and value checked against the two PDFs)"++[[deviations]]+id = "D1"+rule = "t.22, t.28-t.31 (the bout's phrases and footwork)"+text = "the bout is fenced phrase by phrase: every phrase starts with both fencers on guard 1.95 m apart (pelvis to pelvis), each fencer chooses one of nine intentions (`game spec` intentions) executed by fixed skills on the robot, each starts its intention after 0, 10, ... or 50 ms (drawn per phrase), and the phrase ends at the first touch or after 3 s without one; distance, footwork between phrases and the length of the piste are not part of the bout (the screening found the robots' footwork too slow for a bout over the piste: docs/screening/fencing.md)"+affects_result = true+[[deviations]]+id = "D2"+rule = "t.91, m.19, Material Rules Annexe B"+text = "the robot's whole structure is the target (t.91: the whole body), its epee (guard, blade, grip) is not; the apparatus measures the force on the point along the blade (> 7.35 N for >= 2 ms, three consecutive 1 ms samples; lockout 45 ms, inside the 40-50 ms tolerance)"+affects_result = true+[[deviations]]+id = "D3"+rule = "t.24, t.25, t.33-t.35, t.56.10"+text = "a phrase that ended in a fall, a corps-a-corps or a fencer over a limit counts as a phrase without a touch (none of the 2916 measured phrases did)"+affects_result = false+[[deviations]]+id = "D4"+rule = "t.39, t.40"+text = "the 9 minutes of fencing time are one period (no one-minute rests); every phrase takes its measured fencing time (to the halt, 3 s without a touch)"+affects_result = true+[[deviations]]+id = "D5"+rule = "t.38.1.b"+text = "at 14-14 a double touch is not counted (the pool bout's rule at 4-4 applied to the 15-touch bout; the 2026 rules have no clause for 14-14 in direct elimination)"+affects_result = true+[[deviations]]+id = "D6"+rule = "t.158-t.170"+text = "no cards or penalties (the robots cannot commit the faults they punish), except the P-cards for unwillingness to fight (t.124)"+affects_result = false+[[deviations]]+id = "D7"+rule = "t.39 (competition formula)"+text = "one direct-elimination bout instead of a competition"+affects_result = false+[[deviations]]+id = "D8"+rule = "-"+text = "the fencer is the robot library's Unitree G1 (bodies/unitree_g1) with the epee on its right wrist mount, its legs, waist and free arm on NVIDIA's SONIC whole-body policy (tracking our en garde, step and lunge motions), its sword arm on the point skill; a lunge from guard covers about 0.25 m in 0.4 s, so the phrases are fenced from 1.95 m, where a lunge reaches the chest; you command it by intentions, not by motions"+affects_result = true+[[deviations]]+id = "D9"+rule = "t.124"+text = "unwillingness to fight as the FIE applies it to direct-elimination bouts (t.124.1): one minute of fencing time without a hit -> 'Halt!'; the first time a P-red card to both fencers, a penalty hit each; the second time the P-black card to the fencer with the lower score, who loses the bout, at equal scores to the fencer who loses a seeded lot (t.124.1.b.i: lots for fencers not in the FIE ranking); no P-card at 14-14 (t.124.3.a): the minute restarts; the minute restarts after each hit, double, annulled double and penalty hit (t.124.3.d), not after a phrase without a touch; t.124 does not apply in the extra minute (t.124.3.f)"+affects_result = true+[[deviations]]+id = "D10"+rule = "m.14-m.19"+text = "the epee is rigid (its blade does not bend) and its point is a sphere; its mass is a real standard-parts epee's (Leon Paul: 0.455 kg, balance 12 cm in front of the guard; bodies/hands/epee.xml)"+affects_result = false+[[deviations]]+id = "D11"+rule = "-"+text = "the two ends of the piste are not exactly alike in the simulation (the same phrase fenced from the other end ends differently in 205 of the 1431 pairs of mirrored phrases, about one in seven), so each phrase draws the end each fencer fences from, with probability 1/2 each: both fencers meet the same chances"+affects_result = true+[[deviations]]+id = "D12"+rule = "-"+text = "a preview, accepted by the maintainers (2026-10-14) as a strategy special case: a symmetric zero-sum game of intentions whose phrase table comes from the physics; the agent controls neither distance nor timing, so it is tested on reading the opponent only (capabilities a1 0, a2 0, a3 1, b2 2; tools/check stage 1 requires one of a1-a3 primary and fails), against construction_zh.md P1/P2/P5 (skills take motion targets and do not choose strategy) and framework_zh.md §6.3.1; publishable and open to model runs, not counted in the main board's capability statistics (both formats `preview = true`: never an official configuration, no hidden seeds)"+affects_result = false++[formats.bout] # seat A against the scripted fencer (opponent.Opponent; side B)+preview = true # D12: playable, never official (core 0.2.21: official_config = 0; tools/seeds.py: no cell)+seats = ["A"]+opponent = true # success = winning a valid bout (core/grading.py)+levels = [1, 2] # the opponent level (RCB_LEVEL; default 1)+[formats.duel]+preview = true # D12, as bout+seats = ["A", "B"]+first = ["A", "B"] # the first player chooses first in every phrase (kept hidden), is the first fencer of the phrase draws and of the lots++[modes]+action_levels = ["low"] # the intention for a phrase is the robot's whole command, as a release command in the other turn sports+plays = ["program"]++[timing]+clock_s = 3600 # turn protocol: each seat's chess clock, on its own turn only+start_timeout_s = 1800++[actions.cli] # `game phrase lunge`+low = { phrase = ["intention"] }++[observation]+fields = ["score", "phrase", "fencing_time_s", "time_left_s", "extra_minute", "priority", "passivity", "phrases",+ "committed"]+renderer = "mujoco" # the images are drawn by the sport (cameras.py, MuJoCo osmesa) in each seat's render worker+frame_budget_ms = 4000 # 4 tiles of 800 x 360, osmesa on the CPU+columns = 2++[spec] # the rule constants (/spec adds the intentions, the phrase table, the cameras)+bout = "one FIE direct-elimination bout (t.39-t.40): the first to 15 touches wins; 9 minutes of fencing time (one period); at time the fencer ahead wins; at equal scores one more minute for a deciding touch with priority drawn by lot before it (seeded), the priority holder winning if still equal; a double touch counts for both except at 14-14 (not counted); in the extra minute a double leaves the scores equal. Unwillingness to fight (t.124): one minute of fencing time without a touch: the first time both fencers get a P-red card, a penalty touch each; the second time the fencer with the lower score gets the P-black card and loses the bout (at equal scores: the one who loses a lot, seeded); no card at 14-14; the minute restarts after every touch, double, annulled double and penalty touch, not after a phrase without a touch; it does not apply in the extra minute (observation `passivity`)"+phrase = "every phrase starts with both fencers on guard 1.95 m apart; each fencer has chosen one intention (`game spec` intentions) and starts it after 0, 10, 20, 30, 40 or 50 ms (each equally likely, drawn for each fencer and phrase from the seed, after both have chosen); the phrase ends at the first touch (the apparatus: the point's force along the blade above 7.35 N for 2 ms on the opponent's body; the other's touch within 45 ms is a double) or after 3 s without one; it takes its fencing time from the bout clock (a clock that ends during a phrase ends it without a touch, t.44). The phrases were measured in MuJoCo (D1, D8); `game spec` phrase_table gives, for every pair of intentions, how many of the 72 equally likely phrases (36 pairs of delays x both ends of the piste) end with a touch for you, for the opponent, a double or none"+duel = "both players choose their intention for the next phrase; the first player's choice is kept hidden from the other until the phrase is fenced"+observation = "the state: the score, the phrase number, the fencing time and the time left, the extra minute and the priority, the passivity minute and the P-cards, and every phrase so far (your intention and the opponent's, both start delays, the result, its fencing time, the score after it, cards); the image: 2 rows (side camera beside the piste, top camera above it) x 2 columns (the last phrase half-way and at its end) of 800 x 360 tiles, your robot red, the opponent blue, the points yellow"+scripted_opponent = "format bout: the computer fencer chooses its intention before each phrase from what it has seen of the bout (both fencers' intentions and the results), never from your choice for this phrase; it knows the phrase table. Level 1 reads you with a few simple models of a player (repeats, answers, copies, plays what just won, goes round the menu) but mostly keeps a slow habit (the best answer to your whole-bout mix); level 2 predicts your next intention from your patterns, also models how you read it, answers what it expects, and now and then plays the table's equilibrium mix"++[tiebreaks]+order = ["touches", "passivity", "time", "deciding_touch", "priority"]+text = "the first to 15 touches wins (FIE t.40.1); a second minute without a touch (unwillingness to fight, FIE t.124) loses the bout for the fencer with the lower score, at equal scores for the one who loses a lot (seeded); at the end of the 9 minutes the fencer ahead wins; at equal scores one more minute is fenced and the first touch decides; if the scores are still equal after it, the fencer with priority, drawn by lot (seeded) before the extra minute, wins (FIE t.40.3)"+last_resort_in_prompt = true++[[exploits]]+id = "E1"+text = "an unknown intention, a wrong type, an extra field (a start delay or an end chosen by the player) is refused and changes nothing"+test = "test_exploit_bad_intentions_refused"+[[exploits]]+id = "E2"+text = "the scripted fencer chooses its intention for a phrase without seeing the agent's: after the same bout so far, every choice of the agent meets the same intention"+test = "test_exploit_opponent_cannot_see_your_choice"+[[exploits]]+id = "E3"+text = "format duel: the first player's choice stays out of the other player's observation until the phrase is fenced"+test = "test_exploit_duel_choice_hidden"+[[exploits]]+id = "E4"+text = "`game spec` phrase_table is the table the bout plays (all 2916 phrases, 72 per pair over both ends), and every phrase of a bout is the table's phrase for its delays and ends"+test = "test_exploit_spec_is_the_simulator"+[[exploits]]+id = "E5"+text = "the start delays and the ends of the piste come from the seed and the phrase number, not from the intentions (uniform over 0-50 ms; each end with probability 1/2)"+test = "test_exploit_phrase_draws_seeded_not_chosen"+[[exploits]]+id = "E6"+text = "every bout has a winner (touches, passivity, time, the deciding touch or the priority), also when nobody ever touches"+test = "test_exploit_no_draws"+[[exploits]]+id = "E7"+text = "stalling does not pay: both fencers retreating every phrase get the P-red cards after a minute and the P-black card decides the bout after the next"+test = "test_exploit_passivity_cards"+[[exploits]]+id = "E8"+text = "a fixed intention every phrase, or a uniformly random one, loses the majority of its bouts against level 1"+test = "test_exploit_simple_programs_lose"+[[exploits]]+id = "E9"+text = "at 14-14 a double is not counted and the minute restarts; at 13-14 it ends the bout"+test = "test_exploit_double_at_14_14_not_counted"+[[exploits]]+id = "E10"+text = "a phrase whose touch would come after the end of time ends without it (t.44); equal scores at time start the extra minute with priority drawn"+test = "test_exploit_clock_ends_the_phrase"++[players]+reference = "reference" # Sport.players() names: reads only `game spec` and the state+reference_class = "builtin_players:Reference"+check = ["random"] # policies for the generic tests++[fairness]+policy = "rival" # the reference drawing from a stream of the seed and its seat+matches_per_order = 400 # N = 800: 95% CI about +-3.5 pp+max_advantage_pp = 5+mirror = "exact" # the phrase draws and the lots follow the first order, not the seat++[official]+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222]+first_any = true+levels = [1, 2]++[score] # the continuous score (core/score.py)+name = "touch_share"+text = "touches scored / touches scored by both fencers (a double counts for both; 0.5 if neither scored)"+from = "share"+forfeit = 0.0+range = [0, 1]++[reference] # tools/check stage 5, the reference check (docs/screening/README.md)+match = "reference_check:reference_match" # one bout of the reference against the scripted fencer, as step 4 plays it; camera = truth (no images to read)+seeds = 200 # seeds 1..200 per level: at the step-4 rates (61.5 %, 48.0 %) 20 seeds fail the check 1 time in 3, 200 seeds 1 in 300+camera_seeds = 200 # the same player as truth, so the same seeds++[golden]+episodes = "golden" # sports/fencing/golden/<case>/++[[tasks]]+format = "bout"+action_level = "low"+id = "fencing-bout-wallclock-program-standard" # the Season-1 task names ([[tasks]] id)+[[tasks]]+format = "duel"+action_level = "low"+id = "fencing-duel-wallclock-program-standard"++[broadcast] # spectators: the replay video's camera+camera = { name = "broadcast", pos = [0.0, -7.95, 1.75], lookat = [0.0, 0.0, 0.8], fovy_deg = 45, width = 960, height = 400 }++[capabilities] # docs/capabilities_zh.md+a1 = 0 # no perception: the state gives every phrase's intentions and result+a2 = 0 # the phrases' physics is measured; the agent does not predict it+a3 = 1 # what each intention does on this robot (the phrase table), not how to move it+a4 = 0 # turn-based: no real-time timing+b1 = 1 # FIE rules (15 touches, 14-14, the clock, unwillingness to fight, the extra minute, priority) shape the bout and the state, but no evidence yet that using them pays: a reference that stalls when ahead lost 5 points of touch share (screening report, section 6)+b2 = 2 # reading the opponent: the levels adapt to the agent's patterns; the reference without reading (the equilibrium mix) does clearly worse at level 1 (screening report, section 6)+b3 = 0+physics = ["contact"]++[check] # tools/check limits+stage_timeout_s = 28800 # stage 4: 800 rendered duels in the image (osmesa, 2 seats' 2 x 2 tiles per phrase) at about 23 s each, about 5 hdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/instruction.md b/tasks/roboolympics-fencing-bout-i01-standard/instruction.mdnew file mode 100644index 0000000000..7626bde96e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/instruction.md@@ -0,0 +1,69 @@+# Robot epee fencing: program play (bout)++You play robot epee fencing against a scripted opponent (you are seat `A`). Two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time.+This is RoboOlympics task `fencing-bout-wallclock-program-standard` (revision `fencing-7+core-0.2`), one frozen instance: the scripted opponent at level 1; the seed is fixed and never shown. The simulator service is at `http://localhost:8000`.++## Time+Nothing moves while you think: the world waits for the player whose turn it is. Each player has a chess clock of 60 minutes of real time, running only on its own turn (thinking, tool calls, your programs and your reviews all count). **If your clock runs out, you lose.**++After each of your actions (except one that ends the match), send `game ready "WHY" "PLAN"` (a short review) before the game goes on.+The match is graded when your session ends: stay until it is over. **If your session ends before the match is over, you lose the match** (a valid result, success 0), also if you never sent `game start`.++## Write a program+You may write a program that observes, measures in the images, computes your next action and sends it, without a+new model response for each action. You stay in the loop: watch its log, and stop, fix and restart it whenever+needed. Only you send `game start` and `game ready`.++- Use only the camera images, the service's replies and this document; no simulator internals or hidden state.+- One action at a time: an action sent before the previous one has returned is refused (HTTP 429).+- Your container: Python 3.12 with numpy, SciPy and Pillow; the network reaches only your model's API and the package registries. Keep your scripts, logs+ and notes in `/app/output/`.++## Interface+Use the `game` command, or the same calls as HTTP with JSON at `http://localhost:8000/<SEAT>/` (your seat is `$SEAT`):++| `game` command | HTTP | |+| --- | --- | --- |+| `game spec` | `GET /spec` | the actions (types, fields, ranges), the cameras with their intrinsics, the rule constants |+| `game status` | `GET /status` | the current state, no image |+| `game start` | `POST /start {}` | you are ready; the match begins when every seat has started |+| `game wait` | `POST /wait {"timeout_s": 60}` | block until it is your turn (or the match is over) |+| `game observe` | `POST /observe {}` | the state and the camera images (one PNG of tiles: `observation.tiles`) |+| `game act JSON` | `POST /act JSON` | one action |+| `game phrase INTENTION` | `POST /act {"type":"phrase", ...}` | one action (`game spec` lists the fields and ranges) |+| `game ready "WHY" "PLAN"` | `POST /ready {"why":"...","plan":"..."}` | your review after each of your actions |++Errors: 400 = an invalid action (nothing happens), 409 = not now (not your turn, or a review is due), 429 = one+action in flight, or more than 20 requests per second or 4 open requests from your seat (empty body: retry more slowly).++## Rules+- two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time.+- `bout`: one FIE direct-elimination bout (t.39-t.40): the first to 15 touches wins; 9 minutes of fencing time (one period); at time the fencer ahead wins; at equal scores one more minute for a deciding touch with priority drawn by lot before it (seeded), the priority holder winning if still equal; a double touch counts for both except at 14-14 (not counted); in the extra minute a double leaves the scores equal. Unwillingness to fight (t.124): one minute of fencing time without a touch: the first time both fencers get a P-red card, a penalty touch each; the second time the fencer with the lower score gets the P-black card and loses the bout (at equal scores: the one who loses a lot, seeded); no card at 14-14; the minute restarts after every touch, double, annulled double and penalty touch, not after a phrase without a touch; it does not apply in the extra minute (observation `passivity`)+- `phrase`: every phrase starts with both fencers on guard 1.95 m apart; each fencer has chosen one intention (`game spec` intentions) and starts it after 0, 10, 20, 30, 40 or 50 ms (each equally likely, drawn for each fencer and phrase from the seed, after both have chosen); the phrase ends at the first touch (the apparatus: the point's force along the blade above 7.35 N for 2 ms on the opponent's body; the other's touch within 45 ms is a double) or after 3 s without one; it takes its fencing time from the bout clock (a clock that ends during a phrase ends it without a touch, t.44). The phrases were measured in MuJoCo (D1, D8); `game spec` phrase_table gives, for every pair of intentions, how many of the 72 equally likely phrases (36 pairs of delays x both ends of the piste) end with a touch for you, for the opponent, a double or none+- `duel`: both players choose their intention for the next phrase; the first player's choice is kept hidden from the other until the phrase is fenced+- `observation`: the state: the score, the phrase number, the fencing time and the time left, the extra minute and the priority, the passivity minute and the P-cards, and every phrase so far (your intention and the opponent's, both start delays, the result, its fencing time, the score after it, cards); the image: 2 rows (side camera beside the piste, top camera above it) x 2 columns (the last phrase half-way and at its end) of 800 x 360 tiles, your robot red, the opponent blue, the points yellow+- `scripted_opponent`: format bout: the computer fencer chooses its intention before each phrase from what it has seen of the bout (both fencers' intentions and the results), never from your choice for this phrase; it knows the phrase table. Level 1 reads you with a few simple models of a player (repeats, answers, copies, plays what just won, goes round the menu) but mostly keeps a slow habit (the best answer to your whole-bout mix); level 2 predicts your next intention from your patterns, also models how you read it, answers what it expects, and now and then plays the table's equilibrium mix+- Winner: the first to 15 touches wins (FIE t.40.1); a second minute without a touch (unwillingness to fight, FIE t.124) loses the bout for the fencer with the lower score, at equal scores for the one who loses a lot (seeded); at the end of the 9 minutes the fencer ahead wins; at equal scores one more minute is fenced and the first touch decides; if the scores are still equal after it, the fencer with priority, drawn by lot (seeded) before the extra minute, wins (FIE t.40.3). There are no draws.+- Deviation D1 (rulebook t.22, t.28-t.31 (the bout's phrases and footwork)): the bout is fenced phrase by phrase: every phrase starts with both fencers on guard 1.95 m apart (pelvis to pelvis), each fencer chooses one of nine intentions (`game spec` intentions) executed by fixed skills on the robot, each starts its intention after 0, 10, ... or 50 ms (drawn per phrase), and the phrase ends at the first touch or after 3 s without one; distance, footwork between phrases and the length of the piste are not part of the bout (the screening found the robots' footwork too slow for a bout over the piste: docs/screening/fencing.md)+- Deviation D2 (rulebook t.91, m.19, Material Rules Annexe B): the robot's whole structure is the target (t.91: the whole body), its epee (guard, blade, grip) is not; the apparatus measures the force on the point along the blade (> 7.35 N for >= 2 ms, three consecutive 1 ms samples; lockout 45 ms, inside the 40-50 ms tolerance)+- Deviation D4 (rulebook t.39, t.40): the 9 minutes of fencing time are one period (no one-minute rests); every phrase takes its measured fencing time (to the halt, 3 s without a touch)+- Deviation D5 (rulebook t.38.1.b): at 14-14 a double touch is not counted (the pool bout's rule at 4-4 applied to the 15-touch bout; the 2026 rules have no clause for 14-14 in direct elimination)+- Deviation D8 (rulebook -): the fencer is the robot library's Unitree G1 (bodies/unitree_g1) with the epee on its right wrist mount, its legs, waist and free arm on NVIDIA's SONIC whole-body policy (tracking our en garde, step and lunge motions), its sword arm on the point skill; a lunge from guard covers about 0.25 m in 0.4 s, so the phrases are fenced from 1.95 m, where a lunge reaches the chest; you command it by intentions, not by motions+- Deviation D9 (rulebook t.124): unwillingness to fight as the FIE applies it to direct-elimination bouts (t.124.1): one minute of fencing time without a hit -> 'Halt!'; the first time a P-red card to both fencers, a penalty hit each; the second time the P-black card to the fencer with the lower score, who loses the bout, at equal scores to the fencer who loses a seeded lot (t.124.1.b.i: lots for fencers not in the FIE ranking); no P-card at 14-14 (t.124.3.a): the minute restarts; the minute restarts after each hit, double, annulled double and penalty hit (t.124.3.d), not after a phrase without a touch; t.124 does not apply in the extra minute (t.124.3.f)+- Deviation D11 (rulebook -): the two ends of the piste are not exactly alike in the simulation (the same phrase fenced from the other end ends differently in 205 of the 1431 pairs of mirrored phrases, about one in seven), so each phrase draws the end each fencer fences from, with probability 1/2 each: both fencers meet the same chances++## Geometry and physics+Everything you need is in `game spec`: the world frame, the release point, the cameras (pose, field of view, size,+`focal_px`, `principal_point_px`; pinhole: u = cx + f * x_right / depth, v = cy - f * y_up / depth) and the+execution scatter. The physics engine is the phrases: MuJoCo 3.3.7 (1 ms physics steps, 10 ms control steps), two Unitree G1 of the robot library (bodies/unitree_g1, 29 DOF; Unitree's motor torque-speed curves through the library's output stage) with epees, robot x robot, blade x body and blade x blade contacts (bodies/contacts.py), NVIDIA SONIC (GR00T-WholeBodyControl b042411) on the legs, waist and free arm, the point skill on the sword arm, fencing-6's apparatus and phrase referee; each of the 2916 phrases measured once in that world (it is deterministic: 2799 earlier measurements of 1953 of the phrases all ended as in that run, with the same result at the same step) and replayed from sports/fencing/phrases/table.json.++## External material+You may install packages you need (pip, apt), and you may read anything installed in your container, the simulator's and this benchmark's own source code included. Please solve the task yourself: do not search the web for, or download, a ready-made solution to it, such as published or reference solutions, recorded demonstrations, or policies trained for it. This is an honour rule; trials are reviewed. The network reaches your model's API and the package registries (PyPI, Debian / Ubuntu archives) only.++## Resource limits+Limits for your agent environment, your own container only (the simulator in the `sim` service is the benchmark's and does not count): at most **4 GiB of memory**, **512 processes** and **20 GiB** of new files under `/app`, `/tmp` and `/root`; your container has no GPU. These limits may be enforced (from protocol v1.2 on): when enforcement is on, exceeding one for 60 s within any 2 minutes, or a process killed for lack of memory, ends the trial as a failure (reward 0), whatever the deliverable. A monitor outside your container measures every few seconds; the current values are in `/run/rcb-limits/usage.json`. CPU is capped at 2 cores for your container; the cap only slows you down.++## Time limit+You have 7200 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task.++This is wall-clock time from the start of your session; the time you wait for the simulator service counts. When it is up you are stopped without warning and graded on what stands at that moment, as the sections above say. The service does not count this limit for you: the clocks it reports are the game's own. Your session started when you received this task. `/run/rcb-limits/usage.json`, rewritten every few seconds, gives the time left on this limit (`time_left_s`) and its end (`deadline_utc`), counted from a little before your session started, so it never gives you more time than you have: read it (or run `date`) before you decide that time is short, never guess. Waiting counts too: a tool call that sends input to a process that keeps running (an interactive interpreter, a simulator loop, a server) can wait for the whole wait or yield time you give it (for example Codex's `yield_time_ms`) even when the answer is printed at once, so give such calls a short wait and poll again if the output is not complete, or run one-shot scripts that exit when they are done. Installing packages is not cheating (`## External material` above).diff --git a/tasks/roboolympics-fencing-bout-i01-standard/solution/builtin_players.py b/tasks/roboolympics-fencing-bout-i01-standard/solution/builtin_players.pynew file mode 100644index 0000000000..9b95f8886e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/solution/builtin_players.py@@ -0,0 +1,245 @@+"""fencing's built-in players (fencing-7, the phrase-level sport; the same action interface as a model's program:+core/client.py plays them over HTTP).++ Reference a reader of the opponent (since 2026-10-14; screening report, section 6 "fencing-7"): ten hypotheses+ about the opponent's next intention, each scored by how well it predicted the opponent's past choices+ (decayed log-score); the best one is answered with the logit answer (20 per net touch) by the phrase+ table of `game spec`, and in 10 % of the phrases a draw from the table's equilibrium mix. Five are the+ pattern reader of step 4 (2026-10-13): the opponent's mix; after its last intention; after its last two;+ after my last one; after the last pair (tables of decayed counts). Five model how the opponent reads me:+ it predicts MY next intention from my mix, after my last one, after my last two, after its last one or+ after the last pair, and answers that prediction (logit 40, 5 % spread). The pattern reader alone is+ the weak form of the capability-sensitivity check, the equilibrium mix the strong form. It reads only+ `game spec` and the state (the phrases so far), and draws from its own stream (the seed).+ Rival the reference drawing from a stream of the seed and its seat (the fairness policy: two references with+ the same seed would draw alike).+ Random a uniform intention every phrase (generic tests).+No simulator import: this file runs in the player's container as the task's oracle (numpy only)."""+from __future__ import annotations++import math++import numpy as np++PRIOR = 1.0+RESULT = {"you": 1, "opponent": -1, "double": 2, "double, not counted at 14-14": 2, "none": 0}+++def solve_zero_sum(M, max_iter=10000):+ """(value, x, y) of the zero-sum game where the row player maximises x' M y (simplex, Bland's rule)"""+ M = np.asarray(M, float)+ m, n = M.shape+ c = 1.0 - M.min()+ T = np.zeros((m + 1, n + m + 1))+ T[:m, :n] = M + c+ T[:m, n:n + m] = np.eye(m)+ T[:m, -1] = 1.0+ T[m, :n] = -1.0+ basis = list(range(n, n + m))+ for _ in range(max_iter):+ neg = np.flatnonzero(T[m, :-1] < -1e-12)+ if len(neg) == 0:+ break+ col = int(neg[0])+ colv = T[:m, col]+ pos = colv > 1e-12+ ratios = np.full(m, np.inf)+ ratios[pos] = T[:m, -1][pos] / colv[pos]+ ties = np.flatnonzero(ratios <= ratios.min() + 1e-12)+ r = int(min(ties, key=lambda k: basis[k]))+ T[r] /= T[r, col]+ for k in range(m + 1):+ if k != r and T[k, col] != 0.0:+ T[k] -= T[k, col] * T[r]+ basis[r] = col+ else:+ raise RuntimeError("simplex did not converge")+ z = T[m, -1]+ yp = np.zeros(n)+ for r, b in enumerate(basis):+ if b < n:+ yp[b] = T[r, -1]+ xp = np.clip(T[m, n:n + m], 0.0, None)+ return float(1.0 / z - c), xp / xp.sum(), yp / yp.sum()+++def table_from_spec(spec):+ """(intention names, my expected net touches per phrase T[mine, theirs], the equilibrium mix) from `game spec`"""+ names = list(spec["intentions"])+ pt = spec["phrase_table"]+ C = np.array([[pt["counts"][f"{a}|{b}"] for b in names] for a in names], float)+ P = (C + PRIOR) / (C.sum(-1, keepdims=True) + 4 * PRIOR)+ T = P[..., 0] - P[..., 1]+ _, x, _ = solve_zero_sum(T)+ return names, T, x+++class Reader:+ """the pattern reader (screening: game.py Context, beta 20, eps_eq 0.1)"""+ CONTEXTS = ("m", "o1", "o2", "me1", "pair")++ def __init__(self, T, eq, rng, beta=20.0, eps_eq=0.1, decay=0.9, prior=0.3, score_decay=0.8):+ self.P, self.eq, self.rng, self.n = T, eq, rng, len(eq)+ self.beta, self.eps_eq, self.decay, self.prior, self.score_decay = beta, eps_eq, decay, prior, score_decay+ self.hist = []+ self.tabs = {c: {} for c in self.CONTEXTS}+ self.score = {c: 0.0 for c in self.CONTEXTS}+ self._keys, self._preds = {}, {}+ self.used = "m"++ def _key(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "o1":+ return h[-1][1]+ if c == "o2":+ return (h[-2][1], h[-1][1]) if len(h) >= 2 else None+ if c == "me1":+ return h[-1][0]+ return (h[-1][1], h[-1][0])++ def _pred(self, c, key):+ t = self.tabs[c].get(key) if key is not None else None+ if t is None:+ return None+ p = t + self.prior+ return p / p.sum()++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ best, bs = "m", self.score["m"]+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ if p is not None and self.score[c] > bs + 1e-12:+ best, bs = c, self.score[c]+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def choose(self):+ p = self.dist()+ return int(min(np.searchsorted(np.cumsum(p), self.rng.random(), side="right"), len(p) - 1))++ def observe(self, mine, other, res):+ for c, p in self._preds.items():+ self.score[c] = self.score_decay * self.score[c] + math.log(p[other])+ self.hist.append((mine, other, res))+ for c, key in self._keys.items():+ if key is None:+ continue+ t = self.tabs[c].get(key)+ if t is None:+ t = self.tabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[other] += 1.0+++class MindReader(Reader):+ """the pattern reader plus five hypotheses that the opponent predicts my next intention (from the contexts MINE of+ my own play) and answers it"""+ MINE = ("m", "me1", "me2", "o1", "pair")++ def __init__(self, *a, beta_o=40.0, eps_o=0.05, **k):+ super().__init__(*a, **k)+ self.beta_o, self.eps_o = beta_o, eps_o+ self.mtabs = {c: {} for c in self.MINE}+ for c in self.MINE:+ self.score["tom_" + c] = 0.0+ self._mkeys = {}++ def _mkey(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "me1":+ return h[-1][0]+ if c == "me2":+ return (h[-2][0], h[-1][0]) if len(h) >= 2 else None+ if c == "o1":+ return h[-1][1]+ return (h[-1][0], h[-1][1])++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ self._mkeys = {c: self._mkey(c) for c in self.MINE}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ mmarg = self.mtabs["m"].get(0)+ for c in self.MINE:+ t = self.mtabs[c].get(self._mkeys[c]) if self._mkeys[c] is not None else None+ if t is None:+ t = mmarg+ q = np.full(self.n, 1.0 / self.n) if t is None else (t + self.prior) / (t + self.prior).sum()+ v = -self.P.T @ q # the opponent's net per intention against my predicted mix+ a = np.exp(self.beta_o * (v - v.max()))+ a /= a.sum()+ self._preds["tom_" + c] = self.eps_o / self.n + (1 - self.eps_o) * a+ best = max(self._preds, key=lambda c: (self.score[c], c == "m"))+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def observe(self, mine, other, res):+ for c, key in self._mkeys.items():+ if key is None:+ continue+ t = self.mtabs[c].get(key)+ if t is None:+ t = self.mtabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[mine] += 1.0+ super().observe(mine, other, res)+++class Reference:+ def __init__(self, spec, seat, seed=0):+ self.names, T, eq = table_from_spec(spec)+ self.idx = {s: i for i, s in enumerate(self.names)}+ self.r = MindReader(T, eq, self._rng(seed, seat))+ self.seen = 0++ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12]) # by seed, not by seat: mirror runs match++ def act(self, view):+ ph = view["state"].get("phrases") or []+ for p in ph[self.seen:]:+ self.r.observe(self.idx[p["you"]], self.idx[p["opponent"]], RESULT[p["result"]])+ self.seen = len(ph)+ return {"type": "phrase", "intention": self.names[self.r.choose()]}++ def review(self, reply):+ return ("read the phrase's result", f"answer the opponent's next intention as predicted by '{self.r.used}'")+++class Rival(Reference):+ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12, sum(map(ord, str(seat)))])+++class Random:+ def __init__(self, spec, seat, seed=0):+ self.names = list(spec["intentions"])+ self.g = np.random.default_rng(int(seed) * 7919 + 17) # by seed, not by seat: mirror runs match++ def act(self, view):+ return {"type": "phrase", "intention": self.names[int(self.g.integers(len(self.names)))]}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/solution/oracle_play.py b/tasks/roboolympics-fencing-bout-i01-standard/solution/oracle_play.pynew file mode 100644index 0000000000..cc345a9a2b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/solution/oracle_play.py@@ -0,0 +1,5 @@+"""Harbor oracle on any seat: the sport's reference player (builtin_players:Reference, camera images and /spec only) over+HTTP through the core's client loop (ro_client.py = core/client.py)."""+import ro_client++ro_client.main(["builtin_players:Reference"])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/solution/ro_client.py b/tasks/roboolympics-fencing-bout-i01-standard/solution/ro_client.pynew file mode 100644index 0000000000..84258d872b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/solution/ro_client.py@@ -0,0 +1,147 @@+"""Contract ①, the player's side: a stdlib client of the match service and the loop that lets a built-in player (the+sport's reference player, scripted opponents, check policies) play over HTTP exactly as a model's program would.++A built-in player is an object made by factory(spec, seat, seed) with+ act(view) -> body | None view = {"state": <the seat's state>, "observation": <the /observe observation>}+ (body = the /act request; None = nothing now, realtime only)+ review(reply) -> (why, plan) optional; called after each own action (turn) or at each review (realtime)+ message(view) -> text | None optional (realtime, core 0.2.21): a team-channel message to the seat's teammates+ (POST /say; refused messages, e.g. faster than the channel allows, are dropped)++ python3 -m core.client MODULE:FACTORY (SIM_URL, SEAT; e.g. the task's solution/oracle_play.py)+"""+from __future__ import annotations++import importlib+import json+import os+import sys+import time+import urllib.error+import urllib.request+++class Seat:+ """One seat's calls. The service allows 20 requests per second and 4 open requests per seat: the client keeps+ under that (MIN_GAP_S between calls) and retries a request the HTTP layer refused before reading it (a bare 429+ or a reset connection), which never reached the match."""+ MIN_GAP_S = 0.06++ def __init__(self, base: str, seat: str, timeout: float = 600):+ self.base, self.seat, self.timeout, self.last = base.rstrip("/"), seat, timeout, 0.0++ def call(self, ep: str, body: dict | None = None, tries: int = 20) -> dict:+ for i in range(tries):+ time.sleep(max(0.0, self.last + self.MIN_GAP_S - time.monotonic()))+ self.last = time.monotonic()+ req = urllib.request.Request(f"{self.base}/{self.seat}/{ep}",+ data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=self.timeout) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ raw = e.read()+ if e.code == 429 and not raw and i + 1 < tries: # the HTTP layer's limit, not the match's+ time.sleep(0.25 * (i + 1))+ continue+ try:+ out = json.loads(raw)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+ except urllib.error.URLError as e:+ if isinstance(e.reason, (BrokenPipeError, ConnectionResetError, ConnectionRefusedError)) and \+ i + 1 < tries:+ time.sleep(0.25 * (i + 1))+ continue+ raise+ raise RuntimeError("the match service kept refusing")+++def wait_for(base: str, seat: str, deadline_s: float = 300) -> dict:+ t = time.time()+ while time.time() - t < deadline_s:+ try:+ out = Seat(base, seat, 10).call("spec")+ if "error" not in out:+ return out+ except OSError:+ pass+ time.sleep(1)+ raise RuntimeError("the match service did not answer")+++def review_of(player, reply) -> tuple[str, str]:+ f = getattr(player, "review", None)+ return f(reply) if f else ("played as planned", "go on with the same plan")+++REPLY_IMAGES = [0] # acts whose reply carried images of their result (core 0.2.8)+++def play_turn(c: Seat, player) -> dict:+ c.call("start", {})+ while True:+ st = c.call("wait", {"timeout_s": 60}).get("state") or {}+ if st.get("done"):+ return st+ if not st.get("your_turn"):+ continue+ if st.get("awaiting_review"):+ why, plan = review_of(player, st)+ c.call("ready", {"why": why, "plan": plan})+ continue+ view = c.call("observe", {})+ body = player.act({"state": view.get("state") or {}, "observation": view.get("observation") or {}})+ reply = c.call("act", body)+ REPLY_IMAGES[0] += bool((reply.get("observation") or {}).get("image_png_b64"))+ if (reply.get("state") or {}).get("done"):+ return reply["state"]+ if reply.get("http_status"):+ print("refused:", json.dumps(reply)[:300], file=sys.stderr)+ continue+ why, plan = review_of(player, reply)+ c.call("ready", {"why": why, "plan": plan})+++def play_realtime(c: Seat, player, every_s: float = 0.05) -> dict:+ c.call("start", {})+ while True:+ view = c.call("observe", {})+ now = view.get("now") or {}+ if now.get("done"):+ return now+ if now.get("world") == "frozen" and now.get("phase") == "review" and not now.get("ready", {}).get(c.seat):+ why, plan = review_of(player, now)+ c.call("ready", {"why": why, "plan": plan})+ continue+ if now.get("world") == "running":+ v = {"state": now, "observation": view.get("observation") or {}}+ body = player.act(v)+ if body is not None:+ c.call("act", body)+ say = getattr(player, "message", None)+ text = say(v) if say is not None else None+ if text:+ c.call("say", {"text": text})+ c.call("wait", {"dt": every_s})+++def main(argv):+ mod, _, name = argv[0].partition(":")+ sys.path.insert(0, os.getcwd())+ factory = getattr(importlib.import_module(mod), name or "Reference")+ base, seat = os.environ.get("SIM_URL", "http://sim:8000"), os.environ.get("SEAT", "A")+ spec = wait_for(base, seat)+ player = factory(spec, seat, int(os.environ.get("RO_PLAYER_SEED", "0")))+ c = Seat(base, seat)+ proto = spec.get("protocol", "")+ end = play_turn(c, player) if proto.startswith("eai-standard-turn") else play_realtime(c, player)+ print(json.dumps({"final_state": {k: end.get(k) for k in ("reason", "won", "winner", "scores") if k in end},+ "replies_with_images": REPLY_IMAGES[0]}))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i01-standard/solution/solve.sh b/tasks/roboolympics-fencing-bout-i01-standard/solution/solve.shnew file mode 100755index 0000000000..91b1b08047--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/solution/solve.sh@@ -0,0 +1,6 @@+#!/bin/bash+# Oracle on any seat: the sport's reference player.+set -e+mkdir -p /app/output+python3 -c "import numpy, PIL" 2>/dev/null || pip install -q --no-cache-dir -r /opt/client-requirements.txt+cd /solution && python3 oracle_play.pydiff --git a/tasks/roboolympics-fencing-bout-i01-standard/task.toml b/tasks/roboolympics-fencing-bout-i01-standard/task.tomlnew file mode 100644index 0000000000..b94e5fab2e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/task.toml@@ -0,0 +1,122 @@+# Exported by RoboOlympics tools/export_fexam.py from fencing-bout-wallclock-program-standard (sports/fencing/sport.toml): do not edit.+schema_version = "1.3"+artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },+ "/app/output/",+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/replay_check.json", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/video.json", service = "sim" },+ { source = "/data/broadcast.jsonl", service = "sim" },+]++[task]+name = "robot-coding-bench/roboolympics-fencing-bout-i01-standard"+description = "STANDARD (RoboOlympics / Embodied Agent Olympics, our own service): robot epee fencing, one bout against the scripted opponent at level 1, program play (eai-standard-turn/1.0: the world waits for the player whose turn it is; the player's chess clock of 60 minutes of real time runs on its own turns, reviews included, and a player whose clock runs out loses). Camera images and the player's own state only. Frozen development instance (seed and level fixed, not an official seed). two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time. Exported from RoboOlympics task fencing-bout-wallclock-program-standard by tools/export_fexam.py."+authors = [{ name = "RoboOlympics (CHIGUI0)" }]+keywords = ["robotics", "roboolympics", "sports", "fencing", "mujoco", "standard-mode", "vision", "turn-based"]++[metadata]+author_name = "RoboOlympics"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-g1"+family = "fencing_bout"+mode = "standard"+dynamics = "dynamic" # scene dynamics (docs/PROTOCOL.md §2.14): scripts/task_dynamics.toml+protocol = "eai-standard-turn/1.0"+instance_seed = 39+opponent_level = 1+chess_clock_s = 3600+revision = "fencing-7+core-0.2"+play = "program"+action_level = "low"+source_task = "roboolympics/fencing-bout-wallclock-program-standard"+source_commits = ["a6712a675343"]+exporter = "roboolympics tools/export_fexam.py"+player_mode = "unmetered"+official = false+expert_time_estimate_hours = 0.5+oracle = "full"+oracle_evidence = "in process (fencing-7): the oracle beats level 1 on this seed 15:11; over 40 player seeds the reference wins this instance 62.5 %, the equilibrium mix 47.5 % (fresh-seed means 61.5 %, 53.5 %); none of the nine constant intentions nor a random player wins it; live on vanilla Harbor 0.23.0 (2026-10-15, the exported task) the oracle won 15:11 in 25 phrases, replay identical (the world is deterministic)"++[metadata.resources]+# minimum compute to run this task (docs/PROTOCOL.md §2.9)+min_cpus = 3.0+min_memory_gb = 5.0+min_gpu_memory_gb = 0.0+gpu_required = false+gpu_class = "none"+verifier_min_cpus = 2.0+verifier_min_memory_gb = 3.0+verifier_min_gpu_memory_gb = 0.0+measured = "vanilla Harbor 0.23.0 on ws-3 (32 cores), 2026-10-15, oracle and nop of both tasks, docker stats every 5 s: the sim peaks at 4.0 CPUs (its cap) and 0.71 GiB (the replay in a fresh process and the video after the bout; a bout is about 20 s of service time), the oracle's container under 0.1 GiB (a model's harness needs more: RoboOlympics' agent default); turn-based, so fewer CPUs only slow it down; CPU only"++[metadata.resources.limits]+# agent-phase limits in GiB (docs/PROTOCOL.md §2.10); scope: trial = every container, agent = the agent's container;+# enforced from protocol v1.2 when RCB_LIMITS_ENFORCE=1 (a violation fails the trial), otherwise recorded only+scope = "agent"+max_gpu_memory_gb = 0.0+max_memory_gb = 4.0+max_processes = 512+max_disk_gb = 20.0+disk_paths = ["/app", "/tmp", "/root"]+disk_exclude = []+sustain_sec = 60.0+window_sec = 120.0+trial_max_gpu_memory_gb = 0.0+trial_max_memory_gb = 12.0+measured = "design defaults of RoboOlympics' exported matches (the agent 4 GiB under its 6 GiB cap; whole trial: + the sim's 8 GiB cap); measured peaks 2026-10-15: sim 0.71 GiB, oracle container under 0.1 GiB"++[metadata.resources.caps]+# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)+main = { cpus = 2.0, memory_gb = 6.0, pids = 8192 }+sim = { cpus = 4.0, memory_gb = 8.0, pids = 256 }++[metadata.seeds]+# the instances this task may run from (docs/PROTOCOL.md §2.13): the default, the ones a runner may draw+# from (a list, { from = A, to = B } or "any"), and the ones the reference solution under solution/ is for+default = 39+allowed = [39]+oracle = [39]++[verifier]+timeout_sec = 2040.0+environment_mode = "separate"+network_mode = "no-network"++# Resource limits (docs/PROTOCOL.md §2.10): seal the monitor's record first, before any other sidecar ends the episode.+[[verifier.collect]]+service = "rcb_monitor"+command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90"+timeout_sec = 120++# The agent's time is up: stop whatever it left running (a program would keep playing; the match is graded as it stands).+[[verifier.collect]]+service = "main"+command = "kill -9 -1 2>/dev/null; exit 0"+timeout_sec = 30++# Then SIGUSR1 ends the match: the service replays it in a fresh process, checks the replay and writes the verdict+# ("graded_ready"), then the spectator video.+[[verifier.collect]]+service = "sim"+command = "for i in $(seq 1 90); do [ -f /data/server.pid ] && break; sleep 2; done; kill -USR1 $(cat /data/server.pid); for i in $(seq 1 600); do grep -q '\"graded_ready\": true' /data/final.json 2>/dev/null && break; sleep 1; done; [ x$RCB_RENDER_VIDEO = x1 ] && for i in $(seq 1 960); do [ -f /data/video.json ] && break; sleep 1; done; cat /data/final.json | head -c 2000"+timeout_sec = 1860++[agent]+timeout_sec = 7200+# The agent reaches the model APIs, the package registries and the sim (localhost:8000, Harbor's egress control).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com", "pypi.org", "files.pythonhosted.org", "deb.debian.org", "security.debian.org", "archive.ubuntu.com", "security.ubuntu.com", "snapshot.ubuntu.com"]++[environment]+build_timeout_sec = 1200.0+cpus = 2+memory_mb = 6144++[verifier.environment]+build_timeout_sec = 600.0++[verifier.env]+RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/Dockerfile b/tasks/roboolympics-fencing-bout-i01-standard/tests/Dockerfilenew file mode 100644index 0000000000..cba0eb5085--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/Dockerfile@@ -0,0 +1,12 @@+# Separate verifier sandbox: grades the sim service's artifacts; needs nothing but Python.+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+COPY sport_grade.py /tests/sport_grade.py+COPY contract.json /tests/contract.json+COPY nocode_audit.py /tests/nocode_audit.py+COPY seeds.py /tests/seeds.py+COPY fexam_reward.py /tests/fexam_reward.py+RUN chmod +x /tests/test.sh+# resource limits: the verifier step and its copy of the limits (docs/PROTOCOL.md §2.10) # rcb-monitor+COPY rcb_limits.py rcb_limits.json /tests/diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/contract.json b/tasks/roboolympics-fencing-bout-i01-standard/tests/contract.jsonnew file mode 100644index 0000000000..bbf32b910c--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/contract.json@@ -0,0 +1,58 @@+{+ "format": "bout",+ "formats": {+ "bout": {+ "levels": [+ 1,+ 2+ ],+ "opponent": true,+ "preview": true,+ "seats": [+ "A"+ ]+ },+ "duel": {+ "first": [+ "A",+ "B"+ ],+ "preview": true,+ "seats": [+ "A",+ "B"+ ]+ }+ },+ "official": {+ "first_any": true,+ "levels": [+ 1,+ 2+ ],+ "seeds": [+ 1,+ 2,+ 3,+ 101,+ 111,+ 121,+ 202,+ 212,+ 222+ ]+ },+ "protocol": "turn",+ "score": {+ "forfeit": 0.0,+ "from": "share",+ "name": "touch_share",+ "range": [+ 0,+ 1+ ],+ "text": "touches scored / touches scored by both fencers (a double counts for both; 0.5 if neither scored)"+ },+ "sport": "fencing",+ "task": "fencing-bout-wallclock-program-standard"+}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/fexam_reward.py b/tasks/roboolympics-fencing-bout-i01-standard/tests/fexam_reward.pynew file mode 100644index 0000000000..527e256880--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/fexam_reward.py@@ -0,0 +1,19 @@+#!/usr/bin/env python3+"""The hub's reward fields on top of our grader's reward.json (tools/export_fexam.py): infra_error = the trial is not+a valid result (our technical_failure); realtime, slowdown, opponent_level from the sim's final.json. Numbers only."""+import json+from pathlib import Path++LOG, DATA = Path("/logs/verifier"), Path("/data")+r = json.loads((LOG / "reward.json").read_text()) if (LOG / "reward.json").exists() else {"success": 0, "grader_error": 1}+try:+ f = json.loads((DATA / "final.json").read_text())+except (OSError, ValueError):+ f = {}+r["infra_error"] = int(bool(r.get("technical_failure", 1)) or bool(r.get("grader_error")))+r["realtime"] = int(bool(f.get("slowdown"))) # a turn-based match has no slowdown+r["slowdown"] = float(f.get("slowdown") or 0)+r["opponent_level"] = int((f.get("cfg") or {}).get("level") or 0)+r["steps"] = int(f.get("steps") or 0)+(LOG / "reward.json").write_text(json.dumps({k: v for k, v in r.items() if isinstance(v, (int, float))}))+(LOG / "reward.txt").write_text(str(int(r.get("success", 0))) + "\n")diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/grade.py b/tasks/roboolympics-fencing-bout-i01-standard/tests/grade.pynew file mode 100644index 0000000000..f63442d2ca--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/grade.py@@ -0,0 +1,198 @@+"""The verifier (separate sandbox, no network, no simulator): reads what the sim wrote (/data/final.json,+/data/replay_check.json), checks the fresh-process replay agrees with the live match, applies the one validity rule+(technical failures void the trial; a player's own problems are a valid loss, among them a side that never started+in its start window or before the player sessions ended: reason no_show, no_show = 1, <seat>_no_show = 1, core 0.2.7;+and a single side whose session ended after the start and before the end of the match: reason abandoned, abandoned =+1; core 0.2.6) and the no-code audit of+direct play,+and writes reward.json = common fields + the sport's own fields (tests/sport_grade.py: evaluate(final) -> numbers).+The task's formats and official configurations come from tests/contract.json (generated from sport.toml).++Hidden official seeds (core 0.2.14, core/seeds.py): once the sport registers a hidden seed set (contract official+hidden_seeds: sha256, counts and commitments per cell = format x level), official_config needs the match seed to be+one of its cell: the commitment the sim recorded (final.json seed_proof; the replay must give the same one) must be in+the registered cell (hidden_seed = 1, hidden_seed_index = its position; else 0 and -1). A hidden seed is never written:+seed = -1 here and in every record. The public [official] seeds then no longer count as official.+Core 0.2.19: this holds over the sport's own official_config too (tests/sport_grade.py may replace the core's value+with a legacy per-format rule): with a registered set, official_config = 1 needs hidden_seed = 1 and the sport's+value 1, so the sport's rule can only lower it and a public-seed match is never official.+Continuous score (core 0.2.14, core/score.py): final.json continuous.by_side (the replay must agree) becomes+<seat>_continuous_score per seat and, for a single-side format, continuous_score; larger is better.++success: duel / team / multi -> the trial is valid (who won is in <seat>_won / <seat>_place);+ single against a scripted opponent -> valid and the seat's side won;+ single without an opponent (solo) -> valid, complete and the score reaches the success line."""+from __future__ import annotations++import importlib.util+import json+import os+import shutil+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+DATA = Path(os.environ.get("RCB_DATA", "/data"))+LOG = Path(os.environ.get("RCB_LOG", "/logs/verifier"))+COMPLETE = ("match_over", "ready_timeout", "clock", "abandoned", "no_show")+++def _load(name):+ p = HERE / f"{name}.py"+ if not p.exists():+ return None+ spec = importlib.util.spec_from_file_location(name, p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++try: # core/seeds.py; in a task, its copy next to this file (tests/seeds.py)+ from . import seeds as seedset+except ImportError:+ seedset = _load("seeds")+++def hidden_index(d, contract) -> int | None:+ """The match seed's position in its cell (format x level) of the sport's registered hidden official seed set+ (core 0.2.14, core/seeds.py): the commitment the sim recorded (final.json seed_proof; the seed and its salt are+ never written) must be in that cell's registered commitments. None if it is not one."""+ reg = (contract.get("official") or {}).get("hidden_seeds")+ proof = d.get("seed_proof") or {}+ if not reg or seedset is None:+ return None+ return seedset.index(contract.get("sport", ""), d.get("format") or "", (d.get("cfg") or {}).get("level"),+ proof.get("commitment"), reg)+++def official(d, contract) -> bool:+ """An official configuration: the seed (a registered hidden seed once the sport has a hidden set, else one of the+ public [official] seeds), the slowdown, the first player and the level."""+ off = contract.get("official", {})+ if ((contract.get("formats") or {}).get(d.get("format") or "") or {}).get("preview"):+ return False # a preview format ([formats.<f>] preview = true; core 0.2.21) is never official+ ok = True+ if off.get("hidden_seeds"):+ ok &= hidden_index(d, contract) is not None+ elif "seeds" in off:+ ok &= int(d.get("seed") or 0) in off["seeds"]+ if "slowdowns" in off:+ ok &= float(d.get("slowdown") or 0) in off["slowdowns"].get(d.get("play", "program"), [])+ if off.get("first_any"):+ ok &= d.get("first") in d["cfg"]["seats"] or d.get("first") in (d.get("sides") or {}).values()+ if "levels" in off and d["cfg"].get("level") is not None:+ ok &= int(d["cfg"]["level"]) in off["levels"]+ return bool(ok)+++def line_ok(score, line: dict) -> bool:+ if "score_at_least" in line:+ return score >= line["score_at_least"]+ if "score_at_most" in line:+ return score <= line["score_at_most"]+ return False+++def grade(d, r, contract, evaluate, audits=None):+ seats = d["cfg"]["seats"]+ side = d.get("sides") or {s: s for s in seats}+ cont = (d.get("continuous") or {}).get("by_side")+ replay = bool(d.get("deterministic") and r.get("state_sha") == d["state_sha"] and r.get("scores") == d["scores"]+ and r.get("winner") == d["match_winner"] and r.get("commands_sha") == d["commands_sha"]+ and r.get("source_sha") == d["source_sha"] and r.get("k") == d["steps"]+ and (cont is None or r.get("continuous") == cont)+ and (not d.get("seed_proof") or r.get("seed_commitment") == d["seed_proof"].get("commitment")))+ solo = bool(d.get("solo"))+ single = len(set(side.values())) == 1+ complete = d.get("reason") in COMPLETE and (single or d.get("match_winner") in side.values())+ errors = bool(d.get("errors") or any(d["meter_error"].values()) or any(d["proxy_error"].values()))+ valid = bool(d.get("valid_trial") and d.get("finalized") and replay and complete and not errors)+ direct = d.get("play") == "direct"+ audits = audits or {}+ bad = {s: bool(direct and d["player_modes"].get(s) == "model" and audits.get(s, (0, []))[1]) for s in seats}+ winner = d["match_winner"]+ if any(bad.values()): # a no-code violation loses the match (all of them: nobody wins)+ rest = sorted({side[s] for s in seats if not bad[s]})+ winner = rest[0] if len(rest) == 1 and not single else None+ fmt = (contract.get("formats") or {}).get(d.get("format") or "", {})+ if solo:+ score = d["scores"].get(side[seats[0]], 0)+ success = valid and d.get("reason") == "match_over" and not any(bad.values()) and \+ line_ok(score, fmt.get("success", {}))+ elif single:+ success = valid and winner == side[seats[0]]+ else:+ success = valid+ out = dict(success=int(success), valid_trial=int(valid), technical_failure=int(not valid), grader_error=0,+ missing_log=0, deterministic=int(replay), match_over=int(d.get("reason") == "match_over"),+ seed=int(d.get("seed") or 0), official_config=int(official(d, contract)),+ video_rendered=int(bool(d.get("video")) or (DATA / "replay.mp4").exists()), direct_play=int(direct),+ lowlevel_actions=int(d.get("action_level") == "low"), solo=int(solo),+ no_show=int(d.get("reason") == "no_show"), abandoned=int(d.get("reason") == "abandoned"))+ hidx = hidden_index(d, contract)+ out.update(hidden_seed=int(hidx is not None), hidden_seed_index=hidx if hidx is not None else -1)+ if cont is not None: # the continuous score (core 0.2.14): larger is better+ worst = float((contract.get("score") or {}).get("forfeit", 0.0))+ for s in seats:+ out[s + "_continuous_score"] = worst if bad[s] else float(cont.get(side[s], worst))+ if single:+ out["continuous_score"] = out[seats[0] + "_continuous_score"]+ ranking = d.get("ranking") or []+ for s in seats:+ out[s + "_won"] = int(valid and winner == side[s] and not bad[s])+ out[s + "_no_show"] = int(d.get("reason") == "no_show" and not (d.get("joined") or {}).get(s, True))+ if len(set(side.values())) > 2:+ out[s + "_place"] = ranking.index(side[s]) + 1 if valid and side[s] in ranking else 0+ out[s + "_transient_api_errors"] = int(d["transient_api_errors"].get(s, 0))+ out[s + "_unrecovered_api_errors"] = int(d["unrecovered_api_errors"].get(s, 0))+ if direct:+ out[s + "_nocode_tool_calls"] = int(audits.get(s, (0, []))[0])+ out[s + "_nocode_violations"] = len(audits.get(s, (0, []))[1])+ out[s + "_nocode_forfeit"] = int(bad[s])+ out.update(evaluate(d))+ if (contract.get("official") or {}).get("hidden_seeds"):+ # core 0.2.19: once the sport registered a hidden seed set (frozen), only a match on a registered hidden seed of+ # its cell is official, whatever the sport's own official_config says (its legacy public-seed rule); the+ # sport's rule (e.g. its slowdowns) can only lower the value+ out["official_config"] = int(out.get("official_config") == 1 and hidx is not None)+ return out+++def main():+ LOG.mkdir(parents=True, exist_ok=True)+ try:+ contract = json.loads((HERE / "contract.json").read_text())+ evaluate = _load("sport_grade").evaluate+ d, r = (json.loads((DATA / f).read_text()) for f in ("final.json", "replay_check.json"))+ audits = None+ if d.get("play") == "direct":+ nmod = _load("nocode_audit") # the players' no-code audit (players/nocode/)+ # calls the gateway blocked never reached the agent, so they are not judged (direct-native/1.1 rule)+ audits = {s: nmod.nocode_audit(DATA / f"think_calls_{s}.jsonl",+ skip_ids=nmod.gate_blocked_ids(DATA / f"direct_gate_{s}.jsonl"))+ for s in d["cfg"]["seats"]}+ (LOG / "nocode_audit.json").write_text(json.dumps({s: dict(tool_calls=a[0], violations=a[1][:50])+ for s, a in audits.items()}, indent=1))+ out = grade(d, r, contract, evaluate, audits)+ hs = (contract.get("official") or {}).get("hidden_seeds") or {}+ (LOG / "versions.json").write_text(json.dumps({+ "versions": d.get("versions"), "renderer": d.get("renderer"),+ "seed_set": {"sha256": hs.get("sha256"), "counts": hs.get("counts"), "index": hidden_index(d, contract)}+ if hs else None,+ "continuous_score": {k: (d.get("continuous") or {}).get(k) for k in ("name", "from", "higher_is_better")}+ if d.get("continuous") else None}))+ for f in ("final.json", "replay_check.json", "episode.jsonl", "replay.mp4"):+ if (DATA / f).exists():+ shutil.copy(DATA / f, LOG / f)+ except Exception as e: # noqa: BLE001+ print(type(e).__name__, str(e))+ out = dict(success=0, valid_trial=0, technical_failure=1, grader_error=1,+ missing_log=int(not (DATA / "final.json").exists()))+ assert all(isinstance(v, (int, float)) for v in out.values())+ (LOG / "reward.json").write_text(json.dumps(out))+ (LOG / "reward.txt").write_text(str(out["success"]) + "\n")+ print(out)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/nocode_audit.py b/tasks/roboolympics-fencing-bout-i01-standard/tests/nocode_audit.pynew file mode 100644index 0000000000..213aa5d559--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/nocode_audit.py@@ -0,0 +1,321 @@+"""The no-code audit of direct play (docs/benchmarks/roboolympics-modes.md, play switch `direct`), shared by every+sport: the generator copies it into tests/ of every task with declared switches; a grader applies it when final.json+says `play` = "direct".++Every tool call of every model response of the session (think_calls.jsonl, recorded by the metering proxy) must be a+literal `game` command or the opening of a saved camera image (or a planning note); anything else - a program, a+script, another shell command, a pipe, a redirection, command substitution, a file edit - forfeits the contest: a+valid trial that is lost (decided 2026-10-06), reported as `nocode_violations` with the calls in nocode_audit.json.++The audit window starts at the player's first `game start` (decided 2026-10-06): before it, self-inspection is also+allowed - listing the harness's tools, reading the instruction, the spec or other files (read-only commands and file+viewers, a code cell that calls no tool). Starting a program, writing a file or any other side effect is a violation+before `game start` too (a program started then would run during play).+"""+import json+import re+from pathlib import Path++VIEWS = re.compile(r"^/app/output/views/[A-Za-z0-9_.-]+\.png$")+WORD = re.compile(r"^[A-Za-z0-9_.+\-:/=,%]+$")+PLAN_TOOLS = {"TodoWrite", "update_plan"}+++READONLY = {"cat", "ls", "head", "tail", "wc", "pwd", "which", "file", "stat", "echo", "less", "more", "tree"}+INSPECT_TOOLS = {"Read", "Glob", "Grep", "LS", "TodoWrite", "update_plan", "view_image"}+++def literal_words(cmd: str):+ """The words of a command with literal arguments only, or None (see literal_game)."""+ return _words(cmd)+++def literal_game(cmd: str) -> bool:+ """`game WORD ...` with literal arguments only: quoted texts may hold anything but an unescaped $ or ` inside double+ quotes (a backslash there only makes the next character literal); outside quotes only plain words (no ; | & < > $+ ` ( ) { } newline ...)."""+ return _game_ok(_words(cmd))+++def _words(cmd: str):+ words, cur, quote, quoted, esc = [], "", None, False, False+ for ch in cmd.strip():+ if quote:+ if esc:+ cur += ch; esc = False+ elif quote == '"' and ch == "\\":+ esc = True+ elif ch == quote:+ quote = None+ elif quote == '"' and ch in '$`':+ return None+ else:+ cur += ch+ continue+ if ch in "\"'":+ quote, quoted = ch, True+ elif ch in " \t":+ if cur or quoted:+ words.append(cur)+ cur, quoted = "", False+ elif WORD.match(ch):+ cur += ch+ else:+ return None+ if quote:+ return None+ if cur or quoted:+ words.append(cur)+ return words+++def _game_ok(words) -> bool:+ return bool(words) and len(words) >= 2 and words[0] == "game"+++def _args(tool):+ a = tool.get("input") or tool.get("arguments") or tool.get("action") or (tool.get("function") or {}).get("arguments")+ if isinstance(a, str):+ try:+ a = json.loads(a)+ except ValueError:+ return {"_raw": a}+ return a if isinstance(a, dict) else {"_raw": a}+++def _shell(cmd):+ """The command a shell tool runs: codex wraps it as [bash, -lc, CMD]."""+ if isinstance(cmd, list):+ if len(cmd) == 3 and cmd[0] in ("bash", "sh", "/bin/bash", "/bin/sh") and cmd[1] in ("-lc", "-c"):+ return cmd[2]+ return None+ return cmd if isinstance(cmd, str) else None+++# Codex 0.158 with GPT-6 has no direct shell tool: every tool use is an `exec` cell of JavaScript that calls tools+# (tools.exec_command, tools.view_image). JavaScript is code, so only the two one-call cells below are allowed (a+# literal `game` command, or opening a saved camera image, and printing its result); anything else in a cell (loops,+# several calls, computation, other tools) is a violation.+_JS_LIT = r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|-?\d+(?:\.\d+)?'+_JS_CALL = re.compile(r'^\s*const\s+(\w+)\s*=\s*await\s+tools\.(\w+)\(\{(.*)\}\)\s*;?\s*$', re.S)+_JS_PAIR = re.compile(r'\s*(\w+)\s*:\s*(' + _JS_LIT + r')\s*(?:,|$)', re.S)+# the parameters each allowed tool may take (all literal), and what it must be called with+_JS_TOOLS = {"mcp__game__game": {"command"}, # direct-native: the `game` MCP tool (game_mcp.py)+ "exec_command": {"cmd", "workdir", "max_output_tokens", "yield_time_ms"},+ "view_image": {"path", "detail"},+ "write_stdin": {"session_id", "chars", "yield_time_ms", "max_output_tokens"}}+++def _js_value(lit):+ if lit[0] in "\"'":+ body = lit[1:-1]+ if lit[0] == "'":+ body = body.replace("\\'", "'").replace('"', '\\"')+ try:+ return json.loads('"' + body + '"')+ except ValueError:+ return None+ return float(lit)+++def _js_print_ok(stmt, var):+ """Printing the call's result, nothing else: text(r.output), text(JSON.stringify(r)), text("..." + JSON.stringify(r)),+ image(r.image_url[, "detail"])."""+ v = re.escape(var)+ lit = r'(?:"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')'+ pats = (rf'text\(\s*{v}\.output\s*\)', rf'text\(\s*JSON\.stringify\(\s*{v}\s*\)\s*\)',+ rf'text\(\s*{lit}\s*\+\s*JSON\.stringify\(\s*{v}\s*\)\s*\)', rf'image\(\s*{v}\.image_url\s*(?:,\s*{lit}\s*)?\)')+ return any(re.fullmatch(p + r'\s*;?\s*', stmt) for p in pats)+++_JS_FORBIDDEN = re.compile(r"tools\.|ALL_TOOLS|\bawait\b|\bwhile\b|\bdo\b|\bfunction\b|\beval\b|Function\(|\bimport\b|"+ r"\brequire\b|\batob\b|\bbtoa\b|Buffer|Uint8Array|ArrayBuffer|DataView|charCodeAt|"+ r"fromCharCode|codePointAt|setTimeout|setInterval|\bMath\.|\bnew\b|\bclass\b|\byield\b")+++def _js_light_display_ok(rest, var) -> bool:+ """Formatting the result for display without computing on it (direct-native, Codex): no further tool call, no loop+ other than over the result's content items, no arithmetic library, no access to the image bytes except passing+ them to image(); at most 800 characters."""+ body = re.sub(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|`(?:[^`\\]|\\.)*`', '""', rest)+ if len(rest) > 800 or _JS_FORBIDDEN.search(body):+ return False+ for m in re.finditer(r"\bfor\s*\(", body):+ if not re.match(rf"for\s*\(\s*(?:const|let|var)\s+\w+\s+of\s+\(?\s*{re.escape(var)}\s*\??\.\s*content", body[m.start():]):+ return False+ for m in re.finditer(r"\.data\b", body):+ if not re.search(r"image\(\s*[\w.]*$", body[:m.start()]):+ return False+ return True+++def _js_display_ok(rest, var) -> bool:+ """The statements after the call only display its result: text(r), text(r.output), text(JSON.stringify(r)),+ text("..." + JSON.stringify(r)), image(r.image_url[, "..."]), or the loop that shows an MCP result's content+ (`for (const c of (r.content || [])) { if (c.type === "image") image(c); else if (c.type === "text") text(c.text); }`)."""+ compact = re.sub(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'', "L", rest)+ compact = re.sub(r"\s+", "", compact)+ v = re.escape(var)+ c = r"(?P<c>\w+)"+ simple = (rf"text\({v}\);?", rf"text\({v}\.output\);?", rf"text\(JSON\.stringify\({v}\)\);?",+ rf"text\(L\+JSON\.stringify\({v}\)\);?", rf"image\({v}\.image_url(,L)?\);?")+ show = r"(?:image\((?P=c)(?:\.data)?\)|text\((?P=c)(?:\.text)?\))"+ loop = (rf"for\((?:const|let|var){c}of\(?{v}\.content(?:\|\|\[\])?\)?\)\{{"+ rf"(?:(?:else)?if\((?P=c)\.type===?L\){show};?)+(?:else{show};?)?\}};?")+ while compact:+ for pat in simple + (loop,):+ m = re.match(pat, compact)+ if m:+ compact = compact[m.end():]+ break+ else:+ return False+ return True+++def codex_exec_ok(src, cmd_ok=literal_game) -> bool:+ """One literal tool call (a `game` command, opening a camera image, or polling that command's output) and printing+ its result; no other code."""+ if not isinstance(src, str):+ return False+ lines = [x for x in src.strip().split("\n") if x.strip()]+ if not lines:+ return False+ m = _JS_CALL.match(lines[0])+ if not m or m.group(2) not in _JS_TOOLS:+ return False+ var, tool, body = m.group(1), m.group(2), m.group(3)+ args, pos = {}, 0+ while pos < len(body.strip()):+ pm = _JS_PAIR.match(body, pos)+ if not pm:+ return False+ args[pm.group(1)] = _js_value(pm.group(2)); pos = pm.end()+ if not set(args) <= _JS_TOOLS[tool] or any(v is None for v in args.values()):+ return False+ rest = "\n".join(lines[1:])+ if tool == "mcp__game__game": # direct-native: canonical display or light formatting of the result+ return (_js_display_ok(rest, var) or _js_light_display_ok(rest, var)) and _player_command(args.get("command"))+ if not _js_display_ok(rest, var):+ return False+ if tool == "exec_command":+ return isinstance(args.get("cmd"), str) and cmd_ok(args["cmd"])+ if tool == "view_image":+ return isinstance(args.get("path"), str) and bool(VIEWS.match(args["path"]))+ return args.get("chars", "") == "" # write_stdin: only polling a running command, never input+++def _player_command(cmd) -> bool:+ import shlex+ if not isinstance(cmd, str) or "\n" in cmd.strip():+ return False+ try:+ w = shlex.split(cmd)+ except ValueError:+ return False+ return len(w) >= 2 and w[0] == "game"+++def _readonly(cmd) -> bool:+ w = _words(cmd)+ return bool(w) and (w[0] in READONLY or _game_ok(w))+++def tool_name(tool):+ return tool.get("name") or (tool.get("function") or {}).get("name") or tool.get("type")+++def is_game_start(tool) -> bool:+ """A literal `game start` (shell call or Codex cell)."""+ name, a = tool_name(tool), _args(tool)+ cmd = None+ if name == "exec" and tool.get("type") == "custom_tool_call":+ m = _JS_CALL.match((tool.get("input") or "").strip().split("\n")[0]) if isinstance(tool.get("input"), str) else None+ if m and m.group(2) == "exec_command":+ pm = re.search(r'cmd\s*:\s*(' + _JS_LIT + ')', m.group(3))+ cmd = _js_value(pm.group(1)) if pm else None+ elif name in SHELL_TOOLS or name in ("game", "mcp__game__game", "game__game"):+ cmd = _shell(a.get("command", a.get("cmd")))+ w = _words(cmd) if isinstance(cmd, str) else None+ return bool(w) and w[:2] == ["game", "start"]+++def inspection_ok(tool) -> bool:+ """Before `game start`: read-only self-inspection (file viewers, read-only commands, a code cell calling no tool)."""+ if allowed(tool):+ return True+ name, a = tool_name(tool), _args(tool)+ if name in INSPECT_TOOLS:+ return True+ if name == "exec" and tool.get("type") == "custom_tool_call":+ src = tool.get("input")+ code = re.sub(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|`(?:[^`\\]|\\.)*`', '""', src) if isinstance(src, str) else ""+ if isinstance(src, str) and "tools." not in code and "await" not in code and "import" not in code:+ return True # pure JavaScript in the harness's sandbox: no tool, no side effect+ return codex_exec_ok(src, _readonly)+ if name in SHELL_TOOLS:+ cmd = _shell(a.get("command", a.get("cmd")))+ return isinstance(cmd, str) and _readonly(cmd)+ return False+++SHELL_TOOLS = ("Bash", "shell", "exec_command", "local_shell_call", "container.exec", "shell_command")+++def allowed(tool) -> bool:+ name = tool.get("name") or (tool.get("function") or {}).get("name") or tool.get("type")+ a = _args(tool)+ if name in PLAN_TOOLS:+ return True+ if name == "wait" and set(a) <= {"cell_id", "yield_time_ms", "max_tokens"}: # Codex: wait for a running cell+ return True+ if name in ("game", "mcp__game__game", "game__game"): # direct-player (harbor_agents/direct_loop.py): its only tool; no shell+ return _player_command(a.get("command")) # runs it, the line is data for the harness's parser+ if name == "exec" and tool.get("type") == "custom_tool_call": # Codex code mode (see above)+ return codex_exec_ok(tool.get("input"))+ if name in ("Read", "view_image"):+ return isinstance(a.get("file_path", a.get("path")), str) and bool(VIEWS.match(a.get("file_path", a.get("path"))))+ if name in ("Bash", "shell", "exec_command", "local_shell_call", "container.exec", "shell_command"):+ cmd = _shell(a.get("command", a.get("cmd")))+ return isinstance(cmd, str) and literal_game(cmd)+ return False+++def gate_blocked_ids(path):+ """Item ids the gateway (direct_gate.py) blocked, from its log; empty if there is none."""+ ids = set()+ try:+ for line in Path(path).read_text().splitlines():+ e = json.loads(line)+ if e.get("ev") == "blocked" and e.get("item_id"):+ ids.add(e["item_id"])+ except (OSError, ValueError):+ pass+ return ids+++def nocode_audit(path, skip_ids=()):+ """(tool calls, violations [(seq, tool name, arguments excerpt)]) of the session's model responses. skip_ids: the+ item ids the gateway blocked (they never reached the agent, so they are not judged)."""++ n, bad = 0, []+ try:+ lines = Path(path).read_text().splitlines()+ except OSError:+ return 0, []+ started = False # the window opens at the first `game start`+ for line in lines:+ try:+ rec = json.loads(line)+ except ValueError:+ continue+ for tool in rec.get("tool_calls") or []:+ if tool.get("id") in skip_ids: # blocked by the gateway (direct-native/1.1): it never ran+ continue+ n += 1+ ok = allowed(tool) if started else inspection_ok(tool)+ started = started or is_game_start(tool)+ if not ok:+ bad.append({"seq": rec.get("seq"), "tool": tool.get("name") or (tool.get("function") or {}).get("name")+ or tool.get("type"), "args": json.dumps(_args(tool))[:300]})+ return n, baddiff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/rcb_limits.json b/tasks/roboolympics-fencing-bout-i01-standard/tests/rcb_limits.jsonnew file mode 100644index 0000000000..8bc7217428--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/rcb_limits.json@@ -0,0 +1,39 @@+{+ "agent_timeout_sec": 7200,+ "caps": {+ "main": {+ "cpus": 2.0,+ "memory_gb": 6.0,+ "pids": 8192+ },+ "sim": {+ "cpus": 4.0,+ "memory_gb": 8.0,+ "pids": 256+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": false,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 0.0,+ "max_memory_gb": 4.0,+ "max_processes": 512,+ "mode": "standard",+ "scope": "agent",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "roboolympics-fencing-bout-i01-standard",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 0.0,+ "trial_max_memory_gb": 12.0,+ "window_sec": 120.0+}diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/rcb_limits.py b/tasks/roboolympics-fencing-bout-i01-standard/tests/rcb_limits.pynew file mode 100644index 0000000000..3c996ca1f2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/rcb_limits.py@@ -0,0 +1,536 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The session log (robot_coding_bench #233): sanitize() also compares the agent's /app/output/rcb_session_log.jsonl with+the monitor's append-only copy of it (session_log/ in the record) and, when the agent's file is missing or is not what+was written (removed, truncated, rewritten), gives the grader the copy instead (session_log_source()); verify() adds+session_log_tampered (0/1) and session_log_from_monitor (0/1) to reward.json. Only the graders' cost fields read the log.++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ sl = read_json(os.path.join(log, SESSION_LOG_STATUS)) # sanitize()'s session-log comparison (#233)+ if isinstance(sl, dict):+ add["session_log_tampered"] = int(bool(sl.get("tampered")))+ add["session_log_from_monitor"] = int(bool(sl.get("from_monitor")))+ detail["session_log"] = sl+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ try:+ msg = session_log_source(log, max_log)+ if msg:+ done.append(msg)+ except Exception as e: # never keep the grader from running+ done.append(f"session log: not compared with the monitor's copy ({type(e).__name__}: {e})")+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++SESSION_LOG_STATUS = "session_log.json" # in /logs/verifier: what session_log_source() did, read back by verify()+++def session_log_source(log, max_log=MAX_SESSION_LOG, record=None):+ """The session log the grader reads (#233). The monitor copies what the agent's tooling appends to it, append-only,+ into its record (session_log/<segment>.jsonl; a new segment each time the file was truncated, replaced or+ rewritten). The agent's file stays when it is the copy plus at most what was appended after the last tick; else+ (removed, truncated, rewritten, or the copy has segments) the grader gets the copy: the segments' lines in order,+ in a later segment a line an earlier one already gave left out (a rewrite copies the file again). No copy (no monitor on the runner, or no log+ written): nothing changes, nothing is written. Else writes /logs/verifier/session_log.json; returns a line for the+ log, or None."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ d = os.path.join(record, "session_log")+ segs = sorted((int(n.split(".")[0]) for n in (os.listdir(d) if os.path.isdir(d) else ())+ if n.endswith(".jsonl") and n.split(".")[0].isdigit()))+ events = [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)]+ tamper = [e for e in events if e.get("event") in ("session_log_rewritten", "session_log_removed")]+ status = {"from_monitor": 0, "tampered": int(bool(tamper)), "monitor_copy": bool(segs), "events": tamper[:20]}+ msg = None+ if segs:+ copies = []+ for n in segs:+ with open(os.path.join(d, "%d.jsonl" % n), "rb") as f:+ copies.append(f.read(max_log))+ agent = None+ if os.path.isfile(log) and not os.path.islink(log):+ with open(log, "rb") as f:+ agent = f.read(max_log)+ if len(segs) == 1 and not tamper and agent is not None and agent.startswith(copies[0]):+ pass # the agent's file is what was written (and maybe a last tick more)+ else:+ given, out = {}, [] # line -> most times one earlier segment had it+ for c in copies:+ again, lines, here = dict(given), c.splitlines(True), {}+ for line in lines:+ here[line] = here.get(line, 0) + 1+ if again.get(line):+ again[line] -= 1 # the rewrite's copy of a line given before+ continue+ out.append(line)+ for line, k in here.items():+ given[line] = max(given.get(line, 0), k)+ data = b"".join(out)[:max_log]+ if os.path.lexists(log):+ os.unlink(log)+ with open(log, "wb") as f:+ f.write(data)+ status.update(from_monitor=1, tampered=1, agent_bytes=None if agent is None else len(agent),+ copy_bytes=len(data))+ msg = (f"replaced {log} with the monitor's copy ({len(data)} bytes; the agent's file was "+ + ("missing" if agent is None else f"{len(agent)} bytes, not what was written") + ")")+ if not segs and not tamper:+ return None # no copy (no monitor, or no log written): nothing to say+ logs = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ try:+ os.makedirs(logs, exist_ok=True)+ with open(os.path.join(logs, SESSION_LOG_STATUS), "w") as f:+ json.dump(status, f, indent=1)+ except OSError:+ pass+ return msg+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/seeds.py b/tasks/roboolympics-fencing-bout-i01-standard/tests/seeds.pynew file mode 100644index 0000000000..c6a2ae4c83--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/seeds.py@@ -0,0 +1,178 @@+"""Hidden official seeds (core 0.2.14, docs/framework_zh.md §6.4): a sport frozen for a season plays its official+matches on a seed set that only the organisers hold. The repository has its commitments, never the seeds.++ cells the set is partitioned by format x level: one cell per format ("duel") or per format and level of a+ format with levels ("match/L1", "match/L2", ...; cell_of); every cell has its own seeds, none shared+ private set {"schema": PRIVATE, "sport", "created", "cells": {cell: [{"seed": int, "salt": 32 hex}, ...]}}: outside+ git, on the official run host only (tools/seeds.py: $RO_SEEDS_DIR/<sport>.hidden_seeds.json, 0600)+ commitments one per seed, in cell order: sha256("ro-hidden-seeds/1|<sport>|<seed>|<salt>"); the salt (128 random+ bits) makes a commitment say nothing about its seed+ registration set_sha256 (the sport and every cell's commitments) and the count per cell: sport.toml+ [official.hidden_seeds] sha256, counts; the commitments are public (sports/<sport>/seed_commitments.json)++At run time the runner hands one seed, its salt and its index to the sim service only (RO_SEED, RO_SEED_SALT,+RO_SEED_INDEX); the players' containers never see them. In such a match the core writes the seed nowhere: the+episode header, final.json, replay_check.json and the broadcast log carry seed -1 and the commitment only+(final.json seed_proof), the sport's own fields and the players' observations and /spec are scrubbed (scrub()), and+the fresh-process replay takes the seed from the same environment and checks it against the commitment. The salt is+never written either (with it, a six-digit seed would follow from its commitment by brute force). The verifier finds+the commitment in the cell of the match's format and level (index()): hidden_seed, hidden_seed_index. The private set+plus the index is the only record of the seed; after the season the set may be published and anyone can recompute+set_sha256 from it.++Standard library only: the generator copies this file next to the verifier (tests/seeds.py)."""+from __future__ import annotations++import hashlib+import re+import secrets++SCHEMA = "ro-hidden-seeds/1" # the commitment of one seed+SET_SCHEMA = "ro-hidden-seeds/2" # the registered digest of a partitioned set+PRIVATE = "ro-hidden-seeds-private/2"+PUBLIC = "ro-hidden-seeds-public/2"+SEED_RANGE = (100000, 999999) # six digits: an int32 for any simulator+HIDDEN = -1 # the seed as written in the records of a hidden-seed match+HEX = re.compile(r"^[0-9a-f]{64}$")+CELL = re.compile(r"^[a-z0-9][a-z0-9_-]*(/L\d+)?$") # a format name of sport.toml, "/L<level>"+KEEP = {"step", "k", "steps", "t_sim"}+COMMITMENTS = "seed_commitments.json" # sports/<sport>/<this>: the public part (public())+++def commitment(sport: str, seed: int, salt: str) -> str:+ return hashlib.sha256(f"{SCHEMA}|{sport}|{int(seed)}|{salt}".encode()).hexdigest()+++def set_sha256(sport: str, cells: dict) -> str:+ """The registered digest of a seed set: its sport and every cell's commitments, cells in sorted order."""+ text = SET_SCHEMA + "\n" + sport + "\n"+ for c in sorted(cells):+ text += f"[{c}]\n" + "".join(x + "\n" for x in cells[c])+ return hashlib.sha256(text.encode()).hexdigest()+++def cell_of(fmt: str, level, cells) -> str | None:+ """The cell of a match: "<format>/L<level>" when the set has it, else "<format>" when it has that, else None."""+ if level is not None and f"{fmt}/L{int(level)}" in cells:+ return f"{fmt}/L{int(level)}"+ return fmt if fmt in cells else None+++def new(sport: str, counts: dict, avoid=(), created: str = "") -> dict:+ """A fresh private set: counts = {cell: n}; every seed distinct across cells and none of `avoid`."""+ if not counts or any(int(n) < 1 or not CELL.match(c) for c, n in counts.items()):+ raise ValueError("cells: {\"<format>\" or \"<format>/L<level>\": count >= 1}")+ lo, hi = SEED_RANGE+ used, cells = {int(x) for x in avoid}, {}+ for c in sorted(counts):+ cells[c] = []+ while len(cells[c]) < int(counts[c]):+ s = lo + secrets.randbelow(hi - lo + 1)+ if s not in used:+ used.add(s)+ cells[c].append({"seed": s, "salt": secrets.token_hex(16)})+ return {"schema": PRIVATE, "sport": sport, "created": created, "cells": cells}+++def from_seeds(sport: str, cells: dict, created: str = "") -> dict:+ """A private set of given seeds ({cell: [int, ...]}) with fresh salts."""+ out = {c: [{"seed": int(s), "salt": secrets.token_hex(16)} for s in v] for c, v in cells.items()}+ p = {"schema": PRIVATE, "sport": sport, "created": created, "cells": out}+ check_private(p)+ return p+++def check_private(p: dict) -> None:+ if p.get("schema") != PRIVATE or not p.get("sport") or not p.get("cells"):+ raise ValueError(f"not a private seed set (schema {PRIVATE}, sport, cells)")+ seen = set()+ for c, entries in p["cells"].items():+ if not CELL.match(c) or not entries:+ raise ValueError(f"bad cell {c!r}")+ for e in entries:+ if not isinstance(e.get("seed"), int) or not re.fullmatch(r"[0-9a-f]{32}", str(e.get("salt", ""))):+ raise ValueError(f"bad entry in {c}: seed int, salt 32 hex")+ if e["seed"] in seen:+ raise ValueError(f"seed {e['seed']} twice (cells never share a seed)")+ seen.add(e["seed"])+++def public(p: dict) -> dict:+ """The public part of a private set: what goes into the repository."""+ check_private(p)+ cells = {c: [commitment(p["sport"], e["seed"], e["salt"]) for e in v] for c, v in sorted(p["cells"].items())}+ return {"schema": PUBLIC, "sport": p["sport"], "counts": {c: len(v) for c, v in cells.items()},+ "sha256": set_sha256(p["sport"], cells), "cells": cells}+++def registered(sport: str, reg: dict) -> dict:+ """The cells of a registration {sha256, counts, cells}, after checking that they are the registered ones (their+ digest and counts); ValueError otherwise."""+ cells = reg.get("cells") or {}+ counts = reg.get("counts") or {}+ if set(cells) != set(counts) or not cells:+ raise ValueError("hidden seeds: the cells of the commitments and of the counts differ")+ flat = [x for v in cells.values() for x in v]+ if not all(isinstance(x, str) and HEX.match(x) for x in flat) or len(set(flat)) != len(flat):+ raise ValueError("hidden seeds: commitments must be distinct sha256 hex digests")+ for c, v in cells.items():+ if len(v) != int(counts[c]):+ raise ValueError(f"hidden seeds: cell {c} has {len(v)} commitments, count {counts[c]}")+ if set_sha256(sport, cells) != reg.get("sha256"):+ raise ValueError("hidden seeds: the commitments do not hash to the registered sha256")+ return cells+++def index(sport: str, fmt: str, level, commit: str | None, reg: dict) -> int | None:+ """The position of a match's commitment in the cell of its format and level, None if it is not there (or the+ registration is inconsistent: then nothing is a member)."""+ if not commit:+ return None+ try:+ cells = registered(sport, reg)+ except (ValueError, TypeError):+ return None+ cell = cell_of(fmt, level, cells)+ if cell is None or commit not in cells[cell]:+ return None+ return cells[cell].index(commit)+++def resolve(p: dict, cell: str, i: int, reg: dict | None = None) -> tuple[int, str]:+ """(seed, salt) of entry i of a cell of a private set; with a registration, also checks that the set is the+ registered one."""+ check_private(p)+ if cell not in p["cells"]:+ raise KeyError(f"no cell {cell!r} (cells: {', '.join(sorted(p['cells']))})")+ if not 0 <= i < len(p["cells"][cell]):+ raise IndexError(f"cell {cell} has {len(p['cells'][cell])} seeds (0..{len(p['cells'][cell]) - 1}); asked {i}")+ if reg is not None and public(p)["sha256"] != reg.get("sha256"):+ raise ValueError("this private seed set is not the registered one (sha256 differs)")+ e = p["cells"][cell][i]+ return int(e["seed"]), str(e["salt"])+++def scrub(obj, seed: int, salt: str = ""):+ """A copy of obj (JSON-like) without the seed: values under a key named "seed" or "*_seed" become HIDDEN, and so+ does any integer equal to the seed or any string equal to it or to the salt. For a hidden-seed match."""+ seed = int(seed)++ def go(x, key=""):+ if (key == "seed" or key.endswith("_seed")) and not isinstance(x, (dict, list, tuple)):+ return HIDDEN+ if key in KEEP: # the core's step counters: never the seed, may reach six digits+ return x+ if isinstance(x, dict):+ return {k: go(v, str(k)) for k, v in x.items()}+ if isinstance(x, (list, tuple)):+ return [go(v) for v in x]+ if isinstance(x, bool):+ return x+ if isinstance(x, int) and x == seed:+ return HIDDEN+ if isinstance(x, float) and x == seed:+ return float(HIDDEN)+ if isinstance(x, str) and (x == str(seed) or (salt and x == salt)):+ return str(HIDDEN)+ return x+ return go(obj)diff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/sport_grade.py b/tasks/roboolympics-fencing-bout-i01-standard/tests/sport_grade.pynew file mode 100644index 0000000000..a6c7b75098--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/sport_grade.py@@ -0,0 +1,77 @@+"""fencing's part of reward.json (the common part is core/grading.py: success, valid_trial, technical_failure,+deterministic, seed, official_config, video_rendered, <seat>_won, <seat>_transient/unrecovered_api_errors, ...):+numbers only, from final.json (and the seat's metering summary think_usage_<seat>.json, a declared artifact of the+sim). fencing-7 (the phrase-level sport): the bout's phrases instead of fencing-6's halts; the legacy reward names+of both tasks are kept where they still mean something (README.md)."""+import json+import os+from collections import Counter+from pathlib import Path++DATA = Path(os.environ.get("RCB_DATA", "/data"))+COUNTS = ("n_act", "n_observe", "n_reviews", "refused_busy", "refused_turn", "refused_not_model")+++def _usage(seat):+ try:+ return json.loads((DATA / f"think_usage_{seat}.json").read_text())+ except (OSError, ValueError):+ return {}+++def _bout(f):+ ph = f.get("phrases") or []+ return {"bout_over": int(f.get("how") in ("touches", "passivity", "time", "deciding_touch", "priority")),+ "extra_minute": int(bool(f.get("extra_minute"))), "phrases": len(ph),+ "doubles": sum(1 for r in ph if r.get("res") == "double"),+ "doubles_not_counted": sum(1 for r in ph if r.get("annulled")),+ "no_touch_phrases": sum(1 for r in ph if r.get("res") == "none"),+ "p_cards": int(f.get("p_cards") or 0), "fencing_time_s": float(f.get("fencing_time_s") or 0.0)}+++def _intentions(f, side, prefix):+ c = Counter((r.get("intentions") or {}).get(side) for r in f.get("phrases") or [])+ names = ("lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw")+ return {f"{prefix}intention_{n}": int(c.get(n, 0)) for n in names}+++def evaluate(d):+ f = d.get("sport_fields") or {}+ seats = d["cfg"]["seats"]+ scores = d.get("scores") or {}+ stats = d.get("seats") or {}+ out = _bout(f)+ if len(seats) == 1: # the bout against the scripted fencer (side B)+ s = seats[0]+ st, u = stats.get(s, {}), _usage(s)+ errs = d.get("errors") or []+ won = d.get("match_winner") == s and out["bout_over"] == 1+ rp = d.get("replay_scores") or {}+ pf, pa = int(scores.get(s, 0)), int(scores.get("B", 0))+ out.update(+ won=int(won), level=int(f.get("level") or 0), won_on_priority=int(won and f.get("how") == "priority"),+ sim_error=int(d.get("reason") == "technical_error" or any(e.get("where") != "replay" for e in errs)),+ replay_error=int(not d.get("deterministic") or any(e.get("where") == "replay" for e in errs)),+ meter_error=int(bool((d.get("meter_error") or {}).get(s))),+ proxy_error=int(bool((d.get("proxy_error") or {}).get(s))), finalized=int(bool(d.get("finalized"))),+ touches_for=pf, touches_against=pa, points_for=pf, points_against=pa,+ replay_touches_for=int(rp.get(s, -1)), replay_touches_against=int(rp.get("B", -1)),+ clock_forfeit=int(f.get("how") == "clock"), clock_used_s=float((d.get("clock_used_s") or {}).get(s, 0.0)),+ elapsed_s=float(d.get("elapsed_s") or 0.0), metered_requests=int(u.get("requests", 0)),+ metered_output_tokens=int(u.get("output_tokens", 0)), metered_input_tokens=int(u.get("input_tokens", 0)),+ rate_limit_retries=int(u.get("rate_limit_retries", 0)),+ transient_api_errors=int((d.get("transient_api_errors") or {}).get(s, 0)),+ unrecovered_api_errors=int((d.get("unrecovered_api_errors") or {}).get(s, 0)),+ **{k: int(st.get(k, 0)) for k in COUNTS}, **_intentions(f, s, ""), **_intentions(f, "B", "opponent_"))+ return out+ out.update(won_on_priority=int(bool(d.get("valid_trial")) and f.get("how") == "priority"),+ clock_forfeit=int(f.get("how") == "clock"), abandoned=int(f.get("how") == "abandoned"),+ first_player_A=int(f.get("first_player") == "A"), elapsed_s=float(d.get("elapsed_s") or 0.0))+ for s in seats:+ st = stats.get(s, {})+ out[s + "_points"] = int(scores.get(s, 0))+ out[s + "_clock_used_s"] = float((d.get("clock_used_s") or {}).get(s, 0.0))+ for k in COUNTS:+ out[s + "_" + k] = int(st.get(k, 0))+ out.update(_intentions(f, s, s + "_"))+ return outdiff --git a/tasks/roboolympics-fencing-bout-i01-standard/tests/test.sh b/tasks/roboolympics-fencing-bout-i01-standard/tests/test.shnew file mode 100755index 0000000000..7b1faa5b84--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i01-standard/tests/test.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+mkdir -p /logs/verifier+rm -rf /logs/verifier/*+trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resource limits, after the grader (docs/PROTOCOL.md §2.10)+p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # the agent's files are untrusted input: no link out of /app/output, no FIFO or device (docs/PROTOCOL.md §2.6)+python /tests/grade.py 2> /logs/verifier/grade.log+python /tests/fexam_reward.py 2>> /logs/verifier/grade.logdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/DIGEST b/tasks/roboolympics-fencing-bout-i02-standard/DIGESTnew file mode 100644index 0000000000..f5442995ce--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/DIGEST@@ -0,0 +1 @@+sha256:518b1ca6d609a1c7fe5488d3a27b2602f5f78e22f2ffef516bd5cf4400880ae5diff --git a/tasks/roboolympics-fencing-bout-i02-standard/README.md b/tasks/roboolympics-fencing-bout-i02-standard/README.mdnew file mode 100644index 0000000000..582e55f241--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/README.md@@ -0,0 +1,49 @@+# roboolympics-fencing-bout-i02-standard++| | |+|---|---|+| Benchmark | RoboOlympics |+| Mode | standard (`eai-standard-turn/1.0`) |+| Twin | — (none: a task RoboOlympics exports with its own service, PROTOCOL §4c; a turn-based match has no trajectory deliverable) |+| Simulator / robot | `mujoco` / `unitree-g1` |+| Family / instance | `fencing_bout` / seed 35 |+| Oracle | `full` — in process (fencing-7): the oracle beats level 2 on this seed 15:13; over 40 player seeds the reference wins this instance 42.5 %, the equilibrium mix 50 % (fresh-seed means 48.0 %, 53.9 %); none of the nine constant intentions nor a random player wins it; live on vanilla Harbor 0.23.0 (2026-10-15, the exported task) the oracle won 15:13 in 32 phrases, replay identical (the world is deterministic) |+| Agent time budget | 7200 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-olympiad:0.1.0` |++## Task+Robot epee fencing against the scripted opponent (level 2), program play: two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time.++## Difficulty+Frozen development instance: seed 35, level 2, chess clock 3600 s per player. Not one of+the sport's official (hidden) seeds, so results here are previews, not official RoboOlympics results.++## Reference solution+`solution/`: our camera-only reference player through the same HTTP interface. in process (fencing-7): the oracle beats level 2 on this seed 15:13; over 40 player seeds the reference wins this instance 42.5 %, the equilibrium mix 50 % (fresh-seed means 48.0 %, 53.9 %); none of the nine constant intentions nor a random player wins it; live on vanilla Harbor 0.23.0 (2026-10-15, the exported task) the oracle won 15:13 in 32 phrases, replay identical (the world is deterministic).++## Verification+Separate sandbox, no network. The sim service replays the recorded match in a fresh process; the verifier+(`tests/grade.py`, our core's grader) checks that the replay agrees with the live match, applies the validity rule+(technical failures void the trial, a player's own problems are a valid loss), and writes reward.json; success = a+valid, finished match that the agent won. `tests/fexam_reward.py` adds the hub's fields (`infra_error`, `realtime`,+`slowdown`, `opponent_level`; `realtime` = 0 for a turn-based match).++## Compute resources+Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]` in `task.toml`). The agent phase counts every container of the trial at once (the agent's, and in standard modes the simulator sidecar); the verifier phase runs after it.++| | Agent phase | Verifier |+|---|---|---|+| CPU cores | 3 | 2 |+| Memory | 5 GB | 3 GB |+| GPU memory | 0 GB | 0 GB |++- GPU: not needed.+- Measured: vanilla Harbor 0.23.0 on ws-3 (32 cores), 2026-10-15, oracle and nop of both tasks, docker stats every 5 s: the sim peaks at 4.0 CPUs (its cap) and 0.71 GiB (the replay in a fresh process and the video after the bout; a bout is about 20 s of service time), the oracle's container under 0.1 GiB (a model's harness needs more: RoboOlympics' agent default); turn-based, so fewer CPUs only slow it down; CPU only+- Limits in the agent phase (docs/PROTOCOL.md §2.10; `[metadata.resources.limits]`, shown to the agent in `instruction.md`; always measured and reported, and exceeding one fails the trial only when the run sets `RCB_LIMITS_ENFORCE=1`), the agent's container: no GPU, 4 GiB memory, 512 processes, 20 GiB of new files under `/app`, `/tmp`, `/root`; 60 s within 120 s. Expected peak of the whole trial: 0 GiB GPU memory, 12 GiB memory. Limits measured: design defaults of RoboOlympics' exported matches (the agent 4 GiB under its 6 GiB cap; whole trial: + the sim's 8 GiB cap); measured peaks 2026-10-15: sim 0.71 GiB, oracle container under 0.1 GiB.++## Details++### Notes+Source: RoboOlympics task `fencing-bout-wallclock-program-standard`, revision `fencing-7+core-0.2`. The rules, the referee, the scripted+opponent, the observation, the review between points and the grader are ours, unchanged; only the seat is+unmetered (Harbor records the model's usage) and the instance is frozen.diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/Dockerfile b/tasks/roboolympics-fencing-bout-i02-standard/environment/Dockerfilenew file mode 100644index 0000000000..4d1e89d49b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/Dockerfile@@ -0,0 +1,10 @@+# The player's container: no simulator, only Python with the standard client pins and the generic `game`+# command of the core (core/game.py, the sport's shortcuts filled in by tools/generate.py).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /opt/client-requirements.txt+RUN pip install --no-cache-dir -r /opt/client-requirements.txt+COPY game /usr/local/bin/game+RUN chmod +x /usr/local/bin/game && mkdir -p /app/output+ENV SEAT=A+ENV SIM_URL=http://localhost:8000+WORKDIR /appdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/client-requirements.txt b/tasks/roboolympics-fencing-bout-i02-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/docker-compose.yaml b/tasks/roboolympics-fencing-bout-i02-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..ed9e1bbd99--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/docker-compose.yaml@@ -0,0 +1,77 @@+# Exported by RoboOlympics tools/export_fexam.py (do not edit). The `sim` sidecar runs our simulator service+# unchanged (core/launch.py: the match service, eai-standard-turn/1.0); the agent's container (main)+# reaches it at localhost:8000: under Harbor's egress control both share the egress sidecar's network+# namespace (keep [agent] network_mode = "allowlist"). The seat is unmetered: no metering proxy and no+# credential here (Harbor records the model's usage). CPU only (MuJoCo, OSMesa). cap_drop NET_RAW: no raw+# sockets and no SO_MARK, which could bypass the egress proxy's mark.+services:+ main:+ pids_limit: 8192 # rcb-monitor+ volumes: # rcb-monitor+ - rcb_limits:/run/rcb-limits:ro # rcb-monitor+ depends_on: [sim]+ cap_drop: [NET_RAW]+ sim:+ image: ghcr.io/mll-lab-nu/eai-olympiad:0.1.0+ volumes:+ - rcb_observe:/run/rcb-observe:ro # rcb-monitor+ - ./sim:/srv:ro+ working_dir: /srv+ command: python3 /srv/core/launch.py+ cpus: 4+ mem_limit: 8g+ pids_limit: 256+ cap_drop: [NET_RAW]+ environment:+ RCB_DATA: "/data"+ MUJOCO_GL: "osmesa"+ PYOPENGL_PLATFORM: "osmesa"+ OPENBLAS_NUM_THREADS: "1"+ OMP_NUM_THREADS: "1"+ RO_PLUGIN: "/srv/sport/plugin.py"+ RO_SPORT: "fencing"+ RO_FORMAT: "bout"+ RO_SEATS: "A"+ RO_SEED: "35"+ RO_SEED_SALT: ""+ RO_SEED_INDEX: ""+ RO_FIRST: "A"+ RO_LEVEL: "2"+ RO_RENDERER: "mujoco"+ RCB_ACTION_LEVEL: "low"+ RCB_PLAY: "program"+ RCB_ACT_RULE: "program"+ CLOCK_S: "3600"+ START_TIMEOUT_S: "1800"+ READY_TIMEOUT_S: "300"+ SEAT_HOSTS: ""+ RCB_RENDER_VIDEO: "1"+ RCB_BROADCAST: "1"+ RO_REPLAY_TIMEOUT_S: "600"+ RCB_VIDEO_TIMEOUT_S: "900"+ RO_VIDEO_RENDERER: ""+ PLAYER_MODE_A: "unmetered"+ RCB_WALL_CLOCK_S: "7200"+ # >>> rcb_monitor (resource limits monitor, docs/PROTOCOL.md §2.10; generated by scripts/rcb_monitor/inject.py)+ rcb_monitor:+ image: ghcr.io/mll-lab-nu/eai-monitor:0.1.0@sha256:f2c910f53f79c2bfa4a71298b10c78383cae3afc40720ca562cc845b8d20fb0c+ pid: host # sees every container's processes (and NVML's host PIDs); the agent never sees it+ cgroup: host # reads each container's own cgroup (memory, OOM kills, caps)+ network_mode: none+ cap_add: [SYS_PTRACE] # reads /proc of processes running as other users+ cpus: 0.5+ mem_limit: 256m+ pids_limit: 64+ restart: on-failure:3+ working_dir: /var/rcb-monitor+ volumes:+ - ./rcb_monitor:/opt/rcb_monitor:ro+ - rcb_limits:/run/rcb-limits+ - rcb_observe:/run/rcb-observe+ environment:+ RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} # 1: stop the agent at a confirmed violation, and fail the trial+ command: ["python3", "/opt/rcb_monitor/monitor.py", "run"]+ # <<< rcb_monitor+volumes: # rcb-monitor+ rcb_limits: # rcb-monitor+ rcb_observe: # rcb-monitordiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/game b/tasks/roboolympics-fencing-bout-i02-standard/environment/gamenew file mode 100755index 0000000000..d5069faa64--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/game@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""game - your seat in the match (the same commands for every sport; the actions are the sport's, see `game spec`).++ game spec the sport: actions (types, fields, ranges), cameras, units, rules, timing+ game status the current state, no images+ game start you are ready (preparation over); the match begins when every seat has started+ game wait [SECONDS] turn-based: block until it is your turn; real time: let the world run SECONDS (<= 1)+ game observe [QUERY_JSON] the state and the camera images (saved as PNG under /app/output/views/)+ game act ACTION_JSON one action, e.g. game act '{"type": "throw", ...}' (if the sport shows the result+ in images, they are saved like observe's, as reply_*.png)+ game ready "WHY" "PLAN" your review (after each of your actions, turn-based; at each review, real time)+ game say "TEXT" team formats: a message to your teammates (never shown to the other side)+ game team [SINCE] team formats: your teammates' messages after seq SINCE (default 0); reading never+ consumes them (observe / status show the recent ones and team_seq, the newest seq)+Sport shortcuts (generated from the sport's declaration):+ game phrase INTENTION"""+import base64+import json+import os+import sys+import tempfile+import urllib.error+import urllib.request++COMMANDS = json.loads('{"phrase": ["phrase", "intention"]}') # shortcut -> [action type, field, field, ...]+VIEWS = "/app/output/views"+BASE = os.environ.get("SIM_URL", "http://sim:8000") + "/" + os.environ.get("SEAT", "A")+++def call(ep, body=None):+ req = urllib.request.Request(BASE + "/" + ep, data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=600) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ try:+ out = json.load(e)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+++def save(b64, name):+ os.makedirs(VIEWS, exist_ok=True)+ fd, p = tempfile.mkstemp(dir=VIEWS, prefix=name + "_", suffix=".png")+ with os.fdopen(fd, "wb") as f:+ f.write(base64.b64decode(b64))+ return p+++def show(o):+ ob = o.get("observation")+ if isinstance(ob, dict) and ob.get("image_png_b64"):+ ob["image_file"] = save(ob.pop("image_png_b64"), "reply" if ob.get("of") else "obs")+ for k in [k for k in o if k.endswith("_image_b64")]:+ if o[k]:+ o[k[:-4] + "_file"] = save(o.pop(k), k[:-10])+ else:+ o.pop(k)+ print(json.dumps(o, indent=1))+++def arg(name, x):+ """A shortcut's argument as the act body carries it: `entity` as written (an id), true / false as booleans, a+ number as a number, anything else (an enum value) as written; the core checks every field against the schema."""+ if name == "entity":+ return x+ if x in ("true", "false"):+ return x == "true"+ try:+ return float(x)+ except ValueError:+ return x+++def main(a):+ turn = call("spec").get("protocol", "").startswith("eai-standard-turn") if a[:1] == ["wait"] else None+ if a == ["spec"]:+ show(call("spec"))+ elif a == ["status"]:+ show(call("status"))+ elif a == ["start"]:+ show(call("start", {}))+ elif a[:1] == ["wait"] and len(a) <= 2:+ if turn:+ while True:+ o = call("wait", {"timeout_s": 60})+ st = o.get("state") or {}+ if "error" in o or st.get("done") or st.get("your_turn"):+ break+ show(o)+ else:+ show(call("wait", {"dt": float(a[1]) if len(a) == 2 else 0.1}))+ elif a[:1] == ["observe"] and len(a) <= 2:+ show(call("observe", {"query": json.loads(a[1])} if len(a) == 2 else {}))+ elif a[:1] == ["act"] and len(a) == 2:+ show(call("act", json.loads(a[1])))+ elif a[:1] == ["ready"] and len(a) == 3:+ show(call("ready", {"why": a[1], "plan": a[2]}))+ elif a[:1] == ["say"] and len(a) == 2:+ show(call("say", {"text": a[1]}))+ elif a[:1] == ["team"] and len(a) <= 2:+ show(call("team", {"since": int(a[1]) if len(a) == 2 else 0}))+ elif a and a[0] in COMMANDS and len(a) == len(COMMANDS[a[0]]):+ kind, *names = COMMANDS[a[0]]+ show(call("act", {"type": kind, **{n: arg(n, x) for n, x in zip(names, a[1:])}}))+ else:+ sys.exit(__doc__)+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/limits.json b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/limits.jsonnew file mode 100644index 0000000000..56290adc7b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/limits.json@@ -0,0 +1,39 @@+{+ "agent_timeout_sec": 7200,+ "caps": {+ "main": {+ "cpus": 2.0,+ "memory_gb": 6.0,+ "pids": 8192+ },+ "sim": {+ "cpus": 4.0,+ "memory_gb": 8.0,+ "pids": 256+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": false,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 0.0,+ "max_memory_gb": 4.0,+ "max_processes": 512,+ "mode": "standard",+ "scope": "agent",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "roboolympics-fencing-bout-i02-standard",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 0.0,+ "trial_max_memory_gb": 12.0,+ "window_sec": 120.0+}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/monitor.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/monitor.pynew file mode 100644index 0000000000..e87516ba84--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/monitor.py@@ -0,0 +1,1127 @@+#!/usr/bin/env python3+"""rcb_monitor: the trusted resource-limits monitor sidecar of every task (docs/PROTOCOL.md §2.10, record rcb-monitor/1).++Runs as the compose service `rcb_monitor` (generated by scripts/rcb_monitor/inject.py): `pid: host`, `cgroup: host`,+`network_mode: none`, CAP_SYS_PTRACE, the task's GPU reservation, its code read-only from the task directory. The agent+cannot see it (another PID namespace), reach it (no network) or write its record (its own file system).++Which containers it watches: the services that mount the trial's beacon volume `rcb_limits` (read-only at+/run/rcb-limits) are in scope, the ones that mount `rcb_observe` are only recorded (the benchmark's own services: the+simulator sidecar of standard modes, RoboPaint's privileged `scorer`). The compose project names both volumes, so they are unique to the trial; the monitor finds the containers as+the mount namespaces whose /run/rcb-limits is the same directory as its own (docker compose exec'd processes included).+A namespace that does not show the beacon is asked again at every tick (a container that is still being set up has the+host's root until its pivot_root: "no" is never remembered); a "yes" is kept only while the process that proved it lives.+A process whose first thread has exited is found through a thread that lives; a zombie counts in its parent's container.++Every tick (5 s; disk every 60 s) it samples, per container and summed over the scope: GPU memory (NVML, per process,+compute and graphics), memory (cgroup anon+shmem when the container has its own cgroup, else PSS anon+shmem), processes+(TGIDs, zombies included), disk growth under the limits' disk_paths in the agent's container (complete walks only, in+slices between the samples), CPU (recorded only). It appends to /var/rcb-monitor/samples.jsonl and+events.jsonl and writes the agent-visible /run/rcb-limits/usage.json: the current values, the limits and the agent's+clock (`elapsed_s`, `time_left_s`, `deadline_utc`: the task's `[agent] timeout_sec`, counted from the monitor's start,+which is the trial environment's start, a little before the agent's session starts, so it never overstates the time left).++The agent-side session log (robot_coding_bench #233): the privileged tooling writes /app/output/rcb_session_log.jsonl+from the agent's own process, so the agent can delete or rewrite it. Every tick the monitor copies what was appended to+it, append-only, into its record (session_log/<segment>.jsonl; a truncated, replaced or rewritten file starts a new+segment, a removed one keeps its copy; `session_log_rewritten` / `session_log_removed` events). The verifier step+(rcb_limits.sanitize, before the grader) gives the grader that copy when the agent's file is not what was written.++Kernel OOM kills (`oom` events) are read from each watched container's cgroup `memory.events` by a thread of its own+(OomWatch), many times a second: a kill that takes the container's main process with it ends the container, and compose+restarts it with a new cgroup whose counters start at 0, within milliseconds -- a reading once per tick never sees it.+Every event says whom it hit (`scope`: a container the limits bind, or a benchmark-owned service that is only+recorded) and why (`cause`): "cap" when the container's own `oom` counter rose with it (the kernel says its memory+reached its own cap), else "host" (the host's OOM killer, or an enclosing cgroup's: not this container's doing).+Only a "cap" kill in the scope is a violation (rcb_limits.violations); the verifier step reports the others.++RCB_LIMITS_ENFORCE=1 (run-time switch; compose default 0; 0/1/true/false, anything else is a fatal record): once a+violation is confirmed (rcb_limits.violations, the verifier's own rule) the monitor SIGKILLs every in-scope process+except each container's PID 1, so the agent stops at once and Harbor goes on to collection and the verifier (an agent+killed this way ends like one that exited non-zero). It also protects the host (`emergency_kill` events, never a+violation by themselves): above EMERGENCY_GPU_FACTOR x the GPU-memory limit at one sample it kills the scope's process+that holds the most GPU memory; where the runtime applies no kernel memory cap, it stands in for it and kills the+largest process once the scope is above its declared memory caps.+0: it only records.++ python3 monitor.py run # the service's command+ python3 monitor.py seal --wait 90 # the first sidecar collect hook: seal the record (summary.json), print it+ python3 monitor.py beacon # for a runner whose container runtime cannot run the monitor (no `pid: host`,+ # e.g. rootless podman without cgroups): the same service without pid/cgroup host,+ # writing only the agent's clock and `"measured": false` to usage.json+"""+import ctypes+import json+import os+import select+import signal+import stat as stat_mod+import sys+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import rcb_limits # noqa: E402+import selftest # noqa: E402++REC = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+PROC, CGROUP = "/proc", "/sys/fs/cgroup" # module globals: scripts/rcb_monitor/test_monitor.py points them at a fake tree+SCOPE_BEACON, OBSERVE_BEACON = "/run/rcb-limits", "/run/rcb-observe"+LIMITS = os.path.join(HERE, "limits.json")+HZ = os.sysconf("SC_CLK_TCK")+PAGE = os.sysconf("SC_PAGE_SIZE")+GIB = float(2 ** 30)+EMERGENCY_GPU_FACTOR = 1.5 # host protection (enforced runs): above this x the GPU-memory limit at one sample+DISK_SLICE_SEC = 1.5 # of every tick a running disk walk may take (the monitor's CPU cap is half a core)+DISK_WALK_MAX_SEC = 300.0 # a walk not finished by then is partial: a gap in the record, never a baseline+OOM_COLD_SEC = 0.02 # OomWatch: every memory.events is read this often (or at once, when the kernel notifies)+OOM_HOT_SEC = 0.002 # ... and this often for OOM_HOT_FOR_SEC after any of them changed (memory pressure)+OOM_HOT_FOR_SEC = 2.0+OOM_CAP_WINDOW_SEC = 10.0 # a kill is the container's own cap's when its `oom` counter rose with it or this shortly before+OOM_FORGET_SEC = 600.0 # a cgroup not seen by the sampler for this long is no longer watched+SESSION_LOG = "app/output/rcb_session_log.jsonl" # in the agent's container (rcb_limits.SESSION_LOG_NAME)+SESSION_LOG_MAX = 64 * 2 ** 20 # bytes copied at most (rcb_limits.MAX_SESSION_LOG: what a grader is given to read)+SESSION_LOG_TAIL = 4096 # bytes of the copied tail compared at every tick (a rewrite of what was copied)+++# --------------------------------------------------------------------------------------------------- small helpers+def now():+ return time.time()+++def rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def read(p):+ try:+ with open(p) as f:+ return f.read()+ except OSError:+ return None+++def stat_id(p):+ try:+ st = os.stat(p)+ return (st.st_dev, st.st_ino)+ except OSError:+ return None+++def stat_of(base):+ """(starttime, utime+stime) of the process or thread at /proc path `base`, or None."""+ s = read(base + "/stat")+ if not s:+ return None+ try:+ f = s.rsplit(")", 1)[1].split()+ return int(f[19]), int(f[11]) + int(f[12])+ except (IndexError, ValueError):+ return None+++def proc_stat(pid):+ return stat_of(f"{PROC}/{pid}")+++def status(pid):+ s = read(f"{PROC}/{pid}/status")+ if not s:+ return {}+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v.strip()+ return d+++def kb(v):+ try:+ return int((v or "0").split()[0])+ except (ValueError, IndexError):+ return 0+++def append(name, obj):+ with open(os.path.join(REC, name), "a") as f:+ f.write(json.dumps(obj, separators=(",", ":")) + "\n")+++def write_json(path, obj):+ tmp = path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f, indent=1)+ os.replace(tmp, path)+++def event(kind, **kw):+ kw.update(t=round(now(), 2), event=kind)+ append("events.jsonl", kw)+++def clock(t, start, timeout):+ """The agent's clock for usage.json (robot_coding_bench #231): seconds since `start` (the trial environment's start)+ and, with the task's time limit, the time left and the deadline. Counted from before the agent's session starts, so+ `time_left_s` is never more than the agent really has."""+ out = {"elapsed_s": round(max(0.0, t - start), 1)}+ if timeout:+ out.update(time_limit_s=int(timeout), time_left_s=round(max(0.0, start + timeout - t), 1),+ deadline_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(start + timeout)))+ return out+++def usage_limits(lim):+ return {k: lim.get(k) for k in ("max_gpu_memory_gb", "max_memory_gb", "max_processes", "max_disk_gb", "sustain_sec",+ "window_sec")}+++def open_in_root(root, rel):+ """A read-only fd of the regular file `rel` under the directory `root` (a container's /proc/<pid>/root), never+ through a symbolic link (an absolute link would resolve in the monitor's own file system), or None."""+ fd = None+ try:+ fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY)+ parts = rel.split("/")+ for part in parts[:-1]:+ nfd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)+ os.close(fd)+ fd = nfd+ f = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd)+ if not stat_mod.S_ISREG(os.fstat(f).st_mode):+ os.close(f)+ return None+ return f+ except OSError:+ return None+ finally:+ if fd is not None:+ os.close(fd)+++class SessionLogCopy:+ """Append-only copy of the agent's session log into the record (#233). State (inode, offset, segment, tail hash)+ lives in the record's state.json, so a restarted monitor goes on where it was."""++ def __init__(self, state=None):+ self.s = dict(state or {"ino": None, "off": 0, "seg": 0, "tail": "", "copied": 0, "gone": False})++ def step(self, root):+ import hashlib+ fd = open_in_root(root, SESSION_LOG)+ if fd is None:+ if self.s["ino"] is not None and not self.s["gone"]:+ self.s["gone"] = True+ event("session_log_removed", copied=self.s["copied"], segment=self.s["seg"])+ return+ try:+ st = os.fstat(fd)+ s = self.s++ def tail_of(end):+ os.lseek(fd, max(0, end - SESSION_LOG_TAIL), 0)+ return hashlib.sha256(os.read(fd, min(SESSION_LOG_TAIL, end))).hexdigest()++ if s["ino"] is not None and (st.st_ino != s["ino"] or st.st_size < s["off"] or s["gone"]+ or (s["off"] and tail_of(s["off"]) != s["tail"])):+ event("session_log_rewritten", copied=s["off"], size=st.st_size, segment=s["seg"] + 1,+ why="replaced" if st.st_ino != s["ino"] else "truncated" if st.st_size < s["off"] else+ "back after removal" if s["gone"] else "rewritten")+ s.update(off=0, seg=s["seg"] + 1, tail="")+ s.update(ino=st.st_ino, gone=False)+ n = min(st.st_size - s["off"], SESSION_LOG_MAX - s["copied"])+ if n <= 0:+ return+ os.lseek(fd, s["off"], 0)+ data = b""+ while len(data) < n:+ chunk = os.read(fd, n - len(data))+ if not chunk:+ break+ data += chunk+ d = os.path.join(REC, "session_log")+ os.makedirs(d, exist_ok=True)+ with open(os.path.join(d, "%d.jsonl" % s["seg"]), "ab") as out:+ out.write(data)+ s["off"] += len(data)+ s["copied"] += len(data)+ s["tail"] = tail_of(s["off"])+ finally:+ os.close(fd)+++def no_dump():+ """Not dumpable: without CAP_SYS_PTRACE nobody (not even the same uid) can open /proc/<monitor>/{root,mem,fd}."""+ try:+ ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLE = 4+ except Exception:+ pass+++# --------------------------------------------------------------------------------------------------- NVML+class Nvml:+ """Per-process GPU memory (host PIDs: the monitor runs in the host PID namespace) and per-card use, via libnvidia-ml+ (ctypes; no nvidia-smi child processes)."""++ class Proc(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong),+ ("gpuInstanceId", ctypes.c_uint), ("computeInstanceId", ctypes.c_uint)]++ class Proc1(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong)]++ class Mem(ctypes.Structure):+ _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]++ def __init__(self):+ self.lib = ctypes.CDLL("libnvidia-ml.so.1")+ if self.lib.nvmlInit_v2() != 0:+ raise RuntimeError("nvmlInit failed")+ n = ctypes.c_uint(0)+ self.lib.nvmlDeviceGetCount_v2(ctypes.byref(n))+ self.handles = []+ for i in range(n.value):+ h = ctypes.c_void_p()+ if self.lib.nvmlDeviceGetHandleByIndex_v2(i, ctypes.byref(h)) == 0:+ self.handles.append(h)+ self.fns = []+ for name, st in (("nvmlDeviceGetComputeRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses", self.Proc1),+ ("nvmlDeviceGetGraphicsRunningProcesses", self.Proc1)):+ kind = "compute" if "Compute" in name else "graphics"+ if any(k == kind for k, _, _ in self.fns):+ continue+ try:+ self.fns.append((kind, getattr(self.lib, name), st))+ except AttributeError:+ pass++ def sample(self):+ """({host pid: MiB}, {card index: (used MiB, total MiB)}, {host pids whose memory NVML does not tell})."""+ per, cards, unknown = {}, {}, set()+ for i, h in enumerate(self.handles):+ m = self.Mem()+ if self.lib.nvmlDeviceGetMemoryInfo(h, ctypes.byref(m)) == 0:+ cards[i] = (m.used // 2 ** 20, m.total // 2 ** 20)+ seen = {}+ for _kind, fn, st in self.fns:+ cnt = ctypes.c_uint(0)+ rc = fn(h, ctypes.byref(cnt), None)+ if rc not in (0, 7): # 7 = NVML_ERROR_INSUFFICIENT_SIZE: cnt now holds the count+ continue+ cnt = ctypes.c_uint(cnt.value + 16)+ arr = (st * cnt.value)()+ if fn(h, ctypes.byref(cnt), arr) != 0:+ continue+ for k in range(cnt.value):+ mem = arr[k].usedGpuMemory+ if mem >= 2 ** 63: # NVML_VALUE_NOT_AVAILABLE (MIG / vGPU / WSL): not a zero+ unknown.add(arr[k].pid)+ mib = 0+ else:+ mib = mem // 2 ** 20+ seen[arr[k].pid] = max(seen.get(arr[k].pid, 0), mib) # a C+G process is in both lists+ for p, v in seen.items():+ per[p] = per.get(p, 0) + v+ return per, cards, unknown+++# --------------------------------------------------------------------------------------------------- disk+class DiskWalk:+ """One measurement of the files under `paths` below `root` (the agent container's root, seen through /proc): the+ sum of st_blocks, every hard-linked file once, never descending into another mount (a directory on another device;+ files are not asked for theirs: on an overlay root whose layers sit on different file systems they report their+ layer's), `exclude` skipped. It runs in+ slices (step) between the monitor's samples, so a large tree delays no sample. `done` only when every directory was+ read: only then is `bytes` a measurement; before that it is a lower bound."""++ def __init__(self, root, paths, exclude):+ self.root, self.t0 = root, now()+ self.bytes = self.entries = 0+ self.done, self.why = False, None+ self._it = self._walk(list(paths), {root + x.rstrip("/") for x in exclude})++ def _walk(self, paths, excl):+ linked = set() # (dev, ino) of files with several names: counted once+ for base in paths:+ top = self.root + base+ try:+ dev = os.lstat(top).st_dev+ except FileNotFoundError:+ continue # the path does not exist in this container: nothing under it+ except OSError as e:+ self.why = f"{base}: {type(e).__name__}"+ return+ stack = [top]+ while stack:+ d = stack.pop()+ try:+ it = os.scandir(d)+ except FileNotFoundError:+ continue # removed since its parent was read+ except OSError as e:+ self.why = f"{d[len(self.root):]}: {type(e).__name__}"+ return+ with it:+ for e in it:+ try:+ st = e.stat(follow_symlinks=False)+ except OSError:+ continue # removed meanwhile+ if stat_mod.S_ISDIR(st.st_mode):+ if st.st_dev != dev or e.path in excl:+ continue # another mount (never crossed: not the container's own files)+ stack.append(e.path)+ elif st.st_nlink > 1:+ k = (st.st_dev, st.st_ino)+ if k in linked:+ continue+ linked.add(k)+ self.bytes += st.st_blocks * 512+ self.entries += 1+ if self.entries % 256 == 0:+ yield+ yield+ self.done = True++ def step(self, budget_sec):+ """Walk on for at most `budget_sec`; True when the walk has ended (done, or failed with `why`)."""+ end = now() + budget_sec+ for _ in self._it:+ if now() >= end:+ return False+ return True+++# --------------------------------------------------------------------------------------------------- OOM kills+class OomWatch:+ """Kernel OOM kills of the watched containers, from each one's cgroup v2 `memory.events`:+ oom times the cgroup's memory reached its own limit (memory.max) and an allocation was about to fail+ oom_kill processes of the cgroup killed by any OOM killer (its own limit's, an enclosing cgroup's, the host's)+ A kill whose `oom` counter rose with it (or within OOM_CAP_WINDOW_SEC before) happened at the container's own cap+ (`cause: "cap"`); one without is the host's or an enclosing cgroup's OOM killer (`cause: "host"`), which the+ container did not cause by its own use (PROTOCOL §2.10: nothing another trial does can fail a trial).++ The counters live and die with the cgroup, and a container whose main process is killed is gone (and restarted by+ compose with fresh counters) within milliseconds. So the files are read by this object's own thread, every+ OOM_COLD_SEC, at once when the kernel signals a change (poll: memory.events notifies), and every OOM_HOT_SEC for a+ while after any change (the `max` counter rises under memory pressure, before a kill). A kill that removes the+ cgroup within about a millisecond can still be missed: such a kill is then in no record.++ scan() reads every file once; the sampler calls it at each tick when the thread does not run (the tests). The+ thread ends when the record is sealed."""++ def __init__(self):+ self.lock = threading.Lock()+ self.w = {} # cgroup dir -> {"role", "scope", "fd", "kill", "oom", "sig", "cap_t", "seen"}+ self.hot_until = 0.0+ self.thread = None+ self.stopped = False # set at the seal: the record is closed, like the samples++ def watch(self, cg, role, scope, t):+ """The sampler saw this container's cgroup at time t."""+ with self.lock:+ e = self.w.get(cg)+ if e is None:+ e = self.w[cg] = {"fd": None, "kill": None, "oom": None, "sig": None, "cap_t": None}+ e.update(role=role, scope=bool(scope), seen=t)++ @staticmethod+ def _close(e):+ if e["fd"] is not None:+ try:+ os.close(e["fd"])+ except OSError:+ pass+ e["fd"] = None++ def _read(self, cg, e):+ """The counters of the cgroup's memory.events ({} when the file cannot be read: the container is not up).+ A file that stops answering belonged to a cgroup that is gone; the same path opened again is a new cgroup (the+ container restarted: another directory, by its inode and creation time), whose counters all belong to the+ trial: they are compared with 0. The same cgroup opened again keeps what was already counted."""+ for _ in (0, 1):+ try:+ if e["fd"] is None:+ e["fd"] = os.open(cg + "/memory.events", os.O_RDONLY)+ st = os.stat(cg)+ ident = (st.st_dev, st.st_ino, st.st_ctime_ns)+ if e["sig"] is not None and ident != e.get("ident"):+ e["kill"] = e["oom"] = 0 # read before, gone, here again: another instance of the cgroup+ e["ident"] = ident+ os.lseek(e["fd"], 0, os.SEEK_SET)+ out = {}+ for line in os.read(e["fd"], 8192).decode("ascii", "replace").splitlines():+ k, _, v = line.partition(" ")+ if v.strip().isdigit():+ out[k] = int(v)+ return out+ except OSError:+ self._close(e)+ return {}++ def scan(self):+ """Read every watched file once and record the kills since the last reading. True when a counter changed."""+ changed = False+ with self.lock:+ t = now()+ for cg, e in list(self.w.items()):+ if t - e["seen"] > OOM_FORGET_SEC:+ self._close(e)+ del self.w[cg]+ continue+ c = self._read(cg, e)+ if "oom_kill" not in c:+ continue+ kill, oom = c["oom_kill"], c.get("oom", 0)+ sig = (kill, oom, c.get("max", 0))+ if e["kill"] is None or kill < e["kill"] or oom < e["oom"]:+ # the first reading is the baseline; counters that went back are a new cgroup under the same path+ e["kill"], e["oom"] = (kill, oom) if e["kill"] is None else (0, 0)+ changed |= sig != e["sig"]+ if oom > e["oom"]:+ e["cap_t"] = t+ if kill > e["kill"]:+ at_cap = e["cap_t"] is not None and t - e["cap_t"] <= OOM_CAP_WINDOW_SEC+ kw = {"role": e["role"], "scope": e["scope"], "count": kill - e["kill"],+ "cause": "cap" if at_cap else "host", "cap_hits": oom - e["oom"]}+ for name, key in (("memory.max", "memory_cap_gb"), ("memory.current", "memory_current_gb")):+ v = (read(cg + "/" + name) or "").strip() # evidence only: the cause is the counters'+ if v.isdigit():+ kw[key] = round(int(v) / GIB, 3)+ event("oom", **kw)+ e["kill"], e["oom"], e["sig"] = kill, oom, sig+ return changed++ def start(self):+ self.thread = threading.Thread(target=self._loop, name="rcb-oom-watch", daemon=True)+ self.thread.start()++ def _loop(self):+ said = False+ while not self.stopped:+ try:+ if self.scan():+ self.hot_until = now() + OOM_HOT_FOR_SEC+ if now() < self.hot_until:+ time.sleep(OOM_HOT_SEC)+ continue+ with self.lock:+ fds = [e["fd"] for e in self.w.values() if e["fd"] is not None]+ if not fds:+ time.sleep(OOM_COLD_SEC)+ continue+ p = select.poll() # memory.events notifies its readers (POLLPRI) when it changes+ for fd in fds:+ p.register(fd, select.POLLPRI | select.POLLERR)+ if p.poll(OOM_COLD_SEC * 1000):+ self.hot_until = now() + OOM_HOT_FOR_SEC+ except Exception as e: # never stop watching+ if not said:+ said = True+ try:+ event("error", why=f"oom watch: {type(e).__name__}: {e}"[:300])+ except Exception:+ pass+ time.sleep(OOM_COLD_SEC)+++# --------------------------------------------------------------------------------------------------- the monitor+class Monitor:+ def __init__(self):+ self.lim = rcb_limits.read_json(LIMITS) or {}+ self.tick = float(self.lim.get("tick_sec", 5))+ self.disk_tick = float(self.lim.get("disk_tick_sec", 60))+ self.enforce, self.switch_error = rcb_limits.parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ self.me_mnt = rl(f"{PROC}/self/ns/mnt")+ self.beacon = {"scope": stat_id(SCOPE_BEACON), "observe": stat_id(OBSERVE_BEACON)}+ self.cls = {} # mnt ns -> {"kind", "role", "witness": (proc path, starttime)}: only what IS watched+ self.neg, self.ok = set(), set() # this tick: namespaces that said no / whose witness still lives+ self.via = {} # pid -> /proc path of a living thread, for a process whose first thread has exited+ self.prev_cpu = {} # pid -> (starttime, ticks, t)+ self.oomw = OomWatch() # kernel OOM kills of the watched containers (its own thread in run())+ self.disk_base = None # GiB under disk_paths at the first complete walk (kept in state.json across restarts)+ self.disk_last = 0.0+ self.disk_gb = None+ self.walk = None # (DiskWalk, mnt ns, proc path, starttime) of the measurement under way+ self.slog = SessionLogCopy()+ self.series = [] # [(t, {metric: value})] of the last window, for enforcement decisions+ self.confirmed = {} # metric -> time+ self.kill_until = 0.0+ self.killed = 0+ self.emergency = [] # the emergency_kill events of this run+ self.scope_seen = False+ self.gpu_unknown = False+ self.caps = selftest.capabilities()+ self.nvml = None+ try:+ self.nvml = Nvml()+ except Exception as e:+ self.caps["nvml_error"] = f"{type(e).__name__}: {e}"[:200]+ self.caps["nvml"] = int(self.nvml is not None)+ self.caps["nvml_devices"] = len(self.nvml.handles) if self.nvml else 0+ self.t0 = now()+ self.clock_t0 = self.t0 # the agent's clock (usage.json): the first start's, across restarts (run())+ self.timeout = float(self.lim.get("agent_timeout_sec") or 0)+ self._usage_vals = None+ self._last_measures, self._gpu_per = [], {}+ self.fatal_scope = False++ # ---- scope discovery+ def base(self, pid):+ """The /proc path to read a process's namespaces, root and memory from."""+ return self.via.get(pid) or f"{PROC}/{pid}"++ def classify(self, mnt, base):+ """{"kind": "scope" | "observe", "role": "main" | "sidecar"} when the mount namespace `mnt` (of the process or+ thread at /proc path `base`) is one of the trial's containers, else None.++ "No" is never remembered beyond this tick: while a container is set up, its init process is already in a new+ mount namespace but still has the host's root, and the beacon appears only with its pivot_root. "Yes" is+ remembered while the process that proved it lives in the namespace (the kernel may give the number of a+ namespace that ended to a new one)."""+ if mnt in self.ok:+ return self.cls[mnt]+ if mnt in self.neg:+ return None+ c = self.cls.get(mnt)+ if c is not None:+ wbase, wstart = c["witness"]+ ws = stat_of(wbase)+ if ws and ws[0] == wstart and rl(wbase + "/ns/mnt") == mnt:+ self.ok.add(mnt)+ return c+ del self.cls[mnt]+ root = base + "/root"+ kind = None+ if self.beacon["scope"] and stat_id(root + SCOPE_BEACON) == self.beacon["scope"]:+ kind = "scope"+ elif self.beacon["observe"] and stat_id(root + OBSERVE_BEACON) == self.beacon["observe"]:+ kind = "observe"+ st = stat_of(base)+ here = st is not None and rl(base + "/ns/mnt") == mnt # a vanished process tells nothing: ask the next+ if kind and here:+ c = {"kind": kind, "role": "main" if os.path.isdir(root + "/logs/agent") else "sidecar",+ "witness": (base, st[0])}+ self.cls[mnt] = c+ self.ok.add(mnt)+ return c+ if here:+ self.neg.add(mnt)+ return None++ def live_thread(self, pid):+ """/proc path of a thread of `pid` that still runs (its first thread has exited: /proc/<pid>/ns is empty)."""+ try:+ tids = os.listdir(f"{PROC}/{pid}/task")+ except OSError:+ return None+ for tid in tids:+ b = f"{PROC}/{pid}/task/{tid}"+ if tid != str(pid) and rl(b + "/ns/mnt"):+ return b+ return None++ def groups(self):+ """{mnt ns: {"kind", "role", "pids": [...], "zombies": n}} of the watched containers."""+ self.neg, self.ok, self.via = set(), set(), {}+ out, where, lost = {}, {}, []+ try:+ names = os.listdir(PROC)+ except OSError:+ names = []+ for d in names:+ if not d.isdigit():+ continue+ pid = int(d)+ mnt = rl(f"{PROC}/{pid}/ns/mnt")+ if mnt is None:+ lost.append(pid)+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, f"{PROC}/{pid}")+ if c:+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ zombies = []+ for pid in lost:+ b = self.live_thread(pid)+ if not b:+ zombies.append(pid)+ continue+ mnt = rl(b + "/ns/mnt") # its first thread exited, the others run on: a process like any other+ if mnt is None:+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, b)+ if c:+ self.via[pid] = b+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ for pid in zombies:+ st = status(pid)+ if st.get("State", "").startswith("Z"): # a zombie holds a PID until its parent reaps it: counted there+ try:+ g = out.get(where.get(int(st.get("PPid", "0"))))+ except ValueError:+ g = None+ if g:+ g["zombies"] += 1+ self.cls = {m: c for m, c in self.cls.items() if m in self.ok}+ return out++ # ---- per-container measurements+ def cgroup_of(self, pids):+ """The container's own cgroup v2 directory (under the host tree, `cgroup: host`) when every process in it is this+ container's (rootless podman without cgroup delegation leaves containers in a shared one), else None."""+ paths = set()+ for p in pids[:8]:+ s = read(f"{PROC}/{p}/cgroup") or ""+ for line in s.splitlines():+ if line.startswith("0::"):+ paths.add(line[3:].strip())+ if len(paths) != 1:+ return None+ d = CGROUP + paths.pop()+ procs = read(d + "/cgroup.procs")+ if procs is None:+ return None+ members = {int(x) for x in procs.split() if x.isdigit()}+ return d if members and members <= set(pids) else None++ def mem_pss(self, pids):+ tot = 0+ for p in pids:+ s = read(self.base(p) + "/smaps_rollup")+ if s is None:+ st = status(p)+ tot += kb(st.get("RssAnon")) + kb(st.get("RssShmem"))+ continue+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v+ tot += (kb(d.get("Pss_Anon")) + kb(d.get("Pss_Shmem"))) if "Pss_Anon" in d else kb(d.get("Pss"))+ return tot / 1024.0 / 1024.0 # GiB++ def measure(self, g, gpu_per, t, gpu_unknown=()):+ pids = g["pids"]+ threads = cpu = 0.0+ for p in pids:+ threads += int(status(p).get("Threads", "0") or 0)+ ps = proc_stat(p)+ if ps:+ pv = self.prev_cpu.get(p)+ if pv and pv[0] == ps[0] and t > pv[2]:+ cpu += max(0, ps[1] - pv[1]) / HZ / (t - pv[2])+ self.prev_cpu[p] = (ps[0], ps[1], t)+ cg = self.cgroup_of(pids)+ m = {"kind": g["kind"], "role": g["role"], "processes": len(pids) + g.get("zombies", 0),+ "zombies": g.get("zombies", 0), "threads": int(threads), "cpu": round(cpu, 2),+ "gpu_memory_gb": round(sum(gpu_per.get(p, 0) for p in pids) / 1024.0, 3), "cgroup": int(cg is not None)}+ unknown = sum(1 for p in pids if p in gpu_unknown)+ if unknown:+ m["gpu_unmeasured"] = unknown # processes on the GPU whose memory NVML does not tell+ if cg:+ st = {}+ for line in (read(cg + "/memory.stat") or "").splitlines():+ k, _, v = line.partition(" ")+ st[k] = v+ try:+ m["memory_gb"] = round((int(st.get("anon", 0)) + int(st.get("shmem", 0))) / GIB, 3)+ except ValueError:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ mx = (read(cg + "/memory.max") or "").strip()+ m["memory_cap_gb"] = None if mx in ("", "max") else round(int(mx) / GIB, 2)+ self.oomw.watch(cg, g["role"], g["kind"] == "scope", now())+ else:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ return m++ # ---- disk+ def main_proc(self, groups):+ """(mnt ns, pid) to reach the agent container's files through: its PID 1 when visible (it outlives the others)."""+ for mnt, g in groups.items():+ if g["kind"] == "scope" and g["role"] == "main" and g["pids"]:+ init = [p for p in g["pids"] if (status(p).get("NSpid") or "").split()[-1:] == ["1"]]+ return mnt, (init[0] if init else min(g["pids"]))+ return None, None++ def disk_step(self, t, groups):+ """The disk value of this sample: GiB the files under disk_paths grew since the baseline, or None (not measured+ at this tick). Only a complete walk of a container that is still there is a measurement; only such a walk sets+ the baseline. A walk that did not finish is a lower bound: it can show that the limit is exceeded, never that it+ is not, and it never becomes the baseline."""+ if self.walk is None:+ mnt, pid = self.main_proc(groups)+ if pid is None or t - self.disk_last < self.disk_tick:+ return None+ b = self.base(pid)+ st = stat_of(b)+ if st is None:+ return None+ self.disk_last = t+ self.walk = (DiskWalk(b + "/root", self.lim.get("disk_paths") or ["/app"], self.lim.get("disk_exclude") or []),+ mnt, b, st[0])+ w, mnt, b, start = self.walk+ ended = w.step(DISK_SLICE_SEC)+ if not ended and now() - w.t0 <= DISK_WALK_MAX_SEC:+ return None # goes on at the next tick+ self.walk = None+ st = stat_of(b)+ there = st is not None and st[0] == start and rl(b + "/ns/mnt") == mnt # the same container, still up+ gb = w.bytes / GIB+ if ended and w.done and there:+ if self.disk_base is None:+ self.disk_base = gb+ self.save_state()+ event("disk_baseline", gb=round(gb, 3), entries=w.entries)+ self.disk_gb = round(max(0.0, gb - self.disk_base), 3)+ return self.disk_gb+ why = "the container's process ended during the walk" if not there else (w.why or "not finished in time")+ event("disk_partial", why=why, gb=round(gb, 3), entries=w.entries, sec=round(now() - w.t0, 1))+ lim = float(self.lim.get("max_disk_gb") or 0)+ if there and self.disk_base is not None and lim and gb - self.disk_base > lim:+ self.disk_gb = round(gb - self.disk_base, 3) # already over the limit, whatever the rest holds+ return self.disk_gb+ return None++ # ---- state that must outlive a restart of the monitor (restart: on-failure)+ def save_state(self):+ try:+ write_json(os.path.join(REC, "state.json"), {"disk_base": self.disk_base, "session_log": self.slog.s})+ except OSError:+ pass++ def restore(self):+ """After a restart: the disk baseline, the confirmed violations and the last window of samples come back from+ the record, so that a crash neither resets the baseline nor forgets time already spent over a limit."""+ st = rcb_limits.read_json(os.path.join(REC, "state.json")) or {}+ if isinstance(st.get("disk_base"), (int, float)):+ self.disk_base = float(st["disk_base"])+ if isinstance(st.get("session_log"), dict):+ self.slog = SessionLogCopy(st["session_log"])+ _, samples, events = rcb_limits.load_record(REC)+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [(s["t"], s.get("scope") or {}) for s in samples+ if isinstance(s.get("t"), (int, float)) and s["t"] >= self.t0 - window - 3 * self.tick]+ for e in events:+ k = e.get("event")+ if k == "violation" and e.get("metric"):+ self.confirmed.setdefault(e["metric"], e.get("t") or self.t0)+ elif k in ("kill", "emergency_kill"):+ self.killed += int(e.get("processes") or 0)+ if k == "emergency_kill":+ self.emergency.append(e)+ elif k == "scope_found":+ self.scope_seen = True+ if self.enforce and self.confirmed and self.t0 - max(self.confirmed.values()) < 60:+ self.kill_until = max(self.confirmed.values()) + 60++ # ---- enforcement+ @staticmethod+ def spared(pids):+ """The container's own processes that must outlive a kill: its PID 1 and what PID 1 started with it (Harbor's+ `sh -c "sleep infinity"` keepalive). Agent processes are exec'd into the container (their parent is outside+ it) or, when orphaned, adopted by PID 1 later: those are never spared."""+ st = {p: status(p) for p in pids}+ init = [p for p in pids if (st[p].get("NSpid") or "").split()[-1:] == ["1"]]+ if not init:+ return set()+ t1 = (proc_stat(init[0]) or (0, 0))[0]+ keep = set(init)+ for p in pids:+ ns_ppid = None+ ns = (st[p].get("NSpid") or "").split()+ if ns and st[p].get("PPid") is not None:+ # PPid in /proc/<pid>/status is in the reader's namespace (host); compare with PID 1's host PID+ ns_ppid = int(st[p]["PPid"])+ ps = proc_stat(p)+ if ns_ppid == init[0] and ps and ps[0] - t1 <= 2 * HZ: # started with the container, not adopted later+ keep.add(p)+ return keep++ def kill_scope(self, groups, why):+ n = 0+ for mnt, g in groups.items():+ if g["kind"] != "scope":+ continue+ snap = {p: proc_stat(p) for p in g["pids"]}+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue # PID 1 and its keepalive: the container stays up for collection+ if rl(self.base(p) + "/ns/mnt") != mnt or not snap[p] or proc_stat(p) is None \+ or proc_stat(p)[0] != snap[p][0]:+ continue # gone, or its PID now names another process+ try:+ os.kill(p, signal.SIGKILL)+ n += 1+ except OSError:+ pass+ if n:+ self.killed += n+ event("kill", why=why, processes=n)+ return n++ def scope_memory_cap(self):+ """GiB: the declared memory caps of the services the limits bind, summed (None: not declared)."""+ caps = self.lim.get("caps") or {}+ names = self.lim.get("scope_services") or (+ [n for n in caps if n != "*"] if self.lim.get("scope") == "trial" else ["main"])+ vals = [float(caps[n]["memory_gb"]) for n in names if isinstance(caps.get(n), dict) and caps[n].get("memory_gb")]+ return sum(vals) if vals else None++ def check(self, t, scope_vals, groups):+ self.series.append((t, scope_vals))+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [x for x in self.series if x[0] >= t - window - 3 * self.tick]+ samples = [{"t": a, "scope": b} for a, b in self.series]+ for v in rcb_limits.violations(samples, self.lim):+ if v["metric"] not in self.confirmed:+ self.confirmed[v["metric"]] = t+ event("violation", **v)+ if self.enforce:+ self.kill_until = t + 60+ if self.enforce and t <= self.kill_until:+ self.kill_scope(groups, ",".join(sorted(self.confirmed)))+ # Host protection (enforced runs only; PROTOCOL §2.10). An emergency kill is never a violation by itself: the+ # trial fails only by the sustained rule above or a kernel OOM kill at its own memory cap. Both conditions are+ # the trial's own doing (its scope's use against its own limit or caps), never the state of a card or host it+ # shares with other trials.+ if self.enforce:+ cap = self.scope_memory_cap()+ lim_gpu = float(self.lim.get("max_gpu_memory_gb") or 0)+ if cap and scope_vals["memory_gb"] > cap and not any(+ m.get("memory_cap_gb") for m in self._last_measures if m["kind"] == "scope"):+ # no kernel memory cap holds here (e.g. rootless podman without cgroups): stand in for it+ self._emergency(groups, "memory", cap, scope_vals["memory_gb"], key="mem")+ if lim_gpu and scope_vals["gpu_memory_gb"] > EMERGENCY_GPU_FACTOR * lim_gpu:+ self._emergency(groups, "gpu_memory", lim_gpu, scope_vals["gpu_memory_gb"], key="gpu")++ def _emergency(self, groups, why, limit, observed, key):+ best, bv = None, 0 # only a process that holds some: never one with none of it+ for g in groups.values():+ if g["kind"] != "scope":+ continue+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue+ v = self._gpu_per.get(p, 0) if key == "gpu" else self.rss_kb(p)+ if v > bv:+ best, bv = p, v+ if best:+ try:+ os.kill(best, signal.SIGKILL)+ self.killed += 1+ e = {"why": why, "limit": limit, "observed": round(observed, 3), "processes": 1}+ event("emergency_kill", **e)+ self.emergency.append(dict(e, t=round(now(), 2)))+ except OSError:+ pass++ def rss_kb(self, p):+ v = kb(status(p).get("VmRSS"))+ if not v and p in self.via: # the first thread has exited: its status has no memory lines+ for line in (read(self.via[p] + "/status") or "").splitlines():+ if line.startswith("VmRSS:"):+ v = kb(line.partition(":")[2])+ return v++ # ---- main loop+ def run(self):+ os.makedirs(REC, exist_ok=True)+ restarted = os.path.exists(os.path.join(REC, "meta.json"))+ meta = {"format": rcb_limits.FORMAT, "started": round(self.t0, 2), "enforce": self.enforce, "limits": self.lim,+ "capabilities": self.caps, "beacons": {k: bool(v) for k, v in self.beacon.items()}}+ if self.switch_error:+ meta["switch_error"] = self.switch_error+ if restarted:+ self.clock_t0 = (rcb_limits.read_json(os.path.join(REC, "meta.json")) or {}).get("started") or self.t0+ self.restore()+ event("restart", capabilities=self.caps)+ else:+ write_json(os.path.join(REC, "meta.json"), meta)+ event("start", enforce=self.enforce, capabilities=self.caps)+ if self.switch_error:+ event("fatal", why=self.switch_error + " (nothing is enforced; the trial is not a result)")+ if not self.beacon["scope"]:+ event("fatal", why="no scope beacon mounted at /run/rcb-limits")+ if self.lim.get("gpu") and not self.nvml:+ event("fatal", why="GPU task but NVML is unavailable: " + str(self.caps.get("nvml_error")))+ sys.setswitchinterval(0.001) # the OOM watch must get its turn within a millisecond+ self.oomw.start()+ while not os.path.exists(os.path.join(REC, "seal.request")):+ t = now()+ try:+ self.tick_once(t)+ except Exception as e: # a vanished process mid-read must never stop the record+ import traceback+ traceback.print_exc()+ event("error", why=f"{type(e).__name__}: {e}"[:300])+ self.write_usage(t) # every tick, a failed one too: the agent's clock never stops+ for p in list(self.prev_cpu):+ if t - self.prev_cpu[p][2] > 60:+ del self.prev_cpu[p]+ time.sleep(max(0.2, self.tick - (now() - t)))+ self.seal()+ while True: # stay up: Harbor copies the record after the hook+ time.sleep(3600)++ def tick_once(self, t):+ groups = self.groups()+ gpu_per, cards, gpu_unknown = self.nvml.sample() if self.nvml else ({}, {}, set())+ self._gpu_per = gpu_per+ ms = [self.measure(g, gpu_per, t, gpu_unknown) for g in groups.values()]+ self._last_measures = ms+ if self.oomw.thread is None:+ self.oomw.scan() # no thread (tests): read the OOM counters with the sample+ scope = [m for m in ms if m["kind"] == "scope"]+ if scope and not self.scope_seen:+ self.scope_seen = True+ event("scope_found", containers=len(scope), roles=sorted(m["role"] for m in scope))+ if not self.scope_seen and not self.fatal_scope and t - self.t0 > 120:+ self.fatal_scope = True+ event("fatal", why="no container mounting the trial's beacon found within 120 s")+ disk_now = self.disk_step(t, groups)+ _, pid = self.main_proc(groups)+ if pid is not None:+ before = dict(self.slog.s)+ self.slog.step(self.base(pid) + "/root")+ if self.slog.s != before:+ self.save_state()+ vals = {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in scope), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in scope), 3),+ "processes": sum(m["processes"] for m in scope), "disk_gb": disk_now}+ unknown = sum(m.get("gpu_unmeasured", 0) for m in scope)+ if unknown:+ vals["gpu_unmeasured"] = unknown+ if not self.gpu_unknown:+ self.gpu_unknown = True+ event("gpu_unmeasured", processes=unknown,+ why="NVML does not tell the GPU memory of processes in scope (MIG / vGPU?): counted as 0")+ obs = [m for m in ms if m["kind"] == "observe"]+ append("samples.jsonl", {"t": round(t, 2), "scope": vals,+ "observe": {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in obs), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in obs), 3),+ "processes": sum(m["processes"] for m in obs)},+ "cards": {str(k): v for k, v in cards.items()}, "containers": ms})+ self._usage_vals = vals+ self.check(t, vals, groups)++ def write_usage(self, t):+ """The agent-visible /run/rcb-limits/usage.json: the last sample's values (none before the first one), the+ limits, what enforcement did, and the agent's clock."""+ vals = self._usage_vals or {}+ u = {"t": round(t, 2), "measured": bool(vals)}+ u.update({k: vals.get(k) for k in ("gpu_memory_gb", "memory_gb", "processes")})+ u.update(disk_gb=self.disk_gb, enforced=self.enforce, limits=usage_limits(self.lim),+ violations=sorted(self.confirmed),+ # processes the monitor killed at once to protect the host (not violations by themselves)+ emergency_kills=len(self.emergency), last_emergency_kill=(self.emergency or [None])[-1])+ u.update(clock(t, self.clock_t0, self.timeout))+ try:+ write_json(SCOPE_BEACON + "/usage.json", u)+ except OSError:+ pass++ def seal(self):+ try:+ self.oomw.scan() # the counters once more, whatever the watch thread is doing+ except Exception:+ pass+ # The record ends here, for OOM kills as for the samples: what happens to a sidecar in the collect hooks that+ # follow (its replays) is the grader's to judge, from the hook's own evidence.+ self.oomw.stopped = True+ summary, samples, events = rcb_limits.load_record(REC)+ viol = rcb_limits.violations(samples, self.lim, events)+ meta = rcb_limits.read_json(os.path.join(REC, "meta.json")) or {}+ out = {+ "format": rcb_limits.FORMAT, "sealed": True, "enforce": meta.get("enforce", self.enforce),+ "started": meta.get("started"), "ended": round(now(), 2), "n_samples": len(samples),+ "scope_seen": self.scope_seen or any((s.get("scope") or {}).get("processes") for s in samples),+ "peaks": rcb_limits.peaks(samples), "violations": viol,+ "killed": sum(int(e.get("processes") or 0) for e in events if e.get("event") in ("kill", "emergency_kill")),+ "emergency_kills": sum(1 for e in events if e.get("event") == "emergency_kill"),+ "disk_baseline_gb": self.disk_base,+ "disk_partial_walks": sum(1 for e in events if e.get("event") == "disk_partial"),+ "restarts": sum(1 for e in events if e.get("event") == "restart"),+ "capabilities": meta.get("capabilities", self.caps), "limits": self.lim}+ if meta.get("switch_error") or self.switch_error:+ out["switch_error"] = meta.get("switch_error") or self.switch_error+ write_json(os.path.join(REC, "summary.json"), out)+ event("seal", violations=len(viol))+++def seal_cmd(wait):+ open(os.path.join(REC, "seal.request"), "a").close()+ path = os.path.join(REC, "summary.json")+ t_end = now() + wait+ while now() < t_end and not os.path.exists(path):+ time.sleep(0.5)+ s = rcb_limits.read_json(path)+ print(json.dumps({k: (s or {}).get(k) for k in ("sealed", "enforce", "n_samples", "peaks", "violations", "killed")}))+ return 0+++BEACON_WHY = ("this runner cannot run the resource monitor (its container runtime refuses `pid: host`): usage is not "+ "measured and the limits are not enforced; the clock is kept")+++def beacon(rounds=None):+ """`monitor.py beacon`: usage.json with the agent's clock and `"measured": false`, every tick, for a runner whose+ container runtime cannot create the monitor service (it rewrites the service to run this instead of `run`). The+ start is kept in the service's own /var/rcb-monitor/beacon.json, so a restart does not reset the clock."""+ lim = rcb_limits.read_json(LIMITS) or {}+ tick, timeout = float(lim.get("tick_sec", 5)), float(lim.get("agent_timeout_sec") or 0)+ start = now()+ try:+ os.makedirs(REC, exist_ok=True)+ st = rcb_limits.read_json(os.path.join(REC, "beacon.json")) or {}+ if isinstance(st.get("started"), (int, float)):+ start = float(st["started"])+ else:+ write_json(os.path.join(REC, "beacon.json"), {"started": round(start, 2)})+ except OSError:+ pass+ n = 0+ while rounds is None or n < rounds:+ t = now()+ u = {"t": round(t, 2), "measured": False, "why": BEACON_WHY, "enforced": 0, "limits": usage_limits(lim)}+ u.update(clock(t, start, timeout))+ try:+ write_json(SCOPE_BEACON + "/usage.json", u)+ except OSError:+ pass+ n += 1+ if rounds is None or n < rounds:+ time.sleep(tick)+ return 0+++def main(argv):+ if argv[:1] == ["beacon"]:+ return beacon()+ if argv[:1] == ["seal"]:+ wait = float(argv[argv.index("--wait") + 1]) if "--wait" in argv else 90.0+ return seal_cmd(wait)+ if argv[:1] in (["run"], []):+ no_dump()+ Monitor().run()+ return 0+ print(__doc__)+ return 2+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/rcb_limits.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/rcb_limits.pynew file mode 100644index 0000000000..3c996ca1f2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/rcb_limits.py@@ -0,0 +1,536 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The session log (robot_coding_bench #233): sanitize() also compares the agent's /app/output/rcb_session_log.jsonl with+the monitor's append-only copy of it (session_log/ in the record) and, when the agent's file is missing or is not what+was written (removed, truncated, rewritten), gives the grader the copy instead (session_log_source()); verify() adds+session_log_tampered (0/1) and session_log_from_monitor (0/1) to reward.json. Only the graders' cost fields read the log.++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ sl = read_json(os.path.join(log, SESSION_LOG_STATUS)) # sanitize()'s session-log comparison (#233)+ if isinstance(sl, dict):+ add["session_log_tampered"] = int(bool(sl.get("tampered")))+ add["session_log_from_monitor"] = int(bool(sl.get("from_monitor")))+ detail["session_log"] = sl+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ try:+ msg = session_log_source(log, max_log)+ if msg:+ done.append(msg)+ except Exception as e: # never keep the grader from running+ done.append(f"session log: not compared with the monitor's copy ({type(e).__name__}: {e})")+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++SESSION_LOG_STATUS = "session_log.json" # in /logs/verifier: what session_log_source() did, read back by verify()+++def session_log_source(log, max_log=MAX_SESSION_LOG, record=None):+ """The session log the grader reads (#233). The monitor copies what the agent's tooling appends to it, append-only,+ into its record (session_log/<segment>.jsonl; a new segment each time the file was truncated, replaced or+ rewritten). The agent's file stays when it is the copy plus at most what was appended after the last tick; else+ (removed, truncated, rewritten, or the copy has segments) the grader gets the copy: the segments' lines in order,+ in a later segment a line an earlier one already gave left out (a rewrite copies the file again). No copy (no monitor on the runner, or no log+ written): nothing changes, nothing is written. Else writes /logs/verifier/session_log.json; returns a line for the+ log, or None."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ d = os.path.join(record, "session_log")+ segs = sorted((int(n.split(".")[0]) for n in (os.listdir(d) if os.path.isdir(d) else ())+ if n.endswith(".jsonl") and n.split(".")[0].isdigit()))+ events = [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)]+ tamper = [e for e in events if e.get("event") in ("session_log_rewritten", "session_log_removed")]+ status = {"from_monitor": 0, "tampered": int(bool(tamper)), "monitor_copy": bool(segs), "events": tamper[:20]}+ msg = None+ if segs:+ copies = []+ for n in segs:+ with open(os.path.join(d, "%d.jsonl" % n), "rb") as f:+ copies.append(f.read(max_log))+ agent = None+ if os.path.isfile(log) and not os.path.islink(log):+ with open(log, "rb") as f:+ agent = f.read(max_log)+ if len(segs) == 1 and not tamper and agent is not None and agent.startswith(copies[0]):+ pass # the agent's file is what was written (and maybe a last tick more)+ else:+ given, out = {}, [] # line -> most times one earlier segment had it+ for c in copies:+ again, lines, here = dict(given), c.splitlines(True), {}+ for line in lines:+ here[line] = here.get(line, 0) + 1+ if again.get(line):+ again[line] -= 1 # the rewrite's copy of a line given before+ continue+ out.append(line)+ for line, k in here.items():+ given[line] = max(given.get(line, 0), k)+ data = b"".join(out)[:max_log]+ if os.path.lexists(log):+ os.unlink(log)+ with open(log, "wb") as f:+ f.write(data)+ status.update(from_monitor=1, tampered=1, agent_bytes=None if agent is None else len(agent),+ copy_bytes=len(data))+ msg = (f"replaced {log} with the monitor's copy ({len(data)} bytes; the agent's file was "+ + ("missing" if agent is None else f"{len(agent)} bytes, not what was written") + ")")+ if not segs and not tamper:+ return None # no copy (no monitor, or no log written): nothing to say+ logs = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ try:+ os.makedirs(logs, exist_ok=True)+ with open(os.path.join(logs, SESSION_LOG_STATUS), "w") as f:+ json.dump(status, f, indent=1)+ except OSError:+ pass+ return msg+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/selftest.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/selftest.pynew file mode 100644index 0000000000..89d553743f--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/rcb_monitor/selftest.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""What the resource monitor can measure where it runs (capabilities(), written into its record), and a self-test of+the shared violation rule and the verifier step (no containers needed; ci_checks/check-monitor.py runs it):++ python3 scripts/rcb_monitor/selftest.py+"""+import json+import os+import sys+import tempfile++HERE = os.path.dirname(os.path.abspath(__file__))+++def _rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def capabilities():+ """Facts the verifier and the results footnotes need: does the monitor see the host's processes (pid: host), the+ host's cgroup tree (cgroup: host; per-container memory and OOM counts), """+ c = {}+ try:+ pids = [d for d in os.listdir("/proc") if d.isdigit()]+ except OSError:+ pids = []+ try:+ c["pid_host"] = int(len(pids) > 1 and open("/proc/1/comm").read().strip() != open("/proc/self/comm").read().strip())+ except OSError:+ c["pid_host"] = 0+ own = ""+ try:+ own = [ln[3:].strip() for ln in open("/proc/self/cgroup") if ln.startswith("0::")][0]+ except (OSError, IndexError):+ pass+ c["cgroup_v2"] = int(os.path.exists("/sys/fs/cgroup/cgroup.controllers"))+ c["cgroup_host"] = int(bool(own) and own != "/" and os.path.isdir("/sys/fs/cgroup" + own))+ return c+++# --------------------------------------------------------------------------------------------------- self-test+def _check(cond, msg):+ if not cond:+ raise AssertionError(msg)+++def test_rule():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ tick = 5.0+ over = [(i * tick, 10.0 if 20 <= i < 33 else 1.0) for i in range(60)] # 65 s over the limit+ _check(abs(r.sustained(over, 5, 60, 120, tick) - 160.0) < 0.01, "65 s over: confirmed at 60 s")+ short = [(i * tick, 10.0 if 20 <= i < 31 else 1.0) for i in range(60)] # 55 s+ _check(r.sustained(short, 5, 60, 120, tick) is None, "55 s over: no violation")+ flap = [(i * tick, 10.0 if (i % 2 == 0 and i >= 20) else 1.0) for i in range(80)] # half the time, never 60 s straight+ _check(r.sustained(flap, 5, 60, 120, tick) is not None, "59 s on / 1 s off does not escape: 60 s in any 120 s")+ sparse = [(i * 25.0, 10.0) for i in range(4)] # 25 s gaps count 15 s each+ _check(r.sustained(sparse, 5, 60, 120, tick) is None, "gaps never count against the agent")+ _check(r.sustained(over, 0, 60, 120, tick) is None, "limit 0 = not limited")+ disk = [(0, 1.0), (60, 30.0), (120, 1.0), (180, 30.0), (240, 31.0)]+ _check(r.consecutive(disk, 20) == 240, "disk: two consecutive measurements over")+++def test_verify():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ lim = {"max_gpu_memory_gb": 4.0, "max_memory_gb": 8.0, "max_processes": 100, "max_disk_gb": 10.0,+ "sustain_sec": 60, "window_sec": 120, "tick_sec": 5}+ for enforce, gpu, want in ((1, 6.0, "fail"), (0, 6.0, "observe"), (1, 3.0, "pass")):+ with tempfile.TemporaryDirectory() as d:+ rec, tests, logs = (os.path.join(d, x) for x in ("rec", "tests", "logs"))+ for x in (rec, tests, logs):+ os.makedirs(x)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ with open(os.path.join(rec, "samples.jsonl"), "w") as f:+ for i in range(40):+ f.write(json.dumps({"t": 1000 + 5 * i, "scope": {"gpu_memory_gb": gpu if i > 5 else 0.5,+ "memory_gb": 2.0, "processes": 10,+ "disk_gb": 0.1 if i % 12 == 0 else None}}) + "\n")+ open(os.path.join(rec, "events.jsonl"), "w").close()+ json.dump({"format": r.FORMAT, "sealed": True, "enforce": enforce, "scope_seen": True},+ open(os.path.join(rec, "summary.json"), "w"))+ json.dump({"success": 1, "infra_error": 0}, open(os.path.join(logs, "reward.json"), "w"))+ open(os.path.join(logs, "reward.txt"), "w").write("1\n")+ import shutil+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=rec, RCB_VERIFIER_LOGS=logs)+ import subprocess+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ txt = open(os.path.join(logs, "reward.txt")).read().strip()+ if want == "fail":+ _check(out["success"] == 0 and out["resource_limit_exceeded"] == 1 and out["success_before_limits"] == 1+ and txt == "0" and out["over_gpu_memory_gb"] == 1, f"enforced violation fails: {out}")+ elif want == "observe":+ _check(out["success"] == 1 and out["limits_violation_observed"] == 1 and txt == "1"+ and "resource_limit_exceeded" not in out, f"observe mode only records: {out}")+ else:+ _check(out["success"] == 1 and out["limits_violation_observed"] == 0 and out["resource_monitor_missing"] == 0,+ f"within limits: {out}")+ _check(out["peak_gpu_memory_gb"] == gpu, "peak recorded")+ # no record at all: enforced = infra, observed = flagged only+ for enforce in (1, 0):+ with tempfile.TemporaryDirectory() as d:+ logs, tests = os.path.join(d, "logs"), os.path.join(d, "tests")+ os.makedirs(logs)+ os.makedirs(tests)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ json.dump({"success": 1}, open(os.path.join(logs, "reward.json"), "w"))+ import shutil+ import subprocess+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=os.path.join(d, "none"), RCB_VERIFIER_LOGS=logs,+ RCB_LIMITS_ENFORCE=str(enforce))+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ _check(out["resource_monitor_missing"] == 1 and out.get("infra_error", 0) == enforce,+ f"missing record (enforce={enforce}): {out}")+++def main():+ if sys.argv[1:2] == ["caps"]:+ print(json.dumps(capabilities()))+ return 0+ test_rule()+ test_verify()+ print("rcb_monitor selftest: ok")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/__init__.pynew file mode 100644index 0000000000..eeacb3c0af--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/__init__.py@@ -0,0 +1,69 @@+"""RoboOlympics robot resource library (bodies/README.md, "机器人资源库"): shared robots, the attachments on their+common wrist mount, the one trusted limit / servo path, and optional control libraries. Not a part of the framework+(players / sports / core / tools): a library the sports draw from; core never imports it.++ from bodies import load_body, assemble+ B = load_body("wheeled_humanoid") # a robot: model, joints, actuators, real limits (body.toml)+ cfg = assemble("wheeled_humanoid", "paddle", controllers=["wholebody"]) # robot + attachment + controllers+ cfg.id # "wheeled_humanoid@wh-3+paddle+wholebody#<hash>"++A sport declares in sport.toml++ [body]+ name = "wheeled_humanoid"+ hand = "paddle"+ controllers = ["wholebody"] # optional: bodies/control/<name>.py the sport imports++tools/generate.py then copies the robot (without its fine meshes and provenance tools), the attachments, the limit+/ servo path and the declared control libraries into the task's simulator directory, with configuration.json (the+assembled configuration's id and hash). The fixed-base arms (franka_panda, franka_fr3, kuka_iiwa14: limits only, each+sport's scene carries the arm's MJCF) are declared with [arm] body instead; the limits-only legged robots (booster_t1:+the sport's scene carries the model and its walking policy; bodies/servo.py Actuators + WalkCommand) with [legs] body.+"""+from __future__ import annotations++import importlib+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+# library robots with a model, a rig and a servo (load_body); "status" in each body.toml says what they may be used for+BODIES = ("wheeled_humanoid", "unitree_g1", "unitree_h1", "galaxea_r1pro", "tianji_marvin_pro", "abb_irb1100")+ARMS = ("franka_panda", "franka_fr3", "kuka_iiwa14") # limits-only entries (bodies/limits.py)+LEGS = ("booster_t1",) # limits-only legged entries (bodies/servo.py Actuators + WalkCommand; the+ # sport's scene carries the model and the walking policy): sport.toml [legs] body+PLANAR = ("ssl_robot",) # planar-base robots with their own interface (MjSpec mount, rig with kick /+ # dribble: bodies/ssl_robot/README.md); load_body works, the arm checks do not apply+ROBOTS = BODIES + ARMS + LEGS + PLANAR+CONTROLLERS = ("wholebody", "arbiter", "kinematics") # bodies/control/: optional, a sport imports them+++def _path():+ if str(HERE.parent) not in sys.path:+ sys.path.insert(0, str(HERE.parent))+++def load_body(name: str):+ """A library robot (bodies/<name>/body.py load()): mount into a scene, rig, robot-only export."""+ if name not in BODIES + PLANAR:+ raise ValueError(f"unknown body {name!r}; one of {list(BODIES + PLANAR)}")+ _path()+ return importlib.import_module(f"bodies.{name}.body").load()+++def planner(name: str):+ """The whole-body planner module (bodies/control/wholebody.py), the same for every body with the wheeled+ humanoid's controlled vector (and the legged ones' planar copies)."""+ if name not in BODIES:+ raise ValueError(f"unknown body {name!r}; one of {list(BODIES)}")+ _path()+ return importlib.import_module("bodies.control.wholebody")+++def assemble(robot: str, attachment: str | None = None, other_attachment: str | None = None, controllers=(),+ arm: str = "right"):+ """robot + attachment(s) + declared controllers -> an assembled configuration with its own version hash+ (bodies/assembly.py)."""+ _path()+ from bodies import assembly+ return assembly.assemble(robot, attachment, other_attachment, controllers, arm)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/assembly.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/assembly.pynew file mode 100644index 0000000000..dfa297859d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/assembly.py@@ -0,0 +1,132 @@+"""Assembled configurations (bodies/README.md "三个概念"): a robot of the library + its attachment(s) (bodies/hands)++ the control libraries a sport declares = one configuration with its own version hash.++The robot's revision (body.toml) says when the robot changed; the configuration's hash says when anything that+decides how the assembled robot behaves changed: the robot's model, meshes, declarations and code, the attachment's+declaration and model, the declared control libraries, and the shared limit / servo path. Tasks and results record+the configuration id, so a result names exactly the robot it was played with.++ from bodies import assemble+ cfg = assemble("unitree_g1", "paddle", controllers=["wholebody"])+ cfg.id # "unitree_g1@g1-2+paddle+wholebody#3f9c0a1b2c4d"+ cfg.hash # the full sha256+ cfg.record() # a dict for configuration.json, a sport's /spec or its results+ cfg.write(sim_dir / "bodies" / "configuration.json")++ from bodies.assembly import recorded+ recorded(sim_dir) # what tools/generate.py wrote into a task's simulator directory (None if nothing)++Stable: the hash is a sha256 over a canonical JSON of the inputs and the sha256 of every file that takes part+(read as bytes; no timestamps, no paths outside bodies/), so the same files give the same hash in a checkout and in a+task's simulator directory (tools/sportlib.copy_body copies exactly these files).+"""+from __future__ import annotations++import hashlib+import json+import tomllib+from dataclasses import dataclass, field+from pathlib import Path++HERE = Path(__file__).resolve().parent+SHARED = ("limits.py", "servo.py", "selfcollision.py") # the trusted limit / servo path, self-collision+ROBOT_FILES = ("body.toml", "model.xml", "*.py", "meshes/*", "meshes_25k/*", "policy/*.npz") # behaviour, players' images+FILE_NAME = "configuration.json"+++def _sha(p: Path) -> str:+ return hashlib.sha256(p.read_bytes()).hexdigest()+++def robot_files(robot: str, root: Path = HERE) -> list[Path]:+ """The files of bodies/<robot>/ that decide its behaviour (not the fine meshes, provenance tools, licences)."""+ d = root / robot+ out = set()+ for pat in ROBOT_FILES:+ out.update(p for p in d.glob(pat) if p.is_file() and "__pycache__" not in p.parts)+ return sorted(out)+++@dataclass+class Configuration:+ robot: str+ revision: str+ title: str+ status: str+ attachment: str | None+ other_attachment: str | None+ arm: str+ controllers: list+ files: dict = field(default_factory=dict) # path relative to bodies/ -> sha256+ hash: str = ""++ @property+ def id(self) -> str:+ parts = [f"{self.robot}@{self.revision}", self.attachment or "bare"]+ if self.other_attachment:+ parts.append(f"{self.other_attachment}(other)")+ parts += list(self.controllers)+ return "+".join(parts) + "#" + self.hash[:12]++ def record(self) -> dict:+ return dict(id=self.id, hash=self.hash, robot=self.robot, revision=self.revision, title=self.title,+ status=self.status, attachment=self.attachment, other_attachment=self.other_attachment,+ arm=self.arm, controllers=list(self.controllers), files=dict(self.files))++ def write(self, path) -> Path:+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(self.record(), indent=1, sort_keys=True) + "\n")+ return path+++def assemble(robot: str, attachment: str | None = None, other_attachment: str | None = None, controllers=(),+ arm: str = "right", root: Path | str | None = None) -> Configuration:+ """robot + attachment(s) + declared controllers -> a Configuration with its hash. root: the bodies/ directory+ (default: this one; a task's sim/bodies works the same)."""+ root = Path(root or HERE)+ decl = tomllib.loads((root / robot / "body.toml").read_text())+ b = decl["body"]+ files = {}+ for p in robot_files(robot, root):+ files[str(p.relative_to(root))] = _sha(p)+ for f in SHARED:+ if (root / f).exists():+ files[f] = _sha(root / f)+ hand_decl = {}+ for h in (attachment, other_attachment):+ if h:+ hands = tomllib.loads((root / "hands" / "hands.toml").read_text())+ if h not in hands:+ raise ValueError(f"unknown attachment {h!r}; one of {sorted(hands)}")+ hand_decl[h] = hands[h]+ files[f"hands/{hands[h]['file']}"] = _sha(root / "hands" / hands[h]["file"])+ controllers = sorted(set(controllers))+ for c in controllers:+ p = root / "control" / f"{c}.py"+ if not p.exists():+ raise ValueError(f"unknown controller {c!r} (bodies/control/{c}.py)")+ files[f"control/{c}.py"] = _sha(p)+ if b.get("kind") == "arm" and (attachment or other_attachment):+ raise ValueError(f"{robot} is a limits-only arm entry: its sport's scene carries the tool")+ canon = dict(robot=robot, revision=b["revision"], attachment=attachment, other_attachment=other_attachment,+ arm=arm, controllers=controllers, attachments=hand_decl, files=dict(sorted(files.items())))+ h = hashlib.sha256(json.dumps(canon, sort_keys=True, separators=(",", ":")).encode()).hexdigest()+ return Configuration(robot, b["revision"], b["title"], b.get("status", "library"), attachment, other_attachment,+ arm, controllers, dict(sorted(files.items())), h)+++def recorded(sim_dir) -> dict | None:+ """The configuration a task's simulator directory was generated with (sim/bodies/configuration.json), or None."""+ p = Path(sim_dir) / "bodies" / FILE_NAME+ return json.loads(p.read_text()) if p.exists() else None+++def verify(sim_dir) -> tuple[bool, str]:+ """Recompute the recorded configuration from the files in sim_dir/bodies: (same hash?, the id)."""+ rec = recorded(sim_dir)+ if rec is None:+ return False, "no configuration.json"+ cfg = assemble(rec["robot"], rec["attachment"], rec["other_attachment"], rec["controllers"], rec["arm"],+ root=Path(sim_dir) / "bodies")+ return cfg.hash == rec["hash"], cfg.iddiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/configuration.json b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/configuration.jsonnew file mode 100644index 0000000000..03f0eb6188--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/configuration.json@@ -0,0 +1,99 @@+{+ "arm": "right",+ "attachment": "epee",+ "controllers": [],+ "files": {+ "hands/epee.xml": "b5dde39a11acd81eac48b0f11f42bde1c88e8ddcf8c6951cb4f5ba1ed3f3f500",+ "limits.py": "3c1c255c17edcd97e2a9f817632073c72b5e2255b5c9cea92af51c2418ff4fe2",+ "selfcollision.py": "92634c19d3e7cb005f79b7ffe5af9a119bda1538a4ceab1cd32927029277c7c2",+ "servo.py": "8fda6665e86e2d214e712013547b0e9235e7f585b6372f0a544eb23902e4613e",+ "unitree_g1/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",+ "unitree_g1/agile.py": "34f2ba002a957f4a833479c8aeb0f161f3b00b019d0361ca58c5ffa7c42275a8",+ "unitree_g1/body.py": "8b78d0635a096f33b8251a1112cb83d68061d1c312bc1e3e500c1bf142a0cb0d",+ "unitree_g1/body.toml": "2325acc68a7ac0a1e622726eb5d1a7769a7d316fb284ac3f38247d6517ea5789",+ "unitree_g1/falcon.py": "54766d6d95c115b6123b57ff2e47c400b500d83c7e4f6a3e3e5c87313ac5a392",+ "unitree_g1/kick.py": "c664f7b536ac81667426decde49f937f1068d775c5fb7605a812cc0e95d5e110",+ "unitree_g1/meshes/head_link.stl": "7f521c99e468cda5381b88de4ec05dfee599d53659371a97748f611eb711ddb1",+ "unitree_g1/meshes/left_ankle_pitch_link.stl": "1dca4a92c90edce064bd358a697a09078d456b97ba71c9753ce0c89ce5e95e20",+ "unitree_g1/meshes/left_ankle_roll_link.stl": "daeb41423a730353c32a663a25081249adab1e0d2b1f75680032427286c98d47",+ "unitree_g1/meshes/left_elbow_link.stl": "11b90a65c436cc6e29732665e69b262770550f85495ef818a31c9843a48e9453",+ "unitree_g1/meshes/left_hip_pitch_link.stl": "23b44cf14be710741889451e7ca22e57df9c80d74aec0ea6945827962bd807b8",+ "unitree_g1/meshes/left_hip_roll_link.stl": "169e1d38fde7752d66ba0a604d83dfb1c6bd7cb75669f380fae03fe01184d4f5",+ "unitree_g1/meshes/left_hip_yaw_link.stl": "cc6d89db6683d52c02b859b92601b3d98a7d46883c0d16a327811d976fd8a827",+ "unitree_g1/meshes/left_knee_link.stl": "7d566d51ea3fe5dde90470f36cd9809bbc2edd36aecc9b119512bfb2d4495893",+ "unitree_g1/meshes/left_rubber_hand.stl": "be14d2b3e72e59094e119b2d0cba50f2b780ce74ab351c90282afe29061b80fb",+ "unitree_g1/meshes/left_shoulder_pitch_link.stl": "d671bd2a7831a8b4c9d5c5487676ca5d94d84f5cb86026acfcd833f549197bc9",+ "unitree_g1/meshes/left_shoulder_roll_link.stl": "8f491a0fbe1f34947de1e16c81658bd26dfe0f2958c59ae83829192044672131",+ "unitree_g1/meshes/left_shoulder_yaw_link.stl": "8151d536bc0bbd6d38277a047e0109649aa174b17b15fc2878253d47d2a0d548",+ "unitree_g1/meshes/left_wrist_pitch_link.stl": "b57e59744483c9b389373e326a9e9597047b32e78ed6df7d8c7a6c3a96105701",+ "unitree_g1/meshes/left_wrist_roll_link.stl": "5d2e89cab6c5583269179cd573a7b8e09a7a9eec86ad842f680df8ee9c8f7fc5",+ "unitree_g1/meshes/left_wrist_yaw_link.stl": "5fa6603d707585f94259ad63d0a9ae0ebc430116443bf6c491b98e411a88436b",+ "unitree_g1/meshes/logo_link.stl": "033edba23cd6314aac5a9710c81d4cfc0b77f28b9bdbafade3fdec7bfeb1438b",+ "unitree_g1/meshes/pelvis.stl": "7fc122ba00b406a79014370b9a5e6d81cb75e12def7faf5a313f6ea55f1cb371",+ "unitree_g1/meshes/pelvis_contour_link.stl": "86838d78054520c8a7987632cb8fc102d06e310ae04a0c211a96fc1173f8f33f",+ "unitree_g1/meshes/right_ankle_pitch_link.stl": "5dba280683a0fe546b75cd17677b35e128098947dc7df15240fec645622b064b",+ "unitree_g1/meshes/right_ankle_roll_link.stl": "1f9b09689332ae170e309a91dcb28b685cac310c897a3bb689d8bc85a8050f4a",+ "unitree_g1/meshes/right_elbow_link.stl": "fdb1d4142e9a6cc64f4b6602538dde3310eda04589899f5f534a90922a574732",+ "unitree_g1/meshes/right_hip_pitch_link.stl": "0073660201fd7db9f04153f27af02ed50f48393e32c6168fc7eadeb404bdc053",+ "unitree_g1/meshes/right_hip_roll_link.stl": "35c50fe31dd2c87b4dd249c3d7706039525b760e1068fcc2b28737f771289661",+ "unitree_g1/meshes/right_hip_yaw_link.stl": "8971d1918c578ab17df99f2dccc1c8679f1e00f7e46ae39bb63c984aea321aad",+ "unitree_g1/meshes/right_knee_link.stl": "53dd565d24d70730499f7a41087fd46c54413e5dc3b30defb481e6d688550aec",+ "unitree_g1/meshes/right_rubber_hand.stl": "8916bd1b87d7abfb7f9ce3bbbae1223dd597b9df7e7590ed64e373d579c43f6e",+ "unitree_g1/meshes/right_shoulder_pitch_link.stl": "874e9386b11996653323b0a27812de93c8604b5cd26c951e2db5c94fc7ed878c",+ "unitree_g1/meshes/right_shoulder_roll_link.stl": "50de6c85248dbf89c64c3c9ff9c97b6a4203cf9811cabd81e0a93cdef107cdaf",+ "unitree_g1/meshes/right_shoulder_yaw_link.stl": "b46b13c35fe1e8aedb600ea46ea5e6703a9988fd8a6b5a065a3a6fb5436a7fb7",+ "unitree_g1/meshes/right_wrist_pitch_link.stl": "0a453978ebf4624d6962f0908768be89182c108d3762499ff0f0a40934db7911",+ "unitree_g1/meshes/right_wrist_roll_link.stl": "1a8f1274d785cce6bd40035b46d7206256bda51cb8c0d16ac75a4feb7da126ea",+ "unitree_g1/meshes/right_wrist_yaw_link.stl": "e75956daf0cb161e28815ff0f3f04d6a5e5cb27f2516b61ae06973c02f9d4b37",+ "unitree_g1/meshes/torso_link_rev_1_0.stl": "49d4916cac621b3cc03bddf4a4095eae32c318ea5075ecb275c7f1c5fddfe2f4",+ "unitree_g1/meshes/waist_roll_link_rev_1_0.stl": "f8eb2b56bb080b8bd89778d931d7f060d0106acc3ea5a662a2f5ef1313d10814",+ "unitree_g1/meshes/waist_yaw_link_rev_1_0.stl": "6cda482220cf900e8eb72ac08499c0c0f49ff020e3cbe6176293ea0fd0815e4f",+ "unitree_g1/meshes_25k/head_link.stl": "b0b7459e77a9b361cbd3b42d75cdf8f54280e5771ae6655890920a15048d31e0",+ "unitree_g1/meshes_25k/left_ankle_pitch_link.stl": "d61e414cbeb7f87800c8216959a5d4f34dea746fcdf390f6920f7abe7f473d82",+ "unitree_g1/meshes_25k/left_ankle_roll_link.stl": "ac56add2f6f6c4cd2b3b33274d8b8a10b49acceed658cffc6b36cb4a317923ea",+ "unitree_g1/meshes_25k/left_elbow_link.stl": "6043e71584dec9e8832f1e1e0e061074ad868ed4cf83c63a2684a47650547b32",+ "unitree_g1/meshes_25k/left_hip_pitch_link.stl": "7c5fe35b1d28fad41dbe2865dd6a395255ab54911e5702ea11553635b808261e",+ "unitree_g1/meshes_25k/left_hip_roll_link.stl": "7e0f0ff6a935a6bdf79dd79b7cd206b6225ef1d813aa81bad3b1e8627fae4f24",+ "unitree_g1/meshes_25k/left_hip_yaw_link.stl": "cf13b4e40a0f06ee8f3cf89e5e2a962223912251dd8707a5f8474e66b3df7e5c",+ "unitree_g1/meshes_25k/left_knee_link.stl": "78fa5f7cfea0b075e32de93ee5303cfcb3fe30b21cbb9422d9d3e307ef513530",+ "unitree_g1/meshes_25k/left_rubber_hand.stl": "03a87a3e22dddf9d77fb7ce8189ead6629e90cde3ad8479acf4480afd15f3926",+ "unitree_g1/meshes_25k/left_shoulder_pitch_link.stl": "3163bd3e1e473e4fa48900a74c844a5647b46f6c6ae30e94a1d51183d026cc75",+ "unitree_g1/meshes_25k/left_shoulder_roll_link.stl": "8fe40e7a3c4c62735346e16900e1bf3de7e9373273bb881f232c4a0be7ca470d",+ "unitree_g1/meshes_25k/left_shoulder_yaw_link.stl": "2ef7a79abb015d2fefed54ced7c46b7949c3c6dcb774b6500b2f59522a7ebd52",+ "unitree_g1/meshes_25k/left_wrist_pitch_link.stl": "50baada401939b9ee9e8cd03988f1ad800727394491eef6f4dd88a136f8f1f12",+ "unitree_g1/meshes_25k/left_wrist_roll_link.stl": "233ba263c0ad165460af24c49172d112c476333c64c23cc65f4eec130f75defc",+ "unitree_g1/meshes_25k/left_wrist_yaw_link.stl": "354af14f646a5a29a41142ed1436e9dbda1903755ebe96030d4b518cde989445",+ "unitree_g1/meshes_25k/lod.json": "b7fb97ab3499fa28076a572c26b3125dc3efc069d16b64a756ea9485b4429f3a",+ "unitree_g1/meshes_25k/logo_link.stl": "555ec8563662a7d9dc8c02d731a9657fa77194858a3a252f444aa946aa5f339e",+ "unitree_g1/meshes_25k/pelvis.stl": "a5e7b076649f4899a0fbfcf7e1ee0368cf84fbb2e68bab695398ab6c1ca77d99",+ "unitree_g1/meshes_25k/pelvis_contour_link.stl": "d016ed38115363429e2740aaa047dbd1d4e49fe796f24232099ade2295adcaa0",+ "unitree_g1/meshes_25k/right_ankle_pitch_link.stl": "0c5c9eca53d7370207426be70e45032afcb9f41be13dce246f259e5252e0c6b7",+ "unitree_g1/meshes_25k/right_ankle_roll_link.stl": "e3ac204d29d5f91e97e1cef60691d5edb1fdda026b954e2169c914ab541cffd3",+ "unitree_g1/meshes_25k/right_elbow_link.stl": "233ae8c8f2f55588be7cc6d17cfaa66f9b5c37d0eaf32dbdee3807542478244d",+ "unitree_g1/meshes_25k/right_hip_pitch_link.stl": "9b744118b6b7ffe69d7982ce4579eb20b35a9496b8a13d6aa6ab3145f1163e34",+ "unitree_g1/meshes_25k/right_hip_roll_link.stl": "4c9c886c2977ba0881e87a3ed9712a90a149e5e996cb7a47b7c263926fa99856",+ "unitree_g1/meshes_25k/right_hip_yaw_link.stl": "79954979142fddcf9f234c3cf8b946529ac2b87bc18295b762bf305885e80051",+ "unitree_g1/meshes_25k/right_knee_link.stl": "807714c0d515988cbc17ee929e91e4538e3ce16d867d11fd0b07b2153d5dc210",+ "unitree_g1/meshes_25k/right_rubber_hand.stl": "6ba8ebbdf198df47a175a0fc8c7c14597ebb7e2b6bfeae81f538baf6452aa03f",+ "unitree_g1/meshes_25k/right_shoulder_pitch_link.stl": "c0ccf9540f9cbde63165983e7b62d9aa58ef38e8c552d0e3fcff75f7fec5d715",+ "unitree_g1/meshes_25k/right_shoulder_roll_link.stl": "e5787ae15464c086f4542b29c2dab43f5bd528c5f3ee56f2812545fe5e519bdf",+ "unitree_g1/meshes_25k/right_shoulder_yaw_link.stl": "f4a044687ef796f79e286a3bad4dc2c80be65b212132f938e3582a3ca268e399",+ "unitree_g1/meshes_25k/right_wrist_pitch_link.stl": "226f48f17024005dccaa4f3d3ad5f7e8e16bc357a1aba87de173b20cc6ce6d82",+ "unitree_g1/meshes_25k/right_wrist_roll_link.stl": "fec3af45b3b66aa16bf046cb320f72d0c9933dfed6266e253d78f9223ae925c9",+ "unitree_g1/meshes_25k/right_wrist_yaw_link.stl": "b1f689265c15a16c51cd48cbcae54485486a95596de623b8d13b003456295200",+ "unitree_g1/meshes_25k/torso_link_rev_1_0.stl": "3edf21bb662f94969e70da9a8688851c11cc7a5539ffd7548a2fe0caf16040f7",+ "unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stl": "8d994abdb0d933c51fa1e70f3f409b68cb505f4b4fe230f9e52267e96102ef51",+ "unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stl": "8cc0d812b24b8ce39eb563e74e90570415c4016242a290a557276a5afe2c3284",+ "unitree_g1/model.xml": "00aa6a6949c5e694c153985a9e7298064058864021f7ce9cd490caad0894e33c",+ "unitree_g1/policy/agile_g1_velocity_height.npz": "e4b2c05ed1cfce8c4b679fabdc7b4368f4e3022389a3c494adf07d1294eda4ee",+ "unitree_g1/policy/falcon_g1_29dof.npz": "b9e97b9a4d35fc4be1bbba801890246fec659677b78e8b1ce86559e4391af8de",+ "unitree_g1/policy/motion.npz": "d7d7ca64bdc0ca23de845b3cbfa660ad18012b82c674f23aa4e20a2fa803e89d"+ },+ "hash": "972dc62dacadb7d08fe2271f846d803177d50d674afdc6d73f2630e92353360c",+ "id": "unitree_g1@g1-4+epee#972dc62dacad",+ "other_attachment": null,+ "revision": "g1-4",+ "robot": "unitree_g1",+ "status": "library",+ "title": "legged humanoid (Unitree G1, 29 DOF)"+}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/contacts.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/contacts.pynew file mode 100644index 0000000000..caa6d1c1d2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/contacts.py@@ -0,0 +1,100 @@+"""Contacts between robots (construction step 2, physical consistency: "机器人之间有接触"). The library's robots never+touch each other or a second robot: their collision geoms are contype 4 / conaffinity 0 (bodies/selfcollision.py; each+robot's own parts touch through its explicit self-collision pairs), and a hand's contact geoms (contype 1 /+conaffinity 1) touch the world, a ball and each other. A sport whose robots meet (fencing, basketball, soccer) turns+their contacts on here, on the compiled model:++ from bodies import contacts+ m = mujoco.MjModel.from_xml_string(scene)+ info = contacts.between(m, ["A_", "B_"]) # robot prefixes (as mounted); after compiling, before stepping++Robot k gets two bits above the sports' own (BASE and up, two per robot): its body bit on every collision geom of+its body and hand (the library's contype 4 geoms and the hand's), its tool bit on its hand's contact geoms (the blade,+the racket's strings, ...). Each robot's geoms then touch every other robot's body and tools; a robot never touches+itself through these bits (its self-collision stays with its pairs); everything the geoms touched before they still+touch (the bits are added, none removed). Geoms with contype 0 and conaffinity 0 (drawings) are left alone, and so+are geoms whose names match `skip` (sensing volumes such as the G1's kick strike boxes, contype 8).++MuJoCo's broad phase filters body pairs by body_contype / body_conaffinity, which the compiler sets from the bodies'+geoms (the OR of their bits): changing a geom's bits after compiling is not enough, so the bodies' bits are recomputed+here (without it the robots' bodies are still filtered out and they still pass through each other; found in the+fencing and basketball screenings, 2026-10-11).+"""+from __future__ import annotations++import re++BASE = 16 # the first bit used here; bits 0-15 stay the sports' and the library's (1, 4, 8, ...)+MAX_ROBOTS = (31 - BASE) // 2 # contype is a signed 32-bit int+++def bits(k: int) -> tuple[int, int]:+ """(body bit, tool bit) of the k-th robot."""+ if not 0 <= k < MAX_ROBOTS:+ raise ValueError(f"at most {MAX_ROBOTS} robots")+ return 1 << (BASE + 2 * k), 1 << (BASE + 2 * k + 1)+++def _robot_geoms(m, prefix: str) -> list[int]:+ import mujoco as mj+ out = []+ for g in range(m.ngeom):+ b = mj.mj_id2name(m, mj.mjtObj.mjOBJ_BODY, int(m.geom_bodyid[g])) or ""+ if b.startswith(prefix) and (m.geom_contype[g] or m.geom_conaffinity[g]):+ out.append(g)+ return out+++def between(m, prefixes, skip: str = r"_strike$") -> dict:+ """Turn on the contacts between the robots mounted with these prefixes (and between each robot and the others'+ tools) on the compiled model m. Returns {prefix: {body_bit, tool_bit, geoms, tools}}."""+ import mujoco as mj+ import numpy as np+ prefixes = list(prefixes)+ if len(set(prefixes)) != len(prefixes):+ raise ValueError("duplicate prefixes")+ skip_re = re.compile(skip) if skip else None+ info, sets = {}, {}+ for k, p in enumerate(prefixes):+ body_bit, tool_bit = bits(k)+ gs = []+ for g in _robot_geoms(m, p):+ name = mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, g) or ""+ if skip_re is not None and skip_re.search(name):+ continue+ gs.append(g)+ tools = [g for g in gs if (mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, g) or "").startswith(p + "hand_")+ and int(m.geom_contype[g]) & 1] # the hand's contact geoms (body.py: "contact" in hands.toml)+ sets[p] = (gs, tools)+ info[p] = dict(body_bit=body_bit, tool_bit=tool_bit, geoms=len(gs), tools=len(tools))+ every_body = sum(bits(k)[0] for k in range(len(prefixes)))+ every_tool = sum(bits(k)[1] for k in range(len(prefixes)))+ touched = set()+ for k, p in enumerate(prefixes):+ body_bit, tool_bit = bits(k)+ gs, tools = sets[p]+ for g in gs:+ m.geom_contype[g] |= body_bit+ m.geom_conaffinity[g] |= (every_body & ~body_bit) | (every_tool & ~tool_bit)+ touched.add(int(m.geom_bodyid[g]))+ for g in tools:+ m.geom_contype[g] |= tool_bit+ for b in touched: # the broad phase's body filter (see the module docstring)+ sel = m.geom_bodyid == b+ m.body_contype[b] = int(np.bitwise_or.reduce(m.geom_contype[sel]))+ m.body_conaffinity[b] = int(np.bitwise_or.reduce(m.geom_conaffinity[sel]))+ return info+++def contacts_between(m, d, prefix_a: str, prefix_b: str) -> list[tuple[str, str]]:+ """The active contacts between two robots' geoms (names), for checks and records."""+ import mujoco as mj+ out = []+ for c in d.contact[:d.ncon]:+ n1 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, int(c.geom1)) or ""+ n2 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, int(c.geom2)) or ""+ b1 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_BODY, int(m.geom_bodyid[c.geom1])) or ""+ b2 = mj.mj_id2name(m, mj.mjtObj.mjOBJ_BODY, int(m.geom_bodyid[c.geom2])) or ""+ if (b1.startswith(prefix_a) and b2.startswith(prefix_b)) or (b1.startswith(prefix_b) and b2.startswith(prefix_a)):+ out.append((n1, n2))+ return outdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/board.xml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/board.xmlnew file mode 100644index 0000000000..7a08a84359--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/board.xml@@ -0,0 +1,10 @@+<mujoco model="hand_board">+ <!-- Draft: a flat board hand for volleyball (passing and setting surface), normal = local +x. -->+ <worldbody>+ <body name="hand">+ <geom name="wrist" type="cylinder" fromto="0 0 0 0 0 0.04" size="0.035" mass="0.10" rgba="0.2 0.2 0.22 1" group="2"/>+ <geom name="board" type="box" pos="0 0 0.15" size="0.012 0.11 0.15" mass="0.35" rgba="0.95 0.95 0.97 1" group="2"/>+ <site name="center" pos="0.012 0 0.15" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/epee.xml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/epee.xmlnew file mode 100644index 0000000000..a27d76d0df--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/epee.xml@@ -0,0 +1,22 @@+<mujoco model="hand_epee">+ <!-- An epee (FIE Material Rules, August 2026: m.14 under 770 g ready for use, no balance rule; m.16.3 blade at most+ 90 cm; m.17.1 guard through a 13.5 cm gauge). Blade along +z from the grip at the mount.+ Mass (2026-10-11, from Leon Paul's catalogue, leonpaulusa.com: FIE maraging blades 150-183 g at 89-89.5 cm,+ electric guards 86-133 g at 13.3 cm, grips 42-62 g, French pommels up to 200 g; "an epee made with all standard+ parts and a traditional blade weighs 454 g"): grip, pommel and nut 0.14 kg (centre 0.05 m), guard 0.13 kg (a+ disc at 0.105 m), blade with its wire 0.175 kg (tapered: centre of mass 35 % along it, 0.425 m), point 0.01 kg+ (1.01 m): 0.455 kg, centre of mass 0.231 m from the mount (12 cm in front of the guard). The inertial below+ carries it (inertia about the centre of mass: the blade and grip as rods, the guard as a disc); the geoms carry+ the shape only. Until 2026-10-11 the draft had 0.76 kg with a 0.45 kg blade (centre 0.375 m): a G1 holding it on+ guard used 76 % of its wrist pitch motor's torque, 37 % with this one (docs/screening/fencing.md, F0). -->+ <worldbody>+ <body name="hand">+ <inertial pos="0 0 0.2310" mass="0.455" diaginertia="0.03138 0.03138 0.00030"/>+ <geom name="grip" type="capsule" fromto="0 0 0 0 0 0.10" size="0.015" mass="0" rgba="0.15 0.15 0.15 1" group="2"/>+ <geom name="guard" type="cylinder" fromto="0 0 0.10 0 0 0.11" size="0.0675" mass="0" rgba="0.8 0.8 0.85 1" group="2"/>+ <geom name="blade" type="capsule" fromto="0 0 0.11 0 0 1.01" size="0.005" mass="0" rgba="0.75 0.77 0.8 1" group="2"/>+ <geom name="tip" type="sphere" pos="0 0 1.01" size="0.007" mass="0" rgba="0.2 0.2 0.2 1" group="2"/>+ <site name="tip" pos="0 0 1.017" size="0.004" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/gripper.xml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/gripper.xmlnew file mode 100644index 0000000000..cbc385ee31--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/gripper.xml@@ -0,0 +1,18 @@+<mujoco model="hand_gripper">+ <!-- Draft: a parallel gripper that holds and releases (throwing). Two fingers on slide joints, 0-4 cm each; the+ sport adds the finger actuators and the release rule. -->+ <worldbody>+ <body name="hand">+ <geom name="palm" type="box" pos="0 0 0.04" size="0.03 0.06 0.04" mass="0.40" rgba="0.2 0.2 0.22 1" group="2"/>+ <body name="finger_l_body" pos="0 0.045 0.08">+ <joint name="finger_l" type="slide" axis="0 1 0" range="0 0.04"/>+ <geom name="finger_l" type="box" pos="0 0 0.04" size="0.012 0.008 0.04" mass="0.05" rgba="0.8 0.8 0.85 1" group="2"/>+ </body>+ <body name="finger_r_body" pos="0 -0.045 0.08">+ <joint name="finger_r" type="slide" axis="0 -1 0" range="0 0.04"/>+ <geom name="finger_r" type="box" pos="0 0 0.04" size="0.012 0.008 0.04" mass="0.05" rgba="0.8 0.8 0.85 1" group="2"/>+ </body>+ <site name="center" pos="0 0 0.12" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/hands.toml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/hands.tomlnew file mode 100644index 0000000000..7b98300f28--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/hands.toml@@ -0,0 +1,59 @@+# Hands and tools on the common wrist mount (bodies/README.md). A hand is an MJCF fragment whose root body is named+# "hand"; body.py attaches it to the mount body <arm>_mount (+z away from the wrist) and prefixes every name with the+# robot's prefix + "hand_" (so geom "blade" becomes e.g. "A_hand_blade"). Collision: "contact" geoms take part in the+# sport's own contact rules (contype 1, conaffinity 1: the sport adds its <pair>s); every other hand geom is part of+# the robot (contype 4, conaffinity 0: it touches the ball and the world but never the robot itself).+# status: ready = used by a sport and tested there; draft = geometry only, the sport that needs it finishes it.+# Limits (audit 2026-10-08, G10): no hand is actuated yet (the gripper's fingers and the suction cup have no motor).+# The sport that first actuates one declares the real tool it stands for here, with sources, and drives it through+# bodies/servo.py: e.g. the Franka Hand (30-70 N continuous grip, 80 mm stroke, 50 mm/s per finger; product manual+# R50010 v1.2), the RB-Y1 gripper (0.05 m/s, rby1-sdk URDF), the R1 Pro gripper (0-100 mm stroke).++[paddle]+file = "paddle.xml"+status = "ready"+sports = ["tabletennis"]+contact = ["blade"]+site = "center" # the blade centre; face normal = the hand body's local +x+note = "the table-tennis paddle of the Franka tasks (15 x 15 x 1.5 cm blade, 0.14 m beyond the flange, 0.14 kg)"++[racket]+file = "racket.xml"+status = "draft"+sports = ["tennis", "badminton"]+contact = ["strings"]+site = "center"+note = "an oval head on a 0.40 m shaft (tennis: head 0.27 x 0.20 m, 0.30 kg; badminton scales the head and mass)"++[board]+file = "board.xml"+status = "draft"+sports = ["volleyball"]+contact = ["board"]+site = "center"+note = "a flat 0.30 x 0.22 m board (forearm pass and set surface), normal = local +x"++[suction]+file = "suction.xml"+status = "draft"+sports = ["basketball dribble"]+contact = ["cup"]+site = "center"+note = "a switchable suction cup (0.08 m radius): the sport turns the grip on and off (a weld or adhesion actuator)"++[epee]+file = "epee.xml"+status = "draft"+sports = ["fencing"]+contact = ["blade", "tip"]+site = "tip"+note = "an epee: bell guard, a 0.90 m blade along +z, the point (tip) at its end; 0.455 kg, centre of mass 0.231 m from the mount (a standard-parts epee, Leon Paul catalogue; epee.xml)"+mass_source = "Leon Paul catalogue (leonpaulusa.com, 2026-10-11): FIE maraging blade 150-183 g, electric guard 86-133 g, grip 42-62 g, pommel up to 200 g, 'an epee made with all standard parts and a traditional blade weighs 454 g'; FIE m.14 (< 770 g)"++[gripper]+file = "gripper.xml"+status = "draft"+sports = ["throwing"]+contact = ["finger_l", "finger_r"]+site = "center"+note = "a parallel gripper that holds and releases (two fingers on slide joints, 0-8 cm); the release is the sport's action"diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/paddle.xml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/paddle.xmlnew file mode 100644index 0000000000..cbf773b921--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/paddle.xml@@ -0,0 +1,13 @@+<mujoco model="hand_paddle">+ <!-- The table-tennis paddle of the Franka tasks (sports/tabletennis/sim/scene/tt_scene.xml), on the wrist mount:+ handle along +z, blade centre 0.14 m beyond the flange, face normal = local +x. -->+ <worldbody>+ <body name="hand">+ <geom name="handle" type="capsule" fromto="0 0 0 0 0 0.06" size="0.014" mass="0.05" rgba="0.55 0.35 0.2 1"+ group="2"/>+ <geom name="blade" type="box" pos="0 0 0.14" size="0.0075 0.075 0.075" mass="0.09" rgba="0.75 0.08 0.08 1"+ group="2"/>+ <site name="center" pos="0 0 0.14" size="0.005" rgba="1 1 1 1" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/racket.xml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/racket.xmlnew file mode 100644index 0000000000..a1766e8c6e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/racket.xml@@ -0,0 +1,16 @@+<mujoco model="hand_racket">+ <!-- Draft: a tennis racket on the wrist mount (shaft along +z, head centre 0.53 m beyond the flange, face normal =+ local +x). The strings are a thin box; tennis / badminton set their own contact parameters. -->+ <worldbody>+ <body name="hand">+ <geom name="grip" type="capsule" fromto="0 0 0 0 0 0.20" size="0.017" mass="0.12" rgba="0.1 0.1 0.12 1" group="2"/>+ <geom name="throat" type="capsule" fromto="0 0 0.20 0 0 0.40" size="0.010" mass="0.05" rgba="0.85 0.85 0.9 1"+ group="2"/>+ <geom name="frame" type="ellipsoid" pos="0 0 0.53" size="0.012 0.10 0.135" mass="0.10" rgba="0.85 0.85 0.9 1"+ group="2"/>+ <geom name="strings" type="box" pos="0 0 0.53" size="0.004 0.09 0.125" mass="0.03" rgba="0.9 0.9 0.6 0.6"+ group="2"/>+ <site name="center" pos="0 0 0.53" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/suction.xml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/suction.xmlnew file mode 100644index 0000000000..807d35a57b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/hands/suction.xml@@ -0,0 +1,11 @@+<mujoco model="hand_suction">+ <!-- Draft: a switchable suction hand (basketball dribble). The cup faces +z; the sport adds the grip (an adhesion+ actuator or a weld that it switches on and off) and its rules. -->+ <worldbody>+ <body name="hand">+ <geom name="body" type="cylinder" fromto="0 0 0 0 0 0.08" size="0.04" mass="0.30" rgba="0.2 0.2 0.22 1" group="2"/>+ <geom name="cup" type="cylinder" fromto="0 0 0.08 0 0 0.10" size="0.08" mass="0.10" rgba="0.95 0.45 0.1 1" group="2"/>+ <site name="center" pos="0 0 0.10" size="0.005" group="4"/>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/limits.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/limits.pynew file mode 100644index 0000000000..f11fe77e22--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/limits.py@@ -0,0 +1,445 @@+"""Real-robot arm limits for RoboOlympics bodies (numpy only; shared by every sport with a robot arm).++A body's limits are data: `bodies/<body>/body.toml [limits.arm]` holds the manufacturer's numbers with their sources+(Franka Panda / FER and Franka Research 3: Franka "Control Interface Specification and Robot Limits"; KUKA LBR iiwa 14+R820: KUKA's data sheet). This module turns them into the three things a sport's controller needs, so that no arm can+do what the real robot cannot:++ plan_line(q0, q1, lim, T) a time-optimal straight-line joint move, rest to rest, under the joint velocity,+ acceleration and jerk limits (a 7-segment jerk-limited "S-curve" on the path+ parameter, the slowest joint setting the pace); optionally stretched to T seconds+ JerkLimiter the robot's 1 kHz setpoint generator: it follows any joint reference (the 10 ms targets+ of a sport's controller, a player's low-level trajectory) and guarantees that the+ setpoint it sends to the servo never exceeds the velocity, acceleration and jerk limits+ (what libfranka's rate limiter and a real motion generator do); a reference that is+ itself within the limits is followed with a few milliseconds of lag+ TorqueRateLimiter the servo's output stage: the commanded joint torque changes by at most dtau_max per+ second and stays within tau_max (libfranka's kMaxTorqueRate and the motor torques)+ check_rows(...) a low-level trajectory (rows of joint targets at a fixed step) against the velocity and+ acceleration limits: None or the reason to refuse it+ stats(...) per-joint p50 / p95 / p99 / max of |velocity|, |acceleration|, |jerk|, |torque|,+ |torque rate| against the limits (tools/arm_limits.py measures matches with it)++What it does not change: the physics of balls, contacts and the world; the sports' own base / rail / cart limits (a+sport states those); joint ranges (the MJCF's).++Body-agnostic by design: the wheeled humanoid of the unified body (bodies/wheeled_humanoid, `Rig.apply`) can put its+targets through a JerkLimiter and its servo output through a TorqueRateLimiter in the same way, with its own+body.toml [limits.arm] (accel_rad_s2, jerk_rad_s3, torque_rate_nm_s once a source for them exists).+"""++from __future__ import annotations++import math+import tomllib+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np++HERE = Path(__file__).resolve().parent+++# ------------------------------------------------------------------------------------------------ the limits+@dataclass(frozen=True)+class ArmLimits:+ """One arm's joint limits (arrays of the arm's joints, in order) and where they come from."""++ body: str+ model: str+ range_lo: np.ndarray+ range_hi: np.ndarray+ vel: np.ndarray # rad/s+ acc: np.ndarray | None # rad/s^2 (None: the manufacturer publishes none)+ jerk: np.ndarray | None # rad/s^3+ tau: np.ndarray # N m+ dtau: np.ndarray | None # N m/s+ sources: dict = field(default_factory=dict)+ cartesian: dict = field(default_factory=dict)++ @property+ def n(self) -> int:+ return len(self.vel)++ def scaled(self, k: float) -> "ArmLimits":+ """velocity, acceleration and jerk limits times k (a sport that declares a deviation; torques unchanged)"""+ f = lambda a, p: None if a is None else a * k**p+ return ArmLimits(+ self.body,+ self.model + f" (x{k:g})",+ self.range_lo,+ self.range_hi,+ self.vel * k,+ f(self.acc, 1),+ f(self.jerk, 1),+ self.tau,+ self.dtau,+ self.sources,+ self.cartesian,+ )++ def with_jerk(self, jerk) -> "ArmLimits":+ """the same limits with these jerk limits (e.g. jerk_caps(): what the torque rate allows at a pose)"""+ return ArmLimits(+ self.body,+ self.model,+ self.range_lo,+ self.range_hi,+ self.vel,+ self.acc,+ np.asarray(jerk, float),+ self.tau,+ self.dtau,+ self.sources,+ self.cartesian,+ )++ def table(self) -> dict:+ """the limits as plain lists (for /spec and the instructions)"""+ r = lambda a, nd=4: None if a is None else [round(float(x), nd) for x in a]+ return dict(+ body=self.body,+ model=self.model,+ range_rad=[r(self.range_lo), r(self.range_hi)],+ velocity_rad_s=r(self.vel),+ acceleration_rad_s2=r(self.acc),+ jerk_rad_s3=r(self.jerk, 1),+ torque_nm=r(self.tau, 2),+ torque_rate_nm_s=r(self.dtau, 1),+ )+++def load(body: str, root: Path | str | None = None) -> ArmLimits:+ """The arm limits of bodies/<body>/body.toml (root: the directory holding bodies/<body>; default: this one)."""+ d = tomllib.loads((Path(root or HERE) / body / "body.toml").read_text())+ L = d["limits"]["arm"]+ arr = lambda k: None if L.get(k) is None else np.asarray(L[k], float)+ return ArmLimits(+ body=body,+ model=d["body"]["title"],+ range_lo=arr("range_lo_rad"),+ range_hi=arr("range_hi_rad"),+ vel=arr("speed_rad_s"),+ acc=arr("accel_rad_s2"),+ jerk=arr("jerk_rad_s3"),+ tau=arr("torque_nm"),+ dtau=arr("torque_rate_nm_s"),+ sources=dict(d.get("sources", {})),+ cartesian=dict(d.get("limits", {}).get("cartesian", {})),+ )+++# ------------------------------------------------------------------------------------------------ S-curve+def _scurve_params(D, V, A, J):+ """rest-to-rest S-curve over distance D >= 0 under V, A, J: (Tj, Ta, Tv, vp, ap): jerk time, acceleration-phase+ time, cruise time, peak velocity, peak acceleration. Time-optimal (the 7-segment profile)."""+ if D <= 0.0:+ return 0.0, 0.0, 0.0, 0.0, 0.0+ vp = V+ Ta = 2.0 * math.sqrt(V / J) if V * J < A * A else V / A + A / J+ if D < vp * Ta: # the peak velocity is not reached+ vp = (D * D * J / 4.0) ** (1.0 / 3.0)+ if vp <= A * A / J:+ Ta = 2.0 * math.sqrt(vp / J)+ else:+ vp = 0.5 * A * (-A / J + math.sqrt(A * A / (J * J) + 4.0 * D / A))+ Ta = vp / A + A / J+ Tj = min(Ta / 2.0, A / J)+ ap = J * Tj+ Tv = max(0.0, D / vp - Ta) if vp > 0 else 0.0+ return Tj, Ta, Tv, vp, ap+++def _acc_phase(t, Tj, Ta, vp, ap, J):+ """(p, v, a) at time t in the acceleration phase [0, Ta]"""+ if t <= Tj:+ return J * t**3 / 6.0, 0.5 * J * t * t, J * t+ if t <= Ta - Tj:+ u = t - Tj+ return J * Tj**3 / 6.0 + 0.5 * J * Tj * Tj * u + 0.5 * ap * u * u, 0.5 * J * Tj * Tj + ap * u, ap+ tau = max(0.0, Ta - t)+ return vp * Ta / 2.0 - (vp * tau - J * tau**3 / 6.0), vp - 0.5 * J * tau * tau, J * tau+++class Line:+ """A straight-line joint move q(t) = q0 + s(t) (q1 - q0), s an S-curve from 0 to 1 (rest to rest)."""++ def __init__(self, q0, q1, lim: ArmLimits, T: float = 0.0, margin: float = 1.0):+ self.q0, self.q1 = np.asarray(q0, float).copy(), np.asarray(q1, float).copy()+ dq = np.abs(self.q1 - self.q0)+ big = dq > 1e-12+ if not big.any():+ self.t_min = self.T = 0.0+ self.p = (0.0, 0.0, 0.0, 0.0, 0.0)+ self.V = self.A = self.J = 1.0+ self.k = 1.0+ return+ acc = lim.acc if lim.acc is not None else np.full(lim.n, np.inf)+ jerk = lim.jerk if lim.jerk is not None else np.full(lim.n, np.inf)+ self.V = float(np.min(lim.vel[big] / dq[big])) * margin+ self.A = float(np.min(acc[big] / dq[big])) * margin+ self.J = float(np.min(jerk[big] / dq[big])) * margin+ self.A = min(self.A, 1e9)+ self.J = min(self.J, 1e12)+ self.p = _scurve_params(1.0, self.V, self.A, self.J)+ Tj, Ta, Tv, vp, ap = self.p+ self.t_min = 2.0 * Ta + Tv+ self.T = max(float(T), self.t_min)+ self.k = self.t_min / self.T if self.T > 0 else 1.0 # time scaling of a stretched move++ def s(self, t):+ """(s, ds/dt, d2s/dt2) at time t >= 0"""+ if self.t_min <= 0.0:+ return 1.0, 0.0, 0.0+ u = min(max(t * self.k, 0.0), self.t_min)+ Tj, Ta, Tv, vp, ap = self.p+ if u <= Ta:+ p, v, a = _acc_phase(u, Tj, Ta, vp, ap, self.J)+ elif u <= Ta + Tv:+ p, v, a = vp * Ta / 2.0 + vp * (u - Ta), vp, 0.0+ else:+ p, v, a = _acc_phase(self.t_min - u, Tj, Ta, vp, ap, self.J)+ p, a = 1.0 - p, -a+ return p, v * self.k, a * self.k * self.k++ def at(self, t):+ """(q, qd, qdd) at time t"""+ s, sd, sdd = self.s(t)+ d = self.q1 - self.q0+ return self.q0 + s * d, sd * d, sdd * d++ def samples(self, dt):+ """q at t = dt, 2 dt, ..., n dt with n = ceil(T / dt) (the last sample is q1)"""+ n = max(1, int(math.ceil(self.T / dt - 1e-9)))+ return [self.at(i * dt)[0] if i < n else self.q1.copy() for i in range(1, n + 1)]+++def plan_line(q0, q1, lim: ArmLimits, T: float = 0.0, margin: float = 1.0) -> Line:+ return Line(q0, q1, lim, T, margin)+++def hermite(q0, v0, q1, v1, T, n):+ """a cubic Hermite segment from (q0, v0) to (q1, v1) over T seconds, sampled at T j / n, j = 1..n: (q, qd) arrays+ (n x joints). Turns rows of targets one control step apart into a smooth reference for the JerkLimiter."""+ q0, v0, q1, v1 = (np.asarray(x, float) for x in (q0, v0, q1, v1))+ s = (np.arange(1, n + 1) / n)[:, None]+ h00, h10, h01, h11 = 2 * s**3 - 3 * s**2 + 1, s**3 - 2 * s**2 + s, -2 * s**3 + 3 * s**2, s**3 - s**2+ d00, d10, d01, d11 = 6 * s**2 - 6 * s, 3 * s**2 - 4 * s + 1, -6 * s**2 + 6 * s, 3 * s**2 - 2 * s+ q = h00 * q0 + h10 * T * v0 + h01 * q1 + h11 * T * v1+ qd = (d00 * q0 + d01 * q1) / T + d10 * v0 + d11 * v1+ return q, qd+++def jerk_caps(M, lim: ArmLimits, share: float = 0.7):+ """The joint jerks the torque-rate limit allows with the arm's joint-space inertia M (joints x joints, at a pose):+ the inertia part of the torque rate is M qddd, so joint i may use at most share x dtau_max_i / sum_j |M_ij| (every+ joint at its own cap keeps every torque rate within share of its limit; the rest is left to gravity, Coriolis and+ the servo's corrections). Never above the jerk limits. Without a torque-rate limit: the jerk limits."""+ if lim.dtau is None:+ return lim.jerk+ cap = share * lim.dtau / np.maximum(np.sum(np.abs(np.asarray(M, float)), axis=1), 1e-9)+ return cap if lim.jerk is None else np.minimum(lim.jerk, cap)+++# ------------------------------------------------------------------------------------------------ setpoint limiter+def _sqrt_ctrl(err, k, d):+ """the sqrt controller: linear (gain k) near zero, sqrt(2 d |err|) beyond (braking at d), elementwise"""+ lin = d / (k * k)+ a = np.abs(err)+ out = np.where(a <= lin, k * err, np.sign(err) * np.sqrt(np.maximum(0.0, 2.0 * d * (a - 0.5 * lin))))+ return out+++def brake_speed(dist, A, J):+ """The largest speed from which a jerk-limited stop (acceleration from 0, at most A, jerk J) ends within dist:+ the inverse of d(v) = v sqrt(v / J) (v <= A^2 / J) or v^2 / (2 A) + v A / (2 J). Elementwise."""+ dist = np.maximum(np.asarray(dist, float), 0.0)+ A, J = np.asarray(A, float), np.asarray(J, float)+ small = dist <= A**3 / J**2+ v_small = np.cbrt(dist * dist * J)+ v_big = 0.5 * (-A * A / J + np.sqrt(A**4 / J**2 + 8.0 * A * dist))+ return np.where(small, v_small, v_big)+++class JerkLimiter:+ """The robot's setpoint generator at the physics rate: per joint a third-order state (q, qd, qdd) that follows a+ reference (position r, velocity rd) and never exceeds |qd| <= vel, |qdd| <= acc, |dqdd/dt| <= jerk.++ A cascade (position -> velocity -> acceleration -> jerk) with the reference velocity as feed-forward; the jerk is+ clipped, so the acceleration and velocity bounds hold by construction (the velocity bound with a margin of one+ step of jerk and one of acceleration: the discrete steps' overshoot). The velocity loop is the sqrt law at the jerk+ limit. The position loop brakes within both the acceleration and the jerk in force at this step (brake_speed, on+ the error left once the present acceleration has ramped to zero): the jerk a step may use is the tighter of the+ jerk limit and the step's jerk_cap (limits.jerk_caps(): the torque rate's share at the pose, a few hundred rad/s^3+ on a Panda's shoulder in play), and a position loop that assumed the deceleration there at once (a sqrt law at+ BRAKE x the acceleration limit, this class until 2026-10-11) overshot at such a jerk and rang in a self-sustained+ limit cycle (a 2.9 deg step at 231 rad/s^3: out to 6.4 deg, then +-3.5 deg at 2.5 Hz). servo.SetpointGenerator's+ law, with the coast distance taken relative to the reference's velocity (qd - rd): with qd alone a moving+ reference looked overshot and the setpoint braked early (servo.SetpointGenerator and PlanarBase the same since+ 2026-10-12). Deterministic (plain float64 numpy)."""++ KP, KV = 60.0, 300.0 # 1/s: position and velocity loop gains (the linear zone of the sqrt laws)+ BRAKE = 0.6 # position loop brakes at BRAKE x the acceleration limit (room for the jerk)++ def __init__(self, lim: ArmLimits, dt: float, q0=None):+ self.lim, self.dt = lim, float(dt)+ n = lim.n+ self.A = lim.acc if lim.acc is not None else np.full(n, 1e6)+ self.J = lim.jerk if lim.jerk is not None else np.full(n, 1e9)+ # the velocity bound one step of jerk and one of acceleration below the limit (the discrete steps' overshoot)+ margin = (0.0 if lim.jerk is None else lim.jerk * self.dt**2) + (0.0 if lim.acc is None else lim.acc * self.dt)+ self.V = np.maximum(lim.vel - margin, 0.5 * lim.vel)+ self.reset(np.zeros(n) if q0 is None else q0)++ def reset(self, q, qd=None, qdd=None):+ n = self.lim.n+ self.q = np.asarray(q, float).copy()+ self.qd = np.zeros(n) if qd is None else np.asarray(qd, float).copy()+ self.qdd = np.zeros(n) if qdd is None else np.asarray(qdd, float).copy()++ def step(self, r, rd=None, jerk_cap=None):+ """advance one step towards the reference r (velocity rd); jerk_cap: tighter jerk limits for this step (e.g.+ jerk_caps() at the current pose: a soft limit, which the velocity bound may override up to the jerk limit).+ Returns (q, qd, qdd) of the new setpoint"""+ dt, V, A, Jh = self.dt, self.V, self.A, self.J+ J = Jh if jerk_cap is None else np.minimum(Jh, jerk_cap)+ r = np.asarray(r, float)+ rd = np.zeros_like(r) if rd is None else np.asarray(rd, float)+ # the position loop sees the error left once the present acceleration has ramped to zero at this step's jerk+ # (the distance it still covers, relative to the reference moving at rd) and brakes within the acceleration+ # and that jerk (brake_speed). Relative: with qd alone a moving reference looked overshot and the setpoint+ # braked early (2026-10-12: table-tennis strokes delivered too little blade speed, B9 248/284)+ e = r - self.q+ t = np.abs(self.qdd) / J+ e = e - ((self.qd - rd) * t + 0.5 * self.qdd * t * t - np.sign(self.qdd) * J * t**3 / 6.0)+ v_pos = np.sign(e) * np.minimum(self.KP * np.abs(e), brake_speed(np.abs(e), self.BRAKE * A, J))+ v_cmd = np.clip(rd + v_pos, -V, V)+ a_cmd = np.clip(_sqrt_ctrl(v_cmd - self.qd, self.KV, J), -A, A)+ # never run past the velocity limit: the acceleration must be able to fall to zero (at the jerk limit)+ # before |qd| reaches V; planned with the soft jerk, enforced with the hard one if the soft one changed+ room_up, room_dn = np.maximum(0.0, V - self.qd), np.maximum(0.0, V + self.qd)+ a_cmd = np.clip(a_cmd, -np.sqrt(2.0 * J * room_dn), np.sqrt(2.0 * J * room_up))+ hard = (self.qdd > np.sqrt(2.0 * Jh * room_up)) | (self.qdd < -np.sqrt(2.0 * Jh * room_dn))+ a_cmd = np.where(hard, np.clip(a_cmd, -np.sqrt(2.0 * Jh * room_dn), np.sqrt(2.0 * Jh * room_up)), a_cmd)+ jl = np.where(hard, Jh, J)+ j = np.clip((a_cmd - self.qdd) / dt, -jl, jl)+ self.q = self.q + self.qd * dt + 0.5 * self.qdd * dt * dt + j * dt**3 / 6.0+ self.qd = self.qd + self.qdd * dt + 0.5 * j * dt * dt+ self.qdd = self.qdd + j * dt+ return self.q, self.qd, self.qdd+++class TorqueRateLimiter:+ """The servo's output stage: |tau| <= tau_max and |tau - tau_prev| <= dtau_max * dt every step."""++ def __init__(self, lim: ArmLimits, dt: float, tau0=None):+ self.tau_max = lim.tau+ self.step_max = None if lim.dtau is None else lim.dtau * float(dt)+ self.reset(np.zeros(lim.n) if tau0 is None else tau0)++ def reset(self, tau):+ self.tau = np.clip(np.asarray(tau, float), -self.tau_max, self.tau_max)++ def __call__(self, tau_des):+ t = np.asarray(tau_des, float)+ if self.step_max is not None:+ t = np.clip(t, self.tau - self.step_max, self.tau + self.step_max)+ self.tau = np.clip(t, -self.tau_max, self.tau_max)+ return self.tau+++# ------------------------------------------------------------------------------------------------ low-level rows+def check_rows(rows, dt, lim: ArmLimits, prev=None, prev_vel=None, tol=1.001):+ """Rows of joint targets (n x joints) one step dt apart, against the velocity and acceleration limits; prev, the+ targets in force before the first row (and prev_vel, their velocity), join the check if given. Returns None or the+ reason. Jerk is not checked at this step: the JerkLimiter smooths it at the physics rate."""+ a = np.asarray(rows, float)+ if prev is not None:+ a = np.vstack([np.asarray(prev, float)[None], a])+ if len(a) < 2:+ return None+ v = np.diff(a, axis=0) / dt+ if np.any(np.abs(v) > lim.vel * tol + 1e-9):+ i, j = np.argwhere(np.abs(v) > lim.vel * tol + 1e-9)[0]+ return f"joint {j + 1}: {abs(v[i, j]):.3f} rad/s between rows exceeds its speed limit {lim.vel[j]:.3f} rad/s"+ if lim.acc is None:+ return None+ if prev_vel is not None and prev is not None:+ v = np.vstack([np.asarray(prev_vel, float)[None], v])+ if len(v) < 2:+ return None+ acc = np.diff(v, axis=0) / dt+ bad = np.abs(acc) > lim.acc * tol + 1e-9+ if np.any(bad):+ i, j = np.argwhere(bad)[0]+ return (+ f"joint {j + 1}: {abs(acc[i, j]):.2f} rad/s^2 between rows exceeds its acceleration limit "+ f"{lim.acc[j]:.2f} rad/s^2"+ )+ return None+++# ------------------------------------------------------------------------------------------------ measurement+QUANTITIES = (+ ("vel", "velocity", "rad/s"),+ ("acc", "acceleration", "rad/s^2"),+ ("jerk", "jerk", "rad/s^3"),+ ("tau", "torque", "N m"),+ ("dtau", "torque rate", "N m/s"),+)+++def derivatives(q, dt, breaks=None):+ """velocity, acceleration and jerk of a sampled joint path q (steps x joints) by finite differences; `breaks`+ (step indices where the world was reset) cut the differences. Returns dict of arrays (NaN where undefined)."""+ q = np.asarray(q, float)+ v = np.full_like(q, np.nan)+ v[1:] = np.diff(q, axis=0) / dt+ for b in breaks or ():+ v[b] = np.nan+ a = np.full_like(q, np.nan)+ a[1:] = np.diff(v, axis=0) / dt+ j = np.full_like(q, np.nan)+ j[1:] = np.diff(a, axis=0) / dt+ return dict(vel=v, acc=a, jerk=j)+++def stats(series: dict, lim: ArmLimits, joints=None) -> dict:+ """series: name -> (steps x joints) array (NaN = undefined) for vel, acc, jerk, tau, dtau (any subset).+ Returns per quantity: per joint p50, p95, p99, p99.9, max of |x|, the limit, p99 / limit, max / limit and the+ share of samples above the limit."""+ names = joints or [f"A{i + 1}" for i in range(lim.n)]+ out = {}+ for key, title, unit in QUANTITIES:+ x = series.get(key)+ if x is None:+ continue+ L = getattr(lim, key)+ rows = []+ for j in range(lim.n):+ col = np.abs(np.asarray(x, float)[:, j])+ col = col[np.isfinite(col)]+ if not len(col):+ rows.append(None)+ continue+ p = np.percentile(col, [50, 95, 99, 99.9])+ r = dict(+ joint=names[j],+ n=int(len(col)),+ p50=float(p[0]),+ p95=float(p[1]),+ p99=float(p[2]),+ p999=float(p[3]),+ max=float(col.max()),+ )+ if L is not None:+ lj = float(L[j])+ r.update(+ limit=lj,+ p99_ratio=float(p[2] / lj),+ max_ratio=float(col.max() / lj),+ over_share=float(np.mean(col > lj * 1.001)),+ )+ rows.append(r)+ out[key] = dict(title=title, unit=unit, joints=rows)+ return outdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/selfcollision.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/selfcollision.pynew file mode 100644index 0000000000..bb408e4142--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/selfcollision.py@@ -0,0 +1,657 @@+"""Self-collision (bodies/README.md "自碰撞"; real limits B0): a real arm cannot pass through its own body, so the+simulated one cannot either. One declaration per robot (body.toml [self_collision]) says which parts of the robot+touch which; this module turns it into MuJoCo contact pairs, counts the contacts during play, and checks the+declaration against the model.++What collides (body.toml [self_collision], the rules below):+ parts every body of the robot belongs to a part by a regular expression on its name (without the robot's+ prefix / suffix): an arm (`left_arm`, `right_arm`; a single arm: `arm`) or `body` (torso, waist, head,+ pelvis, legs, the base and its wheels, a pedestal). A body that matches nothing inherits its parent's part;+ one hanging below an arm without matching is the arm's TOOL (the hand on the wrist mount: paddle, racket,+ epee). The bodies a fixed-base arm stands on (its pedestal, gantry carriage, rail cart: the ancestors of the+ robot's matched bodies) are `body`.+ rules every arm geom x every body geom (arm_body; legs count as body here); left arm x right arm, tools+ included (arm_arm); a tool x the links of its own arm (tool_own_arm); with same_arm = true also link x+ link of the same arm (a single arm such as the Franka, whose links fold onto each other). Legs (parts+ `left_leg`, `right_leg`): leg_leg = true, left leg x right leg; same_leg = true, link x link of one leg+ (shin x foot). ignore_geoms (a regular expression on geom names) leaves out sensing volumes.+ excluded automatically: two geoms of one rigid group (bodies welded together: a link, its mount and its tool) and+ of two rigid groups joined by one joint (a link and its parent: the joint's housing overlaps by design,+ MuJoCo's own parent filter); by declaration: [[self_collision.exclude]] entries (two body-name patterns+ and a reason), for hulls that overlap at a joint housing one link further away. Every exclusion is+ written down with its reason; the check below fails an exclusion that matches nothing.++How: explicit MuJoCo <pair>s (named <tag>_<i>, tag = the robot's prefix + "selfcol" + suffix), so the robot's+geoms keep their contype / conaffinity (the library's robots: contype 4 / conaffinity 0, they never touch each+other or a second robot) and a pair adds exactly one tested geom pair; the contact parameters are MuJoCo's defaults+(condim 3, friction 1) with a stiff solref (SOLREF: rigid shells). The contacts+block the motion physically, as the real robot's shell does; the servo is not told (a real controller is not+either: the arm stalls against itself, its PD torque rises to the torque limit).++What is recorded (Monitor, fed by every rig.apply): self-collision events (a pair coming into contact; a bouncing+contact is one event), the time in contact, the peak normal force, its peak 10 ms mean and the impulse, per pair;+events whose 10 ms mean force exceeds the declared threshold ([self_collision] warn_force_n) are counted as+warnings. Recorded only: no penalty (the sports decide; see README).++ from bodies import selfcollision as SC+ plan = SC.plan(template_root, decl["self_collision"], prefix="A_") # stdlib only: pairs + exclusions+ SC.add_pairs(scene_root, plan) # <contact><pair .../></contact>+ mon = SC.Monitor(model, plan.tag, warn_force_n=30.0); mon.update(d) per physics step; mon.summary()+ python -m bodies.selfcollision check [robot ...] # needs mujoco (CI installs it)+ python -m bodies.selfcollision pairs ROBOT # the enabled and excluded pairs+ python -m bodies.selfcollision scene sports/SPORT # a sport's scenes: write the pairs++The planning part (plan, add_pairs, scene_block) is stdlib only; Monitor and check import numpy / mujoco.+"""+from __future__ import annotations++import re+import sys+import xml.etree.ElementTree as ET+from dataclasses import dataclass, field+from pathlib import Path++HERE = Path(__file__).resolve().parent+MARK_BEGIN = "<!-- self-collision: generated by bodies/selfcollision.py (scene_block), do not edit -->"+MARK_END = "<!-- /self-collision -->"+++# ------------------------------------------------------------------------------------------------ the model's tree+def _defaults(root: ET.Element) -> dict[str, dict]:+ """class name -> the geom attributes the class gives (nested defaults inherit), "main" for the top level."""+ table: dict[str, dict] = {"main": {}}++ def walk(el, inherited, name):+ attrs = dict(inherited)+ g = el.find("geom")+ if g is not None:+ attrs.update(g.attrib)+ table[name] = attrs+ for ch in el.findall("default"):+ walk(ch, attrs, ch.get("class"))++ for top in root.findall("default"):+ if top.get("class") in (None, "main"):+ walk(top, table["main"], "main")+ else: # a section of classes appended at the top level+ walk(top, table["main"], top.get("class"))+ return table+++def _resolved(geom: ET.Element, cls: str, table: dict) -> dict:+ out = dict(table.get(cls, table["main"]))+ out.update(geom.attrib)+ return out+++def is_collision_geom(attrs: dict) -> bool:+ """The default selection: a geom MuJoCo would collide (contype or conaffinity non-zero; defaults are 1)."""+ return int(attrs.get("contype", "1")) != 0 or int(attrs.get("conaffinity", "1")) != 0+++def is_physical_geom(attrs: dict) -> bool:+ """A geom that is part of the robot's physical shape: a collision geom, or one with mass (the Franka scenes' arm+ meshes are drawn and simulated but switched out of MuJoCo's contacts with contype 0); not a massless drawing."""+ zero = lambda k: attrs.get(k) is not None and float(attrs[k]) == 0.0+ return is_collision_geom(attrs) or not (zero("mass") or zero("density"))+++SELECT = {"collision": is_collision_geom, "physical": is_physical_geom}+++@dataclass+class Plan:+ tag: str # pair names: <tag>_<i>+ pairs: list = field(default_factory=list) # (geom1, geom2, body1, body2, rule)+ excluded: list = field(default_factory=list) # (body1, body2, reason)+ parts: dict = field(default_factory=dict) # body name -> (part, is_tool)+ unused_exclusions: list = field(default_factory=list)++ def summary(self) -> dict:+ rules: dict[str, int] = {}+ for p in self.pairs:+ rules[p[4]] = rules.get(p[4], 0) + 1+ return {"tag": self.tag, "pairs": len(self.pairs), "by_rule": rules, "excluded_body_pairs": len(self.excluded)}+++def plan(root: ET.Element, decl: dict, prefix: str = "", suffix: str = "", world_geoms=(), select=None,+ name_unnamed: bool = True) -> Plan:+ """The self-collision pairs of one robot in an MJCF tree (a body's template or a whole scene). decl: body.toml+ [self_collision]. prefix / suffix: what the robot's names carry in this tree ("A_", "_b"). world_geoms: geoms of+ the worldbody that belong to the robot's body (a pedestal drawn in the world). select(attrs) -> bool picks the+ geoms that take part (default: the collision geoms). Unnamed selected geoms get a name (<body>_sc<k>), since a+ <pair> names its geoms."""+ select = select or is_collision_geom+ table = _defaults(root)+ wb = root.find("worldbody")+ norm = lambda n: n[len(prefix):len(n) - len(suffix) if suffix else None] \+ if n and n.startswith(prefix) and n.endswith(suffix) else None+ parts_re = {k: re.compile(v) for k, v in decl["parts"].items()}++ def match(n):+ if n is None:+ return None+ for k, rx in parts_re.items():+ if rx.fullmatch(n):+ return k+ return None++ # walk the tree: parent, weld group (bodies without a joint are welded to their parent), class, part+ info = {} # body element -> dict++ def walk(el, parent, weld_parent_group, cls, inherited):+ for b in el.findall("body"):+ name = b.get("name")+ n = norm(name)+ jointed = b.find("joint") is not None or b.find("freejoint") is not None+ weld = b if jointed else weld_parent_group+ c = b.get("childclass") or cls+ m = match(n)+ if m is not None:+ part, tool = m, False+ elif inherited is not None:+ part, tool = inherited[0], inherited[0] != "body"+ else:+ part, tool = None, False+ info[b] = dict(name=name, norm=n, parent=parent, weld=weld, cls=c, part=part, tool=tool or (+ inherited is not None and inherited[1]))+ walk(b, b, weld, c, (part, info[b]["tool"]) if part is not None else None)++ walk(wb, None, "world", "main", None)+ robot = [b for b, i in info.items() if i["part"] is not None]+ if not robot:+ raise ValueError(f"no body of the robot (prefix {prefix!r}, suffix {suffix!r}) in the tree")+ # the bodies the robot stands on (ancestors of its matched bodies, not matched themselves): its body+ for b in robot:+ p = info[b]["parent"]+ while p is not None and info[p]["part"] is None:+ info[p]["part"], info[p]["tool"] = "body", False+ p = info[p]["parent"]+ weld_parent = {}+ for b, i in info.items():+ w = i["weld"]+ if w != "world" and w not in weld_parent:+ pb = info[w]["parent"]+ weld_parent[w] = info[pb]["weld"] if pb is not None else "world"++ def adjacent(wa, wb_):+ return wa is wb_ or weld_parent.get(wa) is wb_ or weld_parent.get(wb_) is wa++ # the geoms that take part (not those of [self_collision] ignore_geoms: sensing volumes, e.g. a kick's strike box)+ ignore = re.compile(decl["ignore_geoms"]) if decl.get("ignore_geoms") else None+ kind = lambda p: "arm" if p.endswith("arm") else "leg" if p.endswith("leg") else "body"+ geoms = [] # (name, body element or None for the world, part, tool, weld)+ for b, i in info.items():+ if i["part"] is None:+ continue+ k = 0+ for g in b.findall("geom"):+ attrs = _resolved(g, g.get("class") or i["cls"], table)+ if not select(attrs):+ continue+ if ignore is not None and g.get("name") is not None and ignore.fullmatch(norm(g.get("name")) or ""):+ continue+ if g.get("name") is None:+ if not name_unnamed:+ raise ValueError(f"an unnamed collision geom in body {i['name']}")+ g.set("name", f"{i['name']}_sc{k}")+ k += 1+ geoms.append((g.get("name"), b, i["part"], i["tool"], i["weld"]))+ for gname in world_geoms:+ g = next((x for x in wb.findall("geom") if x.get("name") == gname), None)+ if g is None:+ raise ValueError(f"world geom {gname!r} not found")+ geoms.append((gname, None, "body", False, "world"))+ # exclusions by declaration+ ex = [(re.compile(e["bodies"][0]), re.compile(e["bodies"][1]), e["reason"]) for e in decl.get("exclude", [])]+ used = [False] * len(ex)+ bn = lambda b: "world" if b is None else info[b]["norm"] or info[b]["name"]+ rules = decl.get("rules", {})+ out = Plan(tag=f"{prefix}selfcol{suffix}",+ parts={info[b]["name"]: (i["part"], i["tool"]) for b, i in info.items() if i["part"] is not None})+ seen_ex = set()+ for x in range(len(geoms)):+ for y in range(x + 1, len(geoms)):+ g1, b1, p1, t1, w1 = geoms[x]+ g2, b2, p2, t2, w2 = geoms[y]+ if b1 is b2 and b1 is not None:+ continue+ k1, k2 = kind(p1), kind(p2)+ if k1 == "arm" and k2 == "arm":+ if p1 != p2:+ rule = "arm_arm"+ elif t1 != t2:+ rule = "tool_own_arm"+ elif not t1 and rules.get("same_arm", False):+ rule = "same_arm"+ else:+ continue+ elif k1 == "arm" or k2 == "arm": # an arm (or its tool) with the body or a leg+ rule = "tool_body" if (t1 or t2) else "arm_body"+ elif k1 == "leg" and k2 == "leg":+ rule = "leg_leg" if p1 != p2 else "same_leg"+ if not rules.get(rule, False):+ continue+ else: # body x body, leg x body: not tested+ continue+ if not rules.get(rule if rule != "tool_body" else "arm_body", True):+ continue+ if adjacent(w1, w2):+ key = tuple(sorted((bn(b1), bn(b2))))+ if key not in seen_ex:+ seen_ex.add(key)+ out.excluded.append((*key, "AUTO: one rigid group, or two joined by one joint (the joint's "+ "housing; MuJoCo's parent filter)"))+ continue+ n1, n2 = bn(b1), bn(b2)+ hit = None+ for k, (ra, rb, why) in enumerate(ex):+ if (ra.fullmatch(n1) and rb.fullmatch(n2)) or (ra.fullmatch(n2) and rb.fullmatch(n1)):+ hit = k+ break+ if hit is not None:+ used[hit] = True+ key = tuple(sorted((n1, n2)))+ if key not in seen_ex:+ seen_ex.add(key)+ out.excluded.append((*key, ex[hit][2]))+ continue+ out.pairs.append((g1, g2, n1, n2, rule))+ out.unused_exclusions = [decl["exclude"][k]["bodies"] for k in range(len(ex)) if not used[k]]+ return out+++def is_tag(name: str | None, tag: str) -> bool:+ """A pair name of this robot: <tag>_<i> exactly (robot A's tag "selfcol" must not take robot B's "selfcol_b_3")."""+ return bool(name) and re.fullmatch(re.escape(tag) + r"_\d+", name) is not None+++def info(p: Plan | None) -> dict:+ """What a body's mount() returns about its self-collision (p None: switched off)."""+ if p is None:+ return {"selfcol_tag": None, "selfcol_pairs": 0, "selfcol_unused": [], "selfcol_plan": None}+ return {"selfcol_tag": p.tag, "selfcol_pairs": len(p.pairs), "selfcol_unused": p.unused_exclusions,+ "selfcol_plan": p}+++SOLREF = "0.005 1" # stiff (5 ms, critically damped): the shells are rigid; MuJoCo's default 0.02 lets a servo+ # pushing at its torque limit sink an arm 2 cm into the body (conformance 9)+++def pair_elements(p: Plan) -> list[ET.Element]:+ return [ET.Element("pair", name=f"{p.tag}_{i}", geom1=g1, geom2=g2, solref=SOLREF)+ for i, (g1, g2, *_r) in enumerate(p.pairs)]+++def add_pairs(scene: ET.Element, p: Plan) -> int:+ """Append the plan's pairs to the scene's <contact> (created if missing). Returns the number of pairs."""+ con = scene.find("contact")+ if con is None:+ con = ET.SubElement(scene, "contact")+ for el in pair_elements(p):+ con.append(el)+ return len(p.pairs)+++def scene_block(plans: list[Plan], indent: str = " ") -> str:+ """The pairs of fixed scenes (a sport's MJCF file) as text between the generated-block markers."""+ lines = [indent + MARK_BEGIN]+ for p in plans:+ for el in pair_elements(p):+ lines.append(indent + ET.tostring(el, encoding="unicode"))+ lines.append(indent + MARK_END)+ return "\n".join(lines)+++def put_scene_block(text: str, block: str) -> str:+ """Insert (or replace) the generated block in an MJCF text: inside <contact> (created before </mujoco>)."""+ if MARK_BEGIN in text:+ a = text.index(MARK_BEGIN)+ a = text.rfind("\n", 0, a) + 1+ b = text.index(MARK_END) + len(MARK_END)+ return text[:a] + block.lstrip("\n") + text[b:]+ i = text.rfind("</contact>")+ if i >= 0:+ i = text.rfind("\n", 0, i) + 1 # the start of the </contact> line+ return text[:i] + block + "\n" + text[i:]+ j = text.rfind("</mujoco>")+ return text[:j] + " <contact>\n" + block + "\n </contact>\n" + text[j:]+++def sport_scenes(sport_dir: Path) -> list[tuple[Path, list[Plan]]]:+ """The scenes of a sport that carries a library arm in its own scene (sport.toml [self_collision]: body, and+ [[self_collision.scenes]]: scene, robots = [{prefix, suffix, world_geoms}], geoms = "collision" | "physical")+ with their plans (stdlib only)."""+ import tomllib+ st = tomllib.loads((sport_dir / "sport.toml").read_text())+ sc = st.get("self_collision") or {}+ decl = tomllib.loads((HERE / sc["body"] / "body.toml").read_text())["self_collision"]+ out = []+ for e in sc.get("scenes", []):+ f = sport_dir / e["scene"]+ root = ET.fromstring(f.read_text())+ plans = [plan(root, decl, prefix=r.get("prefix", ""), suffix=r.get("suffix", ""),+ world_geoms=r.get("world_geoms", ()), select=SELECT[e.get("geoms", "collision")],+ name_unnamed=False) for r in e["robots"]]+ out.append((f, plans))+ return out+++def write_sport_scenes(sport_dir: Path) -> list[str]:+ """Write (or refresh) the generated pair blocks of a sport's scenes. Returns what it did."""+ done = []+ for f, plans in sport_scenes(sport_dir):+ text = f.read_text()+ new = put_scene_block(text, scene_block(plans))+ if new != text:+ f.write_text(new)+ done.append(f"{f}: {sum(len(p.pairs) for p in plans)} pairs" + ("" if new != text else " (unchanged)"))+ return done+++def scene_pairs(text: str) -> list[tuple[str, str, str]]:+ """The (name, geom1, geom2) of the generated block of an MJCF text (stdlib: for the static CI check)."""+ if MARK_BEGIN not in text:+ return []+ blk = text[text.index(MARK_BEGIN):text.index(MARK_END)]+ return re.findall(r'<pair name="([^"]+)" geom1="([^"]+)" geom2="([^"]+)"', blk)+++# ------------------------------------------------------------------------------------------------ during play+class Monitor:+ """Self-collision contacts of one robot (its pairs: names <tag>_<i>), fed once per physics step (rig.apply, or+ the sport's loop). An event is a pair coming into contact (after more than GAP_S out of contact: a bouncing+ contact is one event); per event its peak normal force and its peak 10 ms mean force (FORCE_WINDOW_S: what a+ real robot's collision detection, which filters its external-force estimate, would see; an impact's+ instantaneous peak depends on the contact stiffness). An event whose 10 ms mean force exceeds warn_force_n is a+ warning. Also the time in contact, the impulse, the deepest penetration. Nothing it does changes the simulation."""++ GAP_S = 0.02+ FORCE_WINDOW_S = 0.01++ def __init__(self, model, tag: str, warn_force_n: float | None = None):+ import numpy as np+ import mujoco as mj+ self.m = model # no module attributes: a sport may pickle its simulator with it+ self.tag, self.warn = tag, warn_force_n+ ng = model.ngeom+ keys, names = [], {}+ gn = lambda g: mj.mj_id2name(model, mj.mjtObj.mjOBJ_GEOM, g)+ for i in range(model.npair):+ if is_tag(mj.mj_id2name(model, mj.mjtObj.mjOBJ_PAIR, i), tag):+ a, b = int(model.pair_geom1[i]), int(model.pair_geom2[i])+ k = min(a, b) * ng + max(a, b)+ keys.append(k)+ names[k] = (gn(a), gn(b))+ self.keys = np.array(sorted(keys), dtype=np.int64)+ self.names = names+ self.dt = float(model.opt.timestep)+ self.gap = max(1, int(round(self.GAP_S / self.dt)))+ self.win = max(1, int(round(self.FORCE_WINDOW_S / self.dt)))+ self._f = np.zeros(6)+ self.reset()++ @property+ def npairs(self):+ return int(self.keys.size)++ def reset(self):+ self.t = 0+ self.open: dict[int, dict] = {} # pair key -> the running event+ self.events = 0+ self.warnings = 0+ self.steps_in_contact = 0+ self.peak_force = 0.0+ self.peak_force_10ms = 0.0+ self.max_depth = 0.0+ self.impulse = 0.0+ self.first_t = None+ self.by_pair: dict[int, list] = {} # key -> [events, peak force, peak 10 ms mean force]++ def update(self, d):+ """One physics step: the contacts MuJoCo found in the last step (d.contact, d.efc_force)."""+ self.t += 1+ n = d.ncon+ if self.keys.size == 0 or (n == 0 and not self.open):+ return+ import numpy as np+ import mujoco as mj+ now: dict[int, float] = {}+ if n:+ g = d.contact.geom[:n]+ k = np.minimum(g[:, 0], g[:, 1]).astype(np.int64) * self.m.ngeom + np.maximum(g[:, 0], g[:, 1])+ for i in np.nonzero(np.isin(k, self.keys))[0]:+ mj.mj_contactForce(self.m, d, int(i), self._f)+ f = abs(float(self._f[0]))+ kk = int(k[i])+ now[kk] = now.get(kk, 0.0) + f+ self.impulse += f * self.dt+ self.max_depth = max(self.max_depth, -float(d.contact.dist[i]))+ for kk in now:+ if kk not in self.open:+ self.events += 1+ if self.first_t is None:+ self.first_t = self.t+ self.by_pair.setdefault(kk, [0, 0.0, 0.0])[0] += 1+ self.open[kk] = {"w": [0.0] * self.win, "i": 0, "s": 0.0, "peak": 0.0, "avg": 0.0, "last": self.t}+ for kk in list(self.open):+ ev = self.open[kk]+ f = now.get(kk, 0.0)+ w, i = ev["w"], ev["i"]+ ev["s"] += f - w[i]+ w[i] = f+ ev["i"] = (i + 1) % self.win+ if f > 0.0:+ ev["last"] = self.t+ ev["peak"] = max(ev["peak"], f)+ ev["avg"] = max(ev["avg"], ev["s"] / self.win)+ bp = self.by_pair[kk]+ bp[1], bp[2] = max(bp[1], ev["peak"]), max(bp[2], ev["avg"])+ self.peak_force = max(self.peak_force, ev["peak"])+ self.peak_force_10ms = max(self.peak_force_10ms, ev["avg"])+ if self.t - ev["last"] > self.gap: # out of contact for longer than the gap: the event is over+ self._close(kk)+ if now:+ self.steps_in_contact += 1++ def _close(self, kk):+ ev = self.open.pop(kk)+ if self.warn is not None and ev["avg"] > self.warn:+ self.warnings += 1++ def summary(self, top: int = 5) -> dict:+ """What a match record carries (JSON-safe)."""+ open_warn = sum(1 for ev in self.open.values() if self.warn is not None and ev["avg"] > self.warn)+ worst = sorted(self.by_pair.items(), key=lambda kv: -kv[1][2])[:top]+ return {"pairs": self.npairs, "events": self.events, "warnings": self.warnings + open_warn,+ "warn_force_n": self.warn, "time_in_contact_s": round(self.steps_in_contact * self.dt, 4),+ "peak_force_n": round(self.peak_force, 3), "peak_force_10ms_n": round(self.peak_force_10ms, 3),+ "impulse_ns": round(self.impulse, 5), "max_depth_m": round(self.max_depth, 5),+ "first_step": self.first_t,+ "worst_pairs": [{"geoms": list(self.names[k]), "events": v[0], "peak_force_n": round(v[1], 3),+ "peak_force_10ms_n": round(v[2], 3)} for k, v in worst]}+++def monitors(model, tags: dict, body: str) -> dict:+ """One Monitor per seat ({seat: pair tag}) for a sport whose scene carries the library arm `body` (its+ body.toml [self_collision] warn_force_n): for the sports' own simulators (sport.toml [self_collision])."""+ import tomllib+ warn = tomllib.loads((HERE / body / "body.toml").read_text())["self_collision"].get("warn_force_n")+ return {seat: Monitor(model, tag, warn) for seat, tag in tags.items()}+++# ------------------------------------------------------------------------------------------------ the check+def rig_sampler(rig, m, rest_qpos):+ """Random legal poses of a library robot: the controlled vector u (lift, waist, the hand arm) uniform inside the+ rig's ranges (rig.LO / rig.HI; the base and the walking command at rest), the other arm's joints uniform inside+ their MJCF ranges; a legged robot's legs uniform in their ranges (its pelvis where it stands); the base at rest."""+ import numpy as np+ o = getattr(rig, "o", 0)+ other = rig.qadr[-7:]+ jr = {int(m.jnt_qposadr[j]): m.jnt_range[j] for j in range(m.njnt)}+ lo_o = np.array([jr[int(a)][0] for a in other])+ hi_o = np.array([jr[int(a)][1] for a in other])+ legs = rig.lqadr if not getattr(rig, "fixed_base", True) else [] # a legged robot's legs: uniform too+ lo_l = np.array([jr[int(a)][0] for a in legs])+ hi_l = np.array([jr[int(a)][1] for a in legs])++ def sample(rng):+ u = np.array(rig.rest, float)+ u[3:] = rng.uniform(rig.LO[3:], rig.HI[3:])+ q = rest_qpos.copy()+ t = rig.joint_targets(u)+ q[rig.qadr[o:]] = t[o:]+ q[other] = rng.uniform(lo_o, hi_o)+ if len(legs):+ q[legs] = rng.uniform(lo_l, hi_l)+ return q+ return sample+++def check_model(m, tag, rest_qpos, sample, n_random=200, seed=0, structural=0.95, tol=1e-4):+ """The static self-collision check of one compiled model: (problems, report). At rest_qpos no pair of `tag`+ penetrates (more than tol); over n_random random legal poses (sample(rng) -> qpos) no pair penetrates in more+ than `structural` of them (a mount overlap: exclude it with a reason)."""+ import numpy as np+ import mujoco as mj+ d = mj.MjData(m)+ pairs = [i for i in range(m.npair) if is_tag(mj.mj_id2name(m, mj.mjtObj.mjOBJ_PAIR, i), tag)]+ gname = lambda g: mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, int(g))+ dist = lambda i, cut: mj.mj_geomDistance(m, d, int(m.pair_geom1[i]), int(m.pair_geom2[i]), cut, None)+ probs = []+ d.qpos[:] = rest_qpos+ mj.mj_kinematics(m, d)+ rest_pen, closest = [], (None, 1.0)+ for i in pairs:+ x = dist(i, 0.05)+ if x < closest[1]:+ closest = ((gname(m.pair_geom1[i]), gname(m.pair_geom2[i])), x)+ if x < -tol:+ rest_pen.append((gname(m.pair_geom1[i]), gname(m.pair_geom2[i]), round(float(x), 4)))+ for a, b, x in rest_pen:+ probs.append(f"at rest {a} x {b} penetrate by {-x * 100:.2f} cm (fix the rest pose or exclude the pair "+ "with a reason)")+ rng = np.random.default_rng(seed)+ cnt = np.zeros(len(pairs), int)+ any_hit = 0+ for _ in range(n_random):+ d.qpos[:] = sample(rng)+ mj.mj_kinematics(m, d)+ hit = False+ for k, i in enumerate(pairs):+ if dist(i, 0.01) < -tol:+ cnt[k] += 1+ hit = True+ any_hit += hit+ for k, i in enumerate(pairs):+ if cnt[k] > structural * n_random:+ probs.append(f"{gname(m.pair_geom1[i])} x {gname(m.pair_geom2[i])} penetrate in {cnt[k]} of {n_random} "+ "random legal poses: a structural overlap (exclude it with a reason)")+ report = {"pairs": len(pairs), "rest_penetrating": rest_pen,+ "rest_closest": [list(closest[0] or ()), round(float(closest[1]), 4)],+ "random_poses": n_random, "random_poses_with_self_contact": int(any_hit),+ "most_frequent": sorted(([gname(m.pair_geom1[i]), gname(m.pair_geom2[i]), int(cnt[k])]+ for k, i in enumerate(pairs) if cnt[k]), key=lambda x: -x[2])[:5]}+ return probs, report+++def configurations():+ """The hands a library robot is checked with: none, then every hand of bodies/hands/hands.toml on the right+ wrist, with its status (a "ready" hand fails the check, a "draft" hand only warns)."""+ import tomllib+ hands = tomllib.loads((HERE / "hands" / "hands.toml").read_text())+ return [(None, "ready")] + [(h, v.get("status", "draft")) for h, v in hands.items()]+++def compiled(B, hand, other_hand=None, **kw):+ """One library robot (prefix A_) alone in an empty world: (model, info)."""+ import mujoco as mj+ root = ET.Element("mujoco", model="selfcol_check")+ ET.SubElement(root, "compiler", angle="radian", autolimits="true")+ ET.SubElement(root, "option", timestep="0.001")+ for sec in ("default", "asset", "worldbody"):+ ET.SubElement(root, sec)+ if other_hand:+ kw["other_hand"] = other_hand+ info = B.mount(root, "A_", (0.0, 0.0, 0.0), 0.0, hand=hand, **kw)+ return mj.MjModel.from_xml_string(ET.tostring(root, encoding="unicode")), info+++def check_body(name, n_random=200) -> tuple[list, list, dict]:+ """(failures, warnings, report) of one library robot: its declaration is used (no unused exclusion), and in+ every configuration the model passes check_model at the rest pose and over random legal poses."""+ import mujoco as mj+ sys.path.insert(0, str(HERE.parent))+ from bodies import load_body+ B = load_body(name)+ fails, warns, rep = [], [], {}+ unused = None+ for hand, status in configurations():+ m, info = compiled(B, hand)+ d = mj.MjData(m)+ rig = B.rig(m, "A_", hand=hand)+ rig.place(d, rig.rest)+ q0 = d.qpos.copy()+ probs, r = check_model(m, info["selfcol_tag"], q0, rig_sampler(rig, m, q0), n_random=n_random)+ rep[hand or "none"] = r+ u = set(map(tuple, info["selfcol_unused"]))+ unused = u if unused is None else unused & u # unused with every hand+ for p in probs:+ (fails if status == "ready" else warns).append(f"{name} hand={hand or 'none'}: {p}")+ if r["pairs"] == 0:+ fails.append(f"{name} hand={hand or 'none'}: no self-collision pair")+ for u in sorted(unused or ()):+ fails.append(f"{name}: exclusion {list(u)} matches no geom pair (remove it)")+ return fails, warns, rep+++def main(argv=None):+ import argparse+ import json+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("cmd", choices=["check", "pairs", "scene"])+ ap.add_argument("robots", nargs="*")+ ap.add_argument("--random", type=int, default=200)+ ap.add_argument("--json")+ a = ap.parse_args(argv)+ sys.path.insert(0, str(HERE.parent))+ from bodies import BODIES+ if a.cmd == "scene": # robots = sport directories: write their scenes' generated blocks+ for sd in a.robots:+ for line in write_sport_scenes(Path(sd)):+ print(line)+ return 0+ robots = a.robots or list(BODIES)+ if a.cmd == "pairs":+ from bodies import load_body+ for r in robots:+ B = load_body(r)+ root = ET.Element("mujoco")+ for sec in ("default", "asset", "worldbody"):+ ET.SubElement(root, sec)+ p = B.mount(root, "", (0.0, 0.0, 0.0), 0.0, hand="paddle")["selfcol_plan"]+ print(f"== {r}: {p.summary()}")+ for x in p.pairs:+ print(f" pair {x[4]:13s} {x[2]} / {x[0]} x {x[3]} / {x[1]}")+ for x in p.excluded:+ print(f" excl {x[0]} x {x[1]}: {x[2]}")+ return 0+ allf, out = [], {}+ for r in robots:+ f, w, rep = check_body(r, a.random)+ out[r] = {"failures": f, "warnings": w, "report": rep}+ for x in w:+ print("WARN [self-collision]", x)+ for x in f:+ print("FAIL [self-collision]", x)+ print(f"self-collision {r}: " + ", ".join(f"{h}: {v['pairs']} pairs, {v['random_poses_with_self_contact']}/"+ f"{v['random_poses']} random poses in contact"+ for h, v in rep.items()) + ("" if f else "; ok"))+ allf += f+ if a.json:+ Path(a.json).write_text(json.dumps(out, indent=1))+ return 1 if allf else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/servo.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/servo.pynew file mode 100644index 0000000000..7922966b66--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/servo.py@@ -0,0 +1,620 @@+"""The robot library's one trusted limit / servo path (bodies/README.md "限位与伺服").++Every robot of the library sends its commands through this module, and nothing else writes a library robot's+actuators: a robot's `body.py` builds its servo here (`Servo`, `Actuators`, `PlanarBase`, `WalkCommand`) from its+`body.toml`, and a sport drives the robot through the robot's rig (`rig.apply`, `rig.begin_step`) or, for the+fixed-base arms of the library (bodies/franka_panda, franka_fr3, kuka_iiwa14), through `bodies/limits.py`'s+`JerkLimiter` and `TorqueRateLimiter` (the primitives this module composes). `ci_checks/check-robot-limits.py` fails a+sport that references a library robot without going through these (or that defines or patches its own limiter).++The real limits are binding (user decision 2026-10-08, "B0"): the values the manufacturer's controller enforces (SDK)+over the URDF's, never unlimited; an unpublished value is a labelled estimate in body.toml ([limits.<group>.source]+says which). What this module enforces, per layer:++ command `Servo.check` / the rigs' `check`: a 10 ms target row inside the ranges, within the speed limits from+ the row before, and (given the row before that) within the acceleration limits; walking commands+ clipped to the real joystick range and rate-limited (`WalkCommand`)+ setpoint every 1 ms physics step the reference (the 10 ms targets, interpolated) passes a jerk-limited setpoint+ generator (`SetpointGenerator`, limits.JerkLimiter's cascade and braking law, which holds for any ratio+ of acceleration to jerk, for joints and joint-like coordinates; `PlanarBase` for a planar base,+ per axis in the robot's own frame like the vendors' chassis SDKs, or on the norm): the setpoint never+ exceeds the velocity, acceleration and jerk limits that body.toml declares+ output `Actuators.write`: the servo torque through the torque-rate limit (where published), the motor's+ torque-speed curve (where published: Unitree's actuator model) and the torque limit; only then+ `d.ctrl`++What it does not change: contacts, collisions and external forces (a joint pushed by a hit moves as physics says;+D9 of the audit: recorded, not prevented), the joint ranges of the MJCF.++Deterministic: plain float64 numpy, no randomness, no threads.+"""++from __future__ import annotations++import math+from dataclasses import dataclass++import numpy as np++from . import limits as AL++from .sources import QUANTITIES, REQUIRED, SOURCE_RE, TRUSTED, source_problems # noqa: F401 (stdlib only)+++# ------------------------------------------------------------------------------------------------ declarations+def _arr(v, n=None):+ if v is None:+ return None+ a = np.atleast_1d(np.asarray(v, float))+ if n is not None and a.size == 1 and n > 1:+ a = np.full(n, float(a[0]))+ return a+++def joint_limits(decl: dict, group: str, n: int | None = None, name: str | None = None) -> AL.ArmLimits:+ """The limits of one joint group of a body.toml ([limits.<group>]) as bodies/limits.py's ArmLimits (scalars+ broadcast to n joints). Missing acceleration / jerk / torque rate stay None (body.toml's source table says why)."""+ L = decl["limits"][group]+ vel = _arr(L["speed_rad_s"], n)+ n = len(vel)+ rng = L.get("range_rad")+ if rng is not None and np.ndim(rng) == 1:+ lo, hi = np.full(n, float(rng[0])), np.full(n, float(rng[1]))+ elif rng is not None:+ lo, hi = np.array([r[0] for r in rng], float), np.array([r[1] for r in rng], float)+ else:+ lo = _arr(L.get("range_lo_rad"), n) if L.get("range_lo_rad") is not None else np.full(n, -np.inf)+ hi = _arr(L.get("range_hi_rad"), n) if L.get("range_hi_rad") is not None else np.full(n, np.inf)+ return AL.ArmLimits(+ body=decl["body"]["name"] if name is None else name, model=decl["body"]["title"] + f" [{group}]",+ range_lo=lo, range_hi=hi, vel=vel, acc=_arr(L.get("accel_rad_s2"), n), jerk=_arr(L.get("jerk_rad_s3"), n),+ tau=_arr(L.get("torque_nm"), n) if L.get("torque_nm") is not None else np.full(n, np.inf),+ dtau=_arr(L.get("torque_rate_nm_s"), n), sources=dict(decl.get("sources", {})))+++def stack(parts: list[AL.ArmLimits], body: str, model: str) -> AL.ArmLimits:+ """Several limit groups as one (the order of `parts`); a quantity one part lacks becomes None for all, unless+ every part has it."""+ cat = lambda k: None if any(getattr(p, k) is None for p in parts) else np.concatenate([getattr(p, k) for p in parts])+ return AL.ArmLimits(body, model, cat("range_lo"), cat("range_hi"), cat("vel"), cat("acc"), cat("jerk"),+ cat("tau"), cat("dtau"), parts[0].sources if parts else {})+++# ------------------------------------------------------------------------------------------------ output stage+class Actuators:+ """The output stage of a group of motors: servo torques -> torque-rate limit (where declared) -> the motors'+ torque-speed curve (where declared) -> the torque limit -> d.ctrl. The only writer of a library robot's motors.++ envelope: per joint (X1, X2, Y1, Y2) of Unitree's actuator model (unitree_rl_lab unitree_actuators.py): a torque+ along the motion is limited to Y1 below X1 rad/s, falling linearly to 0 at X2 (the motor cannot drive faster); a+ torque against the motion (braking) to Y2 at any speed, as the curve's drawing in unitree_actuators.py shows it+ (its code also fades the braking torque beyond X1, which lets a joint pushed past X2 run away unbraked).++ thermal (optional; motor_model() builds it from body.toml [motors.thermal]): (rated, T, derate_from) per motor:+ an I^2 t state h per motor, dh/dt = ((tau / rated)^2 - h) / T (h = 1: the winding at its limit after a long+ time at the rated torque); the torque limit falls linearly from tau_max at h = derate_from to the rated torque at+ h = 1 (a drive's I^2 t foldback). h starts at 0 (a cold motor) and is never reset by reset(): heat stays with the+ motor (cool_down() for a new match).+ power (optional; [motors.bus]): (groups, watts): per group of motors (one robot's), the summed positive+ mechanical power tau * qd is capped at watts; above it the torques doing positive work are scaled down together+ (the battery and the drives cannot deliver more).+ """++ def __init__(self, model, aid, vadr, tau_max, dt, dtau=None, envelope=None, thermal=None, power=None):+ self.aid, self.vadr = np.asarray(aid, int), np.asarray(vadr, int)+ n = len(self.aid)+ self.dt = float(dt)+ self.tau_max = np.minimum(np.asarray(tau_max, float), model.actuator_ctrlrange[self.aid, 1])+ self.step_max = None if dtau is None else np.asarray(dtau, float) * float(dt)+ self.env = None if envelope is None else tuple(np.asarray(e, float) for e in envelope)+ self.thermal = None+ if thermal is not None:+ rated, T, frm = (np.broadcast_to(np.asarray(x, float), (n,)).copy() for x in thermal)+ self.thermal = (np.minimum(rated, self.tau_max), T, frm)+ self.power = None+ if power is not None:+ groups, watts = power+ self.power = ([np.asarray(g, int) for g in groups], float(watts))+ self.h = np.zeros(n)+ self.tau = np.zeros(n)+ self.stats = dict(steps=0, torque_clipped=0, rate_clipped=0, envelope_clipped=0, thermal_derated=0,+ power_capped=0)++ def reset(self, tau=None):+ self.tau = np.zeros(len(self.aid)) if tau is None else np.clip(np.asarray(tau, float), -self.tau_max,+ self.tau_max)++ def cool_down(self):+ """The thermal state of cold motors (a new match)."""+ self.h = np.zeros(len(self.aid))++ def thermal_limit(self):+ """The torque limit per motor now (the I^2 t foldback; tau_max without a thermal model)."""+ if self.thermal is None:+ return self.tau_max+ rated, _, frm = self.thermal+ x = np.clip((self.h - frm) / np.maximum(1.0 - frm, 1e-9), 0.0, 1.0)+ return self.tau_max - (self.tau_max - rated) * x++ def limit(self, qd):+ """The torque limit per motor at joint speeds qd for torques along (+) the motion: (along, against)."""+ if self.env is None:+ return self.tau_max, self.tau_max+ X1, X2, Y1, Y2 = self.env+ a = np.abs(qd)+ with np.errstate(invalid="ignore"): # X1 = X2 = inf: no curve for that joint+ fall = np.clip(1.0 - (a - X1) / np.maximum(X2 - X1, 1e-9), 0.0, 1.0)+ k = np.where(a < X1, 1.0, fall)+ return np.minimum(Y1 * k, self.tau_max), np.minimum(Y2, self.tau_max)++ def write(self, d, tau):+ t = np.asarray(tau, float)+ st = self.stats+ st["steps"] += 1+ if self.step_max is not None:+ c = np.clip(t, self.tau - self.step_max, self.tau + self.step_max)+ st["rate_clipped"] += int(np.any(c != t))+ t = c+ if self.env is not None:+ qd = d.qvel[self.vadr]+ along, against = self.limit(qd)+ lim = np.where(t * qd > 0, along, against)+ c = np.clip(t, -lim, lim)+ st["envelope_clipped"] += int(np.any((np.abs(c) < np.abs(t) - 1e-12) & (lim < self.tau_max)))+ t = c+ c = np.clip(t, -self.tau_max, self.tau_max)+ st["torque_clipped"] += int(np.any(c != t))+ t = c+ if self.thermal is not None:+ th = self.thermal_limit()+ c = np.clip(t, -th, th)+ st["thermal_derated"] += int(np.any(c != t))+ t = c+ if self.power is not None:+ qd = d.qvel[self.vadr]+ groups, watts = self.power+ p = np.maximum(t * qd, 0.0)+ capped = False+ for g in groups:+ ps = float(p[g].sum())+ if ps > watts:+ pos = g[p[g] > 0]+ t[pos] = t[pos] * (watts / ps)+ capped = True+ st["power_capped"] += int(capped)+ if self.thermal is not None:+ rated, T, _ = self.thermal+ self.h = self.h + self.dt * ((t / rated) ** 2 - self.h) / T+ self.tau = t+ d.ctrl[self.aid] = t+ return t+++def unitree_envelope(decl: dict, joint_keys: list):+ """(X1, X2, Y1, Y2) arrays for joints named by their body.toml [motors.assign] keys (None: a joint without a+ motor curve, e.g. a planar copy's base), or None when the body declares no [motors]."""+ mot = decl.get("motors")+ if not mot:+ return None+ inf = dict(X1=np.inf, X2=np.inf, Y1=np.inf, Y2=np.inf)+ curves = [inf if k is None else mot[mot["assign"][k]] for k in joint_keys]+ return tuple(np.array([c[x] for c in curves], float) for x in ("X1", "X2", "Y1", "Y2"))+++def motor_model(decl: dict, joint_keys: list, groups=None) -> dict:+ """Actuators keyword arguments of a body's motor model from body.toml [motors]: the torque-speed envelope+ (unitree_envelope), the thermal derating ([motors.thermal]: rated_frac of the torque limit is the continuous+ torque, the peak torque from cold lasts peak_s before the foldback ends at the rated torque, the foldback starts+ at derate_from) and the bus power cap per group of motors ([motors.bus] power_w; groups: index arrays into+ joint_keys, one per robot; default all one group). Only the parts the body declares."""+ mot = decl.get("motors") or {}+ kw = dict(envelope=unitree_envelope(decl, joint_keys))+ th = mot.get("thermal")+ if th:+ tau = np.array([np.nan if k is None else _leg_torque(decl, k) for k in joint_keys], float)+ rf = float(th["rated_frac"])+ T = float(th["peak_s"]) / -math.log(1.0 - rf ** 2) # h(peak_s) = 1 at the peak torque from cold+ kw["thermal"] = (rf * tau, T, float(th["derate_from"]))+ bus = mot.get("bus")+ if bus:+ kw["power"] = ([np.arange(len(joint_keys))] if groups is None else groups, float(bus["power_w"]))+ return kw+++def _leg_torque(decl: dict, key: str) -> float:+ """The torque limit of a motor by its [motors.assign] key (the [motors] curve's Y1, the URDF torque)."""+ mot = decl["motors"]+ return float(mot[mot["assign"][key]]["Y1"])+++# ------------------------------------------------------------------------------------------------ setpoints+brake_speed = AL.brake_speed # the jerk-limited stopping speed (bodies/limits.py; the same law, one copy)+++class SetpointGenerator:+ """The library's setpoint generator at the physics rate: per coordinate a third-order state (q, qd, qdd) that+ follows a reference (position r, velocity rd) and never exceeds |qd| <= vel, |qdd| <= acc, |dqdd/dt| <= jerk.++ limits.JerkLimiter's law (velocity loop: the sqrt law at the jerk limit; the velocity guard; the jerk clipped;+ the reference velocity as feed-forward; a position loop that brakes within both the acceleration and the jerk+ limit, brake_speed), with the body's own jerk limit at every step (no per-step jerk_cap). A plain sqrt law on the+ position, which assumes the deceleration is there at once, overshoots and rings wherever the jerk needs long to+ build the acceleration: an SDK's slow jerk (the R1 Pro's arm: 4.5 rad/s^2 at 4.5 rad/s^3) and equally the+ Franka's when its jerk is capped by the torque rate at the pose (limits.jerk_caps(): a few hundred rad/s^3 on+ the shoulder), which is why limits.JerkLimiter uses this law too since 2026-10-11 (since 2026-10-12 both take+ the coast distance relative to the reference's velocity, qd - rd). The velocity bound runs one step of+ acceleration and jerk below the limit (the discrete steps' overshoot). Without declared acceleration /+ jerk (Unitree: none published) it is a velocity limiter with a 17 ms lag. Deterministic (float64 numpy)."""++ KP, KV, BRAKE = AL.JerkLimiter.KP, AL.JerkLimiter.KV, AL.JerkLimiter.BRAKE++ def __init__(self, lim: AL.ArmLimits, dt: float, q0=None):+ self.lim, self.dt = lim, float(dt)+ n = lim.n+ self.A = lim.acc if lim.acc is not None else np.full(n, 1e6)+ self.J = lim.jerk if lim.jerk is not None else np.full(n, 1e9)+ margin = (lim.jerk * self.dt ** 2 if lim.jerk is not None else 0.0) + \+ (lim.acc * self.dt if lim.acc is not None else 0.0)+ self.V = np.maximum(lim.vel - margin, 0.5 * lim.vel)+ self.reset(np.zeros(n) if q0 is None else q0)++ def reset(self, q, qd=None, qdd=None):+ n = self.lim.n+ self.q = np.asarray(q, float).copy()+ self.qd = np.zeros(n) if qd is None else np.clip(np.asarray(qd, float), -self.V, self.V)+ self.qdd = np.zeros(n) if qdd is None else np.asarray(qdd, float).copy()++ def step(self, r, rd=None):+ dt, V, A, J = self.dt, self.V, self.A, self.J+ r = np.asarray(r, float)+ rd = np.zeros_like(r) if rd is None else np.asarray(rd, float)+ e = r - self.q+ # the position loop sees the error left once the present acceleration has ramped to zero at the jerk limit+ # (the distance it still covers, relative to the reference moving at rd): with a slow jerk that distance is+ # what makes a plain sqrt law overshoot; taken with qd alone a moving reference looked overshot and the+ # setpoint braked early (limits.JerkLimiter, 2026-10-12)+ t = np.abs(self.qdd) / J+ e = e - ((self.qd - rd) * t + 0.5 * self.qdd * t * t - np.sign(self.qdd) * J * t ** 3 / 6.0)+ v_pos = np.sign(e) * np.minimum(self.KP * np.abs(e), brake_speed(np.abs(e), self.BRAKE * A, J))+ v_cmd = np.clip(rd + v_pos, -V, V)+ a_cmd = np.clip(AL._sqrt_ctrl(v_cmd - self.qd, self.KV, J), -A, A)+ room_up, room_dn = np.maximum(0.0, V - self.qd), np.maximum(0.0, V + self.qd)+ a_cmd = np.clip(a_cmd, -np.sqrt(2.0 * J * room_dn), np.sqrt(2.0 * J * room_up))+ j = np.clip((a_cmd - self.qdd) / dt, -J, J)+ self.q = self.q + self.qd * dt + 0.5 * self.qdd * dt * dt + j * dt ** 3 / 6.0+ self.qd = self.qd + self.qdd * dt + 0.5 * j * dt * dt+ self.qdd = self.qdd + j * dt+ return self.q, self.qd, self.qdd+++# ------------------------------------------------------------------------------------------------ planar base+@dataclass+class BaseLimits:+ """A planar base: speed / acceleration / jerk of the translation (per axis of the robot's own frame, `axes`, or+ on the norm, `norm`) and of the yaw. From body.toml [limits.base]."""++ speed: np.ndarray # (2,) or scalar for norm+ accel: np.ndarray+ jerk: np.ndarray+ yaw_rate: float+ yaw_accel: float+ yaw_jerk: float+ mode: str = "axes"++ @classmethod+ def of(cls, L: dict) -> "BaseLimits":+ mode = L.get("mode", "norm")+ f = (lambda k: np.asarray(L[k], float)) if mode == "axes" else (lambda k: float(np.max(L[k])))+ return cls(f("speed_m_s"), f("accel_m_s2"), f("jerk_m_s3"), float(L["yaw_rate_rad_s"]),+ float(L["yaw_accel_rad_s2"]), float(L["yaw_jerk_rad_s3"]), mode)++ def table(self) -> dict:+ r = lambda x: np.round(np.asarray(x, float), 4).tolist()+ return dict(mode=self.mode, speed_m_s=r(self.speed), accel_m_s2=r(self.accel), jerk_m_s3=r(self.jerk),+ yaw_rate_rad_s=self.yaw_rate, yaw_accel_rad_s2=self.yaw_accel, yaw_jerk_rad_s3=self.yaw_jerk)+++def _clipn(v, lim, norm):+ if not norm:+ return np.clip(v, -lim, lim)+ n = float(np.linalg.norm(v))+ return v if n <= lim or n == 0.0 else v * (lim / n)+++def _sqrtn(err, k, dlim, norm):+ """the sqrt law (limits._sqrt_ctrl) per component, or on the vector's length along its direction"""+ if not norm:+ return AL._sqrt_ctrl(err, k, dlim)+ n = float(np.linalg.norm(err))+ if n == 0.0:+ return np.zeros_like(err)+ return err / n * float(AL._sqrt_ctrl(np.array([n]), k, dlim)[0])+++class PlanarBase:+ """The jerk-limited setpoint generator of a planar base (x, y in the mount frame; yaw). The translation is limited+ in the robot's own frame (rotated by the setpoint's yaw), per axis ("axes": the vendors' chassis SDKs limit the+ commanded vx, vy, wz separately) or on the norm ("norm"); the yaw as one joint. The same cascade as+ limits.JerkLimiter (position -> velocity -> acceleration -> jerk, sqrt laws, the velocity guard)."""++ KP, KV, BRAKE = AL.JerkLimiter.KP, AL.JerkLimiter.KV, AL.JerkLimiter.BRAKE++ def __init__(self, lim: BaseLimits, dt: float):+ self.lim, self.dt = lim, float(dt)+ self.norm = lim.mode != "axes"+ self.reset(np.zeros(3))++ def reset(self, q, qd=None):+ """q: (x, y, yaw) in the mount frame; qd: their time derivatives (mount frame)."""+ q = np.asarray(q, float)+ qd = np.zeros(3) if qd is None else np.asarray(qd, float)+ self.p, self.yaw = q[:2].copy(), float(q[2])+ c, s = math.cos(self.yaw), math.sin(self.yaw)+ self.v = np.array([c * qd[0] + s * qd[1], -s * qd[0] + c * qd[1]]) # body frame+ self.a = np.zeros(2)+ self.w, self.wd = float(qd[2]), 0.0++ def state(self):+ """(q, qd, qdd) in the mount frame: x, y, yaw."""+ c, s = math.cos(self.yaw), math.sin(self.yaw)+ R = np.array([[c, -s], [s, c]])+ v, a = R @ self.v, R @ self.a+ return np.r_[self.p, self.yaw], np.r_[v, self.w], np.r_[a, self.wd]++ def _axis(self, e, rd, v, a, V, A, J, norm):+ dt = self.dt+ Vg = V - J * dt * dt - A * dt # one step of jerk and of acceleration (discrete overshoot)+ if norm: # the error left once the acceleration has ramped to zero+ na = float(np.linalg.norm(a)) # (relative to the reference moving at rd)+ if na > 0.0:+ t = na / J+ e = e - ((v - rd) * t + 0.5 * a * t * t - a / na * J * t ** 3 / 6.0)+ else:+ t = np.abs(a) / J+ e = e - ((v - rd) * t + 0.5 * a * t * t - np.sign(a) * J * t ** 3 / 6.0)+ if norm:+ n_e = float(np.linalg.norm(e))+ sp = min(self.KP * n_e, float(brake_speed(n_e, self.BRAKE * A, J)))+ v_pos = e / n_e * sp if n_e > 0 else np.zeros_like(e)+ else:+ v_pos = np.sign(e) * np.minimum(self.KP * np.abs(e), brake_speed(np.abs(e), self.BRAKE * A, J))+ v_cmd = _clipn(rd + v_pos, Vg, norm)+ a_cmd = _clipn(_sqrtn(v_cmd - v, self.KV, J, norm), A, norm)+ if norm: # the velocity guard along the motion+ sp = float(np.linalg.norm(v))+ if sp > 0.0:+ u = v / sp+ ap = float(a_cmd @ u)+ cap = math.sqrt(2.0 * J * max(0.0, Vg - sp))+ if ap > cap:+ a_cmd = a_cmd - (ap - cap) * u+ else:+ room_up, room_dn = np.maximum(0.0, Vg - v), np.maximum(0.0, Vg + v)+ a_cmd = np.clip(a_cmd, -np.sqrt(2.0 * J * room_dn), np.sqrt(2.0 * J * room_up))+ j = _clipn((a_cmd - a) / dt, J, norm)+ return j++ def step(self, r, rd=None):+ """advance one step towards the reference r = (x, y, yaw) moving at rd; returns (q, qd, qdd) (mount frame)"""+ L, dt = self.lim, self.dt+ r = np.asarray(r, float)+ rd = np.zeros(3) if rd is None else np.asarray(rd, float)+ jw = self._axis(np.array([r[2] - self.yaw]), np.array([rd[2]]), np.array([self.w]), np.array([self.wd]),+ L.yaw_rate, L.yaw_accel, L.yaw_jerk, False)[0]+ c, s = math.cos(self.yaw), math.sin(self.yaw)+ Rt = np.array([[c, s], [-s, c]]) # mount -> body frame+ e_b, rd_b = Rt @ (r[:2] - self.p), Rt @ rd[:2]+ j = self._axis(e_b, rd_b, self.v, self.a, L.speed, L.accel, L.jerk, self.norm)+ v_new = self.v + self.a * dt + 0.5 * j * dt * dt+ dp_b = self.v * dt + 0.5 * self.a * dt * dt + j * dt ** 3 / 6.0+ self.a = self.a + j * dt+ yaw_mid = self.yaw + 0.5 * self.w * dt+ cm, sm = math.cos(yaw_mid), math.sin(yaw_mid)+ self.p = self.p + np.array([cm * dp_b[0] - sm * dp_b[1], sm * dp_b[0] + cm * dp_b[1]])+ self.v = v_new+ self.yaw += self.w * dt + 0.5 * self.wd * dt * dt + jw * dt ** 3 / 6.0+ self.w += self.wd * dt + 0.5 * jw * dt * dt+ self.wd += jw * dt+ return self.state()+++# ------------------------------------------------------------------------------------------------ the servo+class Servo:+ """The servo of one robot's commanded coordinates x (a rig's controlled vector u, or the part of it that is+ positions) in a compiled model: joint targets q = M x + c.++ Every physics step (`track`): the reference (r, rd) passes the setpoint generator (SetpointGenerator on the joint+ coordinates `jix`, PlanarBase on the base coordinates `bix` = (x, y, yaw)); the joint setpoint (q_sp, qd_sp,+ qdd_sp) = M (x_sp, xd_sp, xdd_sp) + c; the torque tau = kp (q_sp - q) + kd (qd_sp - qd) + bias (gravity, Coriolis)+ + M(q) qdd_sp (inertia feed-forward); then the output stage (Actuators.write). Coordinates of x that map to no+ joint (all-zero columns of M, e.g. a legged robot's walking command) are not servoed here."""++ def __init__(self, model, qadr, vadr, act: Actuators, M, c, kp, kd, dt, joint_lim: AL.ArmLimits | None,+ jix=(), base: BaseLimits | None = None, bix=(), feedforward=True):+ self.m = model+ self.qadr, self.vadr = np.asarray(qadr, int), np.asarray(vadr, int)+ self.act = act+ self.M, self.c = np.asarray(M, float), np.asarray(c, float)+ self.kp, self.kd = np.asarray(kp, float), np.asarray(kd, float)+ self.dt = float(dt)+ self.jix, self.bix = np.asarray(jix, int), np.asarray(bix, int)+ self.n = self.M.shape[1]+ self.lim = joint_lim+ self.jl = SetpointGenerator(joint_lim, dt) if len(self.jix) else None+ self.base = PlanarBase(base, dt) if len(self.bix) else None+ self.ff = feedforward+ self.ready = False+ self._acc = np.zeros(model.nv)+ self._f = np.zeros(model.nv)+ self.x = np.zeros(self.n)+ self.xd = np.zeros(self.n)+ self.xdd = np.zeros(self.n)+ self.peak = dict(vel=np.zeros(self.n), acc=np.zeros(self.n)) # |setpoint| peaks (conformance)++ def reset(self, x, xd=None):+ """The setpoint generator at x (moving at xd), at rest in acceleration: after a teleport, at the start."""+ x = np.asarray(x, float)+ xd = np.zeros(self.n) if xd is None else np.asarray(xd, float)+ if self.jl is not None:+ self.jl.reset(x[self.jix], xd[self.jix])+ if self.base is not None:+ self.base.reset(x[self.bix], xd[self.bix])+ self.x, self.xd, self.xdd = x.copy(), xd.copy(), np.zeros(self.n)+ self.act.reset()+ self.ready = True++ def setpoint(self, r, rd):+ """one step of the setpoint generator towards (r, rd): (x_sp, xd_sp, xdd_sp)"""+ r, rd = np.asarray(r, float), np.asarray(rd, float)+ x, xd, xdd = r.copy(), rd.copy(), np.zeros(self.n)+ if self.jl is not None:+ q, qd, qdd = self.jl.step(r[self.jix], rd[self.jix])+ x[self.jix], xd[self.jix], xdd[self.jix] = q, qd, qdd+ if self.base is not None:+ q, qd, qdd = self.base.step(r[self.bix], rd[self.bix])+ x[self.bix], xd[self.bix], xdd[self.bix] = q, qd, qdd+ self.x, self.xd, self.xdd = x, xd, xdd+ np.maximum(self.peak["vel"], np.abs(xd), out=self.peak["vel"])+ np.maximum(self.peak["acc"], np.abs(xdd), out=self.peak["acc"])+ return x, xd, xdd++ def track(self, d, r, rd, extra_tau=None):+ """one physics step: setpoint, servo torque, output stage (writes d.ctrl of this servo's motors)"""+ if not self.ready:+ raise RuntimeError("servo not reset (rig.place / rig.sync first)")+ x, xd, xdd = self.setpoint(r, rd)+ q_sp, qd_sp, qdd_sp = self.M @ x + self.c, self.M @ xd, self.M @ xdd+ tau = self.kp * (q_sp - d.qpos[self.qadr]) + self.kd * (qd_sp - d.qvel[self.vadr]) + d.qfrc_bias[self.vadr]+ if self.ff:+ import mujoco as mj+ self._acc[:] = 0.0+ self._acc[self.vadr] = qdd_sp+ mj.mj_mulM(self.m, d, self._f, self._acc)+ tau = tau + self._f[self.vadr]+ if extra_tau is not None:+ tau = tau + extra_tau+ return self.act.write(d, tau)+++def check_row(u, u_prev, u_prev2, LO, HI, VEL, ACC, dt, base: BaseLimits | None = None, tol=1e-6):+ """A target row of a controlled vector against the limits: the ranges, the per-step speeds (|du| <= VEL dt) and,+ given u_prev2, the accelerations (|second difference| <= ACC dt^2). base: the limits of a planar base at u[0:3]+ (x, y, yaw): its translation checked on the norm, or per axis in the robot's frame (rotated by u_prev's yaw).+ Returns None or the reason."""+ u, up = np.asarray(u, float), np.asarray(u_prev, float)+ LO, HI, VEL = np.asarray(LO, float), np.asarray(HI, float), np.asarray(VEL, float)+ if u.shape != LO.shape or not np.all(np.isfinite(u)):+ return f"a target must be {len(LO)} finite numbers"+ bad = (u < LO - 1e-9) | (u > HI + 1e-9)+ if bad.any():+ return f"outside the range at {np.nonzero(bad)[0].tolist()}"+ du = u - up+ dd = None if u_prev2 is None else du - (up - np.asarray(u_prev2, float))+ over = np.abs(du) > VEL * dt * (1 + tol) + 1e-12+ if base is not None:+ over[0:2] = False+ why = _base_problem(du[0:2], up[2], base.speed, base.mode, dt, tol)+ if why:+ return "the base speed limit"+ if over.any():+ return f"a per-step speed limit at {np.nonzero(over)[0].tolist()}"+ if dd is not None and ACC is not None:+ over = np.abs(dd) > np.asarray(ACC, float) * dt * dt * (1 + tol) + 1e-12+ if base is not None:+ over[0:2] = False+ if _base_problem(dd[0:2], up[2], base.accel, base.mode, dt * dt, tol):+ return "the base acceleration limit"+ if over.any():+ return f"an acceleration limit at {np.nonzero(over)[0].tolist()}"+ return None+++def _base_problem(dxy, yaw, lim, mode, scale, tol):+ if mode != "axes":+ return math.hypot(*dxy) > float(np.max(lim)) * scale * (1 + tol) + 1e-12+ c, s = math.cos(yaw), math.sin(yaw)+ b = np.array([c * dxy[0] + s * dxy[1], -s * dxy[0] + c * dxy[1]])+ return bool(np.any(np.abs(b) > np.asarray(lim, float) * scale * (1 + tol) + 1e-12))+++# ------------------------------------------------------------------------------------------------ rig layouts+def wheeled_layout(model, rig, decl: dict, phys_dt: float):+ """The servo of a rig with the wheeled humanoid's controlled vector u = [base x, y, yaw, lift, waist, arm 0..6]+ (bodies/wheeled_humanoid, galaxea_r1pro, tianji_marvin_pro): the joint coordinates (lift, waist, arm: those that+ move a joint) through SetpointGenerator with [limits.lift / waist / arm]'s speed, acceleration and jerk, the base+ through PlanarBase ([limits.base]; none when its kind is "absent"). Returns (servo, ACC: the per-coordinate+ acceleration limits for check_row, the base limits or None)."""+ L = decl["limits"]+ moves = np.any(np.abs(rig.M) > 0, axis=0)+ jix = [k for k in range(3, 12) if moves[k]]+ has_base = L["base"].get("kind") != "absent" and moves[0:3].all()+ base = BaseLimits.of(L["base"]) if has_base else None+ group = {3: "lift", 4: "waist"}+ q = lambda k, key: (_arr(L[group.get(k, "arm")].get(key), 7) if group.get(k, "arm") == "arm"+ else _arr(L[group[k]].get(key)))+ acc = np.full(12, 0.0)+ jerk = np.full(12, 0.0)+ for k in range(3, 12):+ a, j = q(k, "accel_rad_s2"), q(k, "jerk_rad_s3")+ acc[k] = np.inf if a is None else (a[k - 5] if k >= 5 else a[0])+ jerk[k] = np.inf if j is None else (j[k - 5] if k >= 5 else j[0])+ if base is not None:+ acc[0:2] = base.accel if base.mode == "axes" else float(base.accel)+ acc[2] = base.yaw_accel+ ji = np.array(jix, int)+ fin = lambda x: None if not np.all(np.isfinite(x)) else x+ lim = AL.ArmLimits(decl["body"]["name"], decl["body"]["title"] + " [u]", rig.LO[ji], rig.HI[ji], rig.VEL[ji],+ fin(acc[ji]), fin(jerk[ji]), np.full(len(ji), np.inf), None, dict(decl.get("sources", {})))+ act = Actuators(model, rig.aid, rig.vadr, rig.tau_lim, phys_dt)+ servo = Servo(model, rig.qadr, rig.vadr, act, rig.M, rig.c, rig.kp, rig.kd, phys_dt, lim, jix=jix, base=base,+ bix=(0, 1, 2) if base is not None else ())+ return servo, acc, base+++def legged_layout(model, rig, decl: dict, phys_dt: float, upper_keys: list, leg_keys: list, planar: dict | None):+ """The servos of a legged rig (bodies/unitree_g1, unitree_h1): the upper body's commanded coordinates (u[3:]:+ waist and arm joints) through SetpointGenerator at the joints' speed limits (Unitree publishes no acceleration+ or jerk: none declared, the motor curves bound them), the planar copy's base (planar: the [walk.planning] model)+ through PlanarBase; the output stages with the motors' torque-speed curves ([motors]: upper_keys / leg_keys name+ each joint's [motors.assign] entry; None = no curve). Returns (upper servo, legs Actuators or None, ACC)."""+ moves = np.any(np.abs(rig.M) > 0, axis=0)+ jix = [k for k in range(3, 12) if moves[k]]+ ji = np.array(jix, int)+ lim = AL.ArmLimits(decl["body"]["name"], decl["body"]["title"] + " [u]", rig.LO[ji], rig.HI[ji], rig.VEL[ji],+ None, None, np.full(len(ji), np.inf), None, dict(decl.get("sources", {})))+ base = None+ if planar is not None:+ base = BaseLimits(float(planar["speed_m_s"]), float(planar["accel_m_s2"]), 25.0 * float(planar["accel_m_s2"]),+ float(planar["yaw_rate_rad_s"]), float(planar["yaw_accel_rad_s2"]),+ 25.0 * float(planar["yaw_accel_rad_s2"]), "norm")+ env = unitree_envelope(decl, upper_keys)+ act = Actuators(model, rig.aid, rig.vadr, rig.tau_lim, phys_dt, envelope=env)+ servo = Servo(model, rig.qadr, rig.vadr, act, rig.M, rig.c, rig.kp, rig.kd, phys_dt, lim, jix=jix, base=base,+ bix=(0, 1, 2) if base is not None else ())+ legs = None+ if leg_keys:+ legs = Actuators(model, rig.laid, rig.lvadr, rig.ltau, phys_dt, envelope=unitree_envelope(decl, leg_keys))+ acc = np.full(12, np.inf)+ if base is not None:+ acc[0:2], acc[2] = base.accel, base.yaw_accel+ return servo, legs, acc+++# ------------------------------------------------------------------------------------------------ walking command+class WalkCommand:+ """A legged robot's walking command (vx, vy, wz in the robot's frame): clipped to the range the real robot's+ deployment accepts ([limits.walk] command_max: Unitree's joystick limits) and changed by at most command_accel+ per second."""++ def __init__(self, L: dict, dt: float):+ self.max = np.asarray(L["command_max"], float)+ self.step_max = np.asarray(L["command_accel"], float) * float(dt)+ self.cmd = np.zeros(3)++ def reset(self):+ self.cmd = np.zeros(3)++ def __call__(self, req):+ req = np.clip(np.asarray(req, float), -self.max, self.max)+ self.cmd = self.cmd + np.clip(req - self.cmd, -self.step_max, self.step_max)+ return self.cmddiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/sources.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/sources.pynew file mode 100644index 0000000000..c759e432d4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/sources.py@@ -0,0 +1,66 @@+"""The robot library's declaration rules (bodies/README.md "准入"), stdlib only: what bodies/servo.py, the+conformance test (bodies/conformance.py) and the CI check (ci_checks/check-robot-limits.py) agree on.++Every limit a robot declares in body.toml [limits.<group>] has a source in [limits.<group>.source]: a reference to+[sources] ("S2", "S2 x 1.5 (S5)"), or "ESTIMATE: <method>" (an unpublished value we chose, labelled), "DERIVED:+<method>" (computed from published facts), or "NOT PUBLISHED: <why>" (the quantity is not limited because nobody+publishes it; then it must have no value). Each kind of group declares the quantities of REQUIRED (a value or a NOT+PUBLISHED source); a group with kind = "absent" is a part the robot does not have.+"""+from __future__ import annotations++import re++TRUSTED = ("Servo", "Actuators", "PlanarBase", "WalkCommand", "SetpointGenerator", "JerkLimiter",+ "TorqueRateLimiter")+SOURCE_RE = re.compile(r"^(S\d+\b|ESTIMATE\b|NOT PUBLISHED\b|DERIVED\b)")+QUANTITIES = { # body.toml key -> what it is (the conformance check's list)+ "speed_rad_s": "joint speed", "accel_rad_s2": "joint acceleration", "jerk_rad_s3": "joint jerk",+ "torque_nm": "joint torque", "torque_rate_nm_s": "joint torque rate",+ "speed_m_s": "base speed", "accel_m_s2": "base acceleration", "jerk_m_s3": "base jerk",+ "yaw_rate_rad_s": "base yaw rate", "yaw_accel_rad_s2": "base yaw acceleration", "yaw_jerk_rad_s3": "base yaw jerk",+ "command_max": "walking command range", "command_accel": "walking command rate",+}+REQUIRED = { # per kind of limit group: what must be declared (a value, or a source entry saying why there is none)+ "joints": ("speed_rad_s", "accel_rad_s2", "jerk_rad_s3", "torque_nm"),+ "base": ("speed_m_s", "accel_m_s2", "jerk_m_s3", "yaw_rate_rad_s", "yaw_accel_rad_s2", "yaw_jerk_rad_s3"),+ "walk": ("command_max", "command_accel"),+ "gantry": ("speed_m_s", "accel_m_s2", "jerk_m_s3"), # linear axes, each limited on its own (per axis)+}+++def source_problems(decl: dict) -> list[str]:+ """Every declared limit has a source: [limits.<group>.source] maps each quantity of the group to a reference of+ [sources] ("S2", "S2 x 1.5 (S5)") or to "ESTIMATE: <method>", "DERIVED: <method>" or "NOT PUBLISHED: <why>";+ each kind of group declares the quantities of REQUIRED (a value, or a NOT PUBLISHED source). Returns problems."""+ out, srcs = [], set((decl.get("sources") or {}).keys())+ if not srcs:+ out.append("no [sources]")+ for g, L in (decl.get("limits") or {}).items():+ if not isinstance(L, dict):+ continue+ if "kind" not in L and not any(q in QUANTITIES for q in L):+ continue # not a limit group of joints or a base (e.g. [limits.cartesian])+ kind = L.get("kind") or ("base" if g == "base" else "walk" if g == "walk" else "gantry" if g == "gantry"+ else "joints")+ if kind == "absent": # the robot has no such part (e.g. a fixed stand's base)+ continue+ src = L.get("source")+ if not isinstance(src, dict):+ out.append(f"[limits.{g}] has no source table [limits.{g}.source]")+ continue+ for q in REQUIRED.get(kind, ()):+ if q not in L and not str(src.get(q, "")).startswith("NOT PUBLISHED"):+ out.append(f"[limits.{g}] {q}: neither a value nor 'NOT PUBLISHED: <why>' in its source table")+ for q in L:+ if q in QUANTITIES:+ s = str(src.get(q, ""))+ if not SOURCE_RE.match(s):+ out.append(f"[limits.{g}] {q}: source {s!r} is not S<k>, ESTIMATE:, DERIVED: or NOT PUBLISHED:")+ for ref in re.findall(r"\bS\d+\b", s):+ if ref not in srcs:+ out.append(f"[limits.{g}] {q}: {ref} is not in [sources]")+ for q, s in src.items():+ if str(s).startswith("NOT PUBLISHED") and q in L:+ out.append(f"[limits.{g}] {q}: has a value but its source says NOT PUBLISHED")+ return outdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/LICENSE b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/LICENSEnew file mode 100644index 0000000000..62637c8d14--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/LICENSE@@ -0,0 +1,27 @@+Copyright (c) 2016-2023 HangZhou YuShu TECHNOLOGY CO.,LTD. ("Unitree Robotics")+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++* Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/agile.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/agile.pynew file mode 100644index 0000000000..db0a773025--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/agile.py@@ -0,0 +1,145 @@+"""NVIDIA WBC-AGILE's velocity-height walking policy for the G1 (optional; body.toml [walk.agile]): a legs-only walking+and balance policy, trained while the arms and the waist moved, that a sport may choose instead of Unitree's policy+(body.py WalkPolicy, the default) or FALCON (falcon.py):++ rig = B.rig(model, prefix, hand="paddle", walker="agile")++Source: nvidia-isaac/WBC-AGILE (Apache-2.0, Copyright (c) NVIDIA CORPORATION & AFFILIATES; policy/LICENSE.agile), the+released LEAPP bundle agile/data/policy/velocity_height_g1/leapp/Velocity-Height-G1-History-v0 (S9); H. Zhao et al.,+"AGILE: A Comprehensive Workflow for Humanoid Loco-Manipulation Learning", arXiv:2603.20147. Trained with PPO in Isaac+Lab on the 29-DOF G1 (physics 200 Hz, policy 50 Hz), legs only: the waist yaw (within +-15 degrees) and the arms+moved to random targets while it stood, the waist roll and pitch held at 0; while it walked, the arms and the waist+went to their default pose (all 0), so walking with the arms elsewhere (the library's rest pose too) or the waist+turned further is outside its training. policy/agile_g1_velocity_height.npz holds the ONNX graph's weights and+constants unchanged (float32, evaluated in float64; tools/export_agile.py), the joint order of the bundle, and a+parity fixture: graph inputs (with their histories) and the outputs onnxruntime gave for them (parity() checks this+port against them).++The graph builds its observation itself and keeps a 5-frame history of each term, fed back every tick (LEAPP feedback):+each tick the oldest frame is dropped and the new one appended, then the terms' histories (oldest frame first) are+concatenated, 5 x 80 = 400 numbers:+ velocity-height command (vx, vy, wz, height) 4 pelvis angular velocity (pelvis frame) 3+ gravity (0, 0, -1) in the pelvis frame 3 q - default (29 joints, Isaac Lab order) 29+ joint speeds x 0.1 29 last action, clipped to +-10 12+MLP 400 -> 512 -> 256 -> 128 (ELU) -> 12: the action (Isaac Lab's leg order); targets = default + scale x action,+clipped to +-6 rad. graph() is that computation; step() maps Unitree's motor order to the bundle's by joint name.++On the rig (body.py G1Rig) and under the arbiter (bodies/control/arbiter.py) the legs follow AGILE's 12 targets on its+PD gains (body.toml [walk.agile] kp, kd: the graph's gain outputs); the waist and the arms stay the sport's (the rig's+u, the arbiter's plans or holds). AGILE has no waist or arm output and no residual: it reads all 29 joints' measured+positions and speeds.++The command as in training: clipped to the training ranges (after [limits.walk]); a command (vx, vy, wz) of norm+below 0.1 is 0 (training zeroed such samples); height 0.72 m (training's walking height). The history starts as in+training (Isaac Lab's history buffer: the first frame fills it, the last action is 0) after place(), a kick and an+arbiter hand-back. NVIDIA's MuJoCo runner starts from the bundle's initial values instead: the export run's first frame+after a reset (9 degrees of tilt, randomised legs, a walking command (0.20, 0.16, 0.23) in all five frames). Measured on+this model: an in-place turn below about 0.7 rad/s barely turns (0.35 rad/s turns 0.03-0.05 rad/s after the first+second; walking at 0.2 m/s or faster it turns as commanded), and it stands with the pelvis at 0.67-0.70 m (FALCON+0.74 m). Deterministic: plain float64 numpy.+"""++from __future__ import annotations++import math+from pathlib import Path++import numpy as np++from .body import ARM, LEGS, TORSO+from .falcon import mlp++HERE = Path(__file__).resolve().parent+UNITREE = LEGS + TORSO + [f"{s}_{a}_joint" for s in ("left", "right") for a in ARM] # Unitree's motor order (29)+TERMS = ("velocity_height_commands", "base_ang_vel", "projected_gravity", "joint_pos", "joint_vel", "actions")+INPUTS = ("base_velocity", "robot_root_ang_vel_b", "robot_root_quat_w", "robot_joint_pos", "robot_joint_vel")+++class Agile:+ """AGILE for one robot: the six term histories and the last action; step() every 20 ms. For the rig like body.py+ WalkPolicy (default: the legs' stance, reset, state); its step() takes falcon.py's arguments."""++ def __init__(self, decl):+ A = decl["walk"]["agile"]+ z = np.load(HERE / A["weights"])+ self.layers = [(z[f"w{k}"].astype(float), z[f"b{k}"].astype(float)) for k in range(4)]+ self.q0, self.dq0 = z["joint_pos_default"].astype(float), z["joint_vel_default"].astype(float)+ self.s_vel, self.act_clip = float(z["joint_vel_scale"]), float(z["action_clip"])+ self.scale, self.offset = z["action_scale"].astype(float), z["action_offset"].astype(float)+ self.t_min, self.t_max = z["target_min"].astype(float), z["target_max"].astype(float)+ self.gravity = z["gravity"].astype(float)+ self.fixture = {k[len("parity_") :]: z[k] for k in z.files if k.startswith("parity_")}+ self.ix = np.array([UNITREE.index(n) for n in z["obs_joints"]]) # Unitree index of each graph joint (29)+ legs = list(z["action_joints"])+ self.out = np.array([legs.index(n) for n in LEGS]) # Unitree leg i <- graph output out[i]+ self.default = self.offset[self.out] # the legs' stance (as WalkPolicy.default)+ self.kp, self.kd = np.array(A["kp"], float), np.array(A["kd"], float) # the legs' PD (12)+ self.history_len = int(A["history"])+ self.height = float(A["base_height_m"])+ self.cmd_min, self.cmd_max = np.array(A["command_min"], float), np.array(A["command_max"], float)+ self.cmd_min_norm = float(A["command_min_norm"])+ self.sizes = [4, 3, 3, len(UNITREE), len(UNITREE), len(LEGS)] # one frame of each term+ self.reset()++ def reset(self):+ self.action = np.zeros(len(LEGS))+ self.hist = tuple(np.zeros((self.history_len, n)) for n in self.sizes)+ self.fresh = True # the next tick's frame fills the history (Isaac Lab's history buffer after a reset)+ self.targets = self.default.copy()++ def command(self, cmd):+ """The walking command as AGILE was trained on it: clipped to its ranges, a small command zeroed."""+ c = np.clip(np.asarray(cmd, float)[:3], self.cmd_min, self.cmd_max)+ return c if math.sqrt(c @ c) >= self.cmd_min_norm else np.zeros(3)++ def frame(self, cmd4, gyro, quat_xyzw, q, dq, last_action):+ """One frame of the six terms, as the graph computes it (graph's order: Isaac Lab joints, quaternion x, y, z,+ w); gravity by Isaac Lab's quat_apply_inverse: v - w t + xyz x t, t = 2 xyz x v."""+ xyz, w = np.asarray(quat_xyzw[:3], float), float(quat_xyzw[3])+ t = 2.0 * np.cross(xyz, self.gravity)+ grav = self.gravity - w * t + np.cross(xyz, t)+ return (+ np.asarray(cmd4, float),+ np.asarray(gyro, float),+ grav,+ np.asarray(q, float) - self.q0,+ (np.asarray(dq, float) - self.dq0) * self.s_vel,+ np.clip(last_action, -self.act_clip, self.act_clip),+ )++ def graph(self, cmd4, gyro, quat_xyzw, q, dq, last_action, hist):+ """The ONNX graph: the new frame appended to each term's history (the oldest dropped), the network on the+ histories. Returns (targets 12, action 12, histories), the legs in the graph's order."""+ hist = tuple(np.vstack([h[1:], f]) for h, f in zip(hist, self.frame(cmd4, gyro, quat_xyzw, q, dq, last_action)))+ action = mlp(self.layers, np.concatenate([h.ravel() for h in hist]))+ return np.clip(self.offset + self.scale * action, self.t_min, self.t_max), action, hist++ def step(self, quat, gyro, q, dq, cmd, arms=None, waist_yaw=None):+ """One policy tick. quat (w, x, y, z) and gyro (pelvis frame) of the pelvis; q, dq: the 29 joints in Unitree's+ motor order (measured); cmd: vx, vy, wz (robot frame). arms, waist_yaw: not used (falcon.py's arguments).+ Returns the 12 leg targets (Unitree's order)."""+ w, x, y, z = quat+ q, dq = np.asarray(q, float), np.asarray(dq, float)+ inputs = (np.r_[self.command(cmd), self.height], gyro, (x, y, z, w), q[self.ix], dq[self.ix], self.action)+ if self.fresh:+ self.hist = tuple(np.tile(f, (self.history_len, 1)) for f in self.frame(*inputs))+ self.fresh = False+ t, self.action, self.hist = self.graph(*inputs, self.hist)+ self.targets = t[self.out]+ return self.targets++ def state(self):+ """The policy's memory (last action, histories, fresh): for hashing and copying."""+ return np.r_[self.action, np.concatenate([h.ravel() for h in self.hist]), self.fresh]++ def parity(self):+ """max |this port - onnxruntime| over the fixture stored with the weights (tools/export_agile.py): all the+ graph's outputs (targets, action, the six histories)."""+ F = self.fixture+ err = 0.0+ for k in range(len(F["joint_pos"])):+ ins = [F[n][k] for n in INPUTS + ("last_action_in",)] + [tuple(F[f"h_policy_{n}_in"][k] for n in TERMS)]+ t, a, hist = self.graph(*ins)+ ref = [F["joint_pos"][k], F["last_action_out"][k]] + [F[f"h_policy_{n}_out"][k] for n in TERMS]+ err = max(err, max(float(np.max(np.abs(g - r))) for g, r in zip([t, a, *hist], ref)))+ return errdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/body.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/body.pynew file mode 100644index 0000000000..d5d5ac08d9--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/body.py@@ -0,0 +1,507 @@+"""The Unitree G1 body (body.toml): MJCF assembly, the walking policy, the waist/arm servo, the kick, the controlled+vector u.++ from bodies import load_body+ B = load_body("unitree_g1")+ B.mount(scene_root, prefix="A_", pos=(0, -1.6, -0.76), yaw=pi / 2, hand="paddle") # into a scene's XML tree+ rig = B.rig(model, prefix="A_", hand="paddle") # after compiling (walker="falcon" / "falcon_legs" / "agile":+ # optional policies)+ rig.begin_step(d, u) # every 10 ms control step (the policy runs every 20 ms)+ rig.apply(d, u_prev, u, j, u_prev2) # every physics substep+ rig.kick(d, foot="right", speed=3.0) # a kick (kick.py); the walking policy resumes after it++The controlled vector u (body.toml [dof]): [walk_vx, walk_vy, walk_wz, waist_pitch, waist_yaw, arm_0 .. arm_6].+walk_*: the walking policy's velocity command in the robot's body frame; the legs are the policy's (or the kick+controller's) and are not in u. Rig.qadr / vadr / M / joint_targets cover the upper body (waist yaw, roll, pitch,+the hand arm, the other arm), as the wheeled humanoid's Rig, so the whole-body planner works on both bodies; the+legs have their own addresses (lqadr, lvadr, laid).+The same Rig drives a fixed-base copy (robot_only_xml(fixed_base=True): the pelvis welded at the origin) and a planar+copy (fixed_base="planar": no legs, the pelvis on two slides and a hinge at the standing height; the whole-body+planner's model and twin): there u[0:3] are the pelvis position (x, y, yaw), as the wheeled humanoid's base, a+stand-in for where walking puts the pelvis; neither copy has legs or a policy.+"""+from __future__ import annotations++import copy+import math+import tomllib+import xml.etree.ElementTree as ET+from pathlib import Path++import numpy as np++from .. import selfcollision as SC+from .. import servo as SV++HERE = Path(__file__).resolve().parent+HANDS = HERE.parent / "hands"+NAME_ATTRS = ("name", "joint", "body", "body1", "body2", "geom", "geom1", "geom2", "site", "mesh", "material",+ "class", "childclass", "target", "texture", "tendon", "actuator")+LEGS = [f"{s}_{j}_joint" for s in ("left", "right") for j in ("hip_pitch", "hip_roll", "hip_yaw", "knee",+ "ankle_pitch", "ankle_roll")]+ARM = ["shoulder_pitch", "shoulder_roll", "shoulder_yaw", "elbow", "wrist_roll", "wrist_pitch", "wrist_yaw"]+TORSO = ["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"]+STAND_Z = 0.793 # the pelvis above the floor at the policy's default stance+PLAN_Z = 0.778 # ... where it settles standing or walking (the planar copy's height)+PLANAR = ["base_x", "base_y", "base_yaw"]+++def short(j):+ """'left_hip_pitch_joint' -> 'hip_pitch', 'waist_yaw_joint' -> 'waist_yaw' (body.toml [motors.assign] keys)."""+ s = j[:-len("_joint")] if j.endswith("_joint") else j+ for side in ("left_", "right_"):+ if s.startswith(side):+ return s[len(side):]+ return s+++def _toml(p):+ return tomllib.loads(Path(p).read_text())+++def _fmt(v):+ return " ".join(repr(float(x)) for x in v)+++def quat_z(yaw):+ return (math.cos(yaw / 2), 0.0, 0.0, math.sin(yaw / 2))+++class G1Body:+ kind = "legged"+ walkers = ("unitree", "falcon", "falcon_legs", "agile") # rig(..., walker=): Unitree's policy (the default),+ # FALCON (falcon.py; "falcon_legs": FALCON on the legs only)+ # or AGILE (agile.py)++ def __init__(self):+ self.decl = _toml(HERE / "body.toml")+ self.hands = _toml(HANDS / "hands.toml")+ self.name = self.decl["body"]["name"]+ self.revision = self.decl["body"]["revision"]+ self.dof = list(self.decl["dof"]["names"])+ W = self.decl["walk"]+ P = W["planning"] # the planner's base tracker (the planar copy): what+ self.base_speed, self.base_accel = float(P["speed_m_s"]), float(P["accel_m_s2"]) # walking really achieves+ self.yaw_rate, self.yaw_accel = float(P["yaw_rate_rad_s"]), float(P["yaw_accel_rad_s2"])+ self.plan_z = PLAN_Z+ C = self.decl["controller"]["step"]+ self.dt = C["control_dt_s"]+ self.substeps = int(round(self.dt / C["physics_dt_s"]))++ # ------------------------------------------------------------------ the template, renamed+ def _hand(self, hand, tag="hand"):+ h = self.hands[hand]+ body = copy.deepcopy(ET.parse(HANDS / h["file"]).getroot().find("worldbody").find("body"))+ contact = set(h.get("contact", []))+ for el in body.iter():+ if el.tag == "body" and el.get("name") == "hand":+ el.set("name", tag)+ elif el.get("name") is not None:+ if el.tag == "geom":+ c = el.get("name") in contact+ el.set("contype", "1" if c else "4")+ el.set("conaffinity", "1" if c else "0")+ el.set("name", f"{tag}_" + el.get("name"))+ elif el.tag == "geom":+ el.set("contype", "4"); el.set("conaffinity", "0")+ return body++ def _template(self, prefix, hand, arm, lod, accent, head_pitch, fixed_base=False):+ root = ET.parse(HERE / self.decl["body"]["model"]).getroot()+ meshdir = HERE / self.decl["body"]["meshes"][lod]+ if lod == "fine" and not meshdir.is_dir(): # the fine meshes are not in git (tools/make_model.py)+ meshdir, lod = HERE / self.decl["body"]["meshes"]["standard"], "standard"+ for m in root.find("asset").findall("mesh"):+ stem = Path(m.get("file")).stem+ m.set("file", str(meshdir / (stem + (".STL" if lod == "fine" else ".stl"))))+ if head_pitch is None:+ head_pitch = self.decl["mounts"]["head_pitch_rad"]+ for b in root.iter("body"):+ if b.get("name") == "head_cam":+ b.set("quat", _fmt((math.cos(head_pitch / 2), 0.0, math.sin(head_pitch / 2), 0.0)))+ if b.get("name") == "torso_link" and accent is not None:+ for g in b.findall("geom"):+ if g.get("mesh") == "g1_torso_link" and g.get("class") == "g1_visual":+ g.set("rgba", _fmt(accent))+ if hand:+ mount = next(b for b in root.iter("body") if b.get("name") == f"{arm}_mount")+ mount.append(self._hand(hand))+ if fixed_base:+ pelvis = root.find("worldbody").find("body")+ for j in pelvis.findall("freejoint"):+ pelvis.remove(j)+ for b in list(pelvis): # the legs go: the pelvis is welded (or planar)+ if b.tag == "body" and "hip" in (b.get("name") or ""):+ pelvis.remove(b)+ if fixed_base == "planar":+ for i, (n, typ, ax) in enumerate((("base_x", "slide", "1 0 0"), ("base_y", "slide", "0 1 0"),+ ("base_yaw", "hinge", "0 0 1"))):+ pelvis.insert(i, ET.Element("joint", name=n, type=typ, axis=ax, damping="0", armature="0.1"))+ for el in root.iter():+ for a in NAME_ATTRS:+ v = el.get(a)+ if v is not None:+ el.set(a, prefix + v)+ return root++ def joints(self, arm, fixed_base=False):+ other = "left" if arm == "right" else "right"+ upper = ["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"] + \+ [f"{arm}_{j}_joint" for j in ARM] + [f"{other}_{j}_joint" for j in ARM]+ return (PLANAR if fixed_base == "planar" else [] if fixed_base else LEGS) + upper++ def _effort(self, j):+ L = self.decl["limits"]+ if j in PLANAR: # the planar copy's stand-in for walking+ return 5000.0+ if j.startswith("waist"):+ return L["waist"]["torque_nm"][["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"].index(j)]+ for i, a in enumerate(ARM):+ if j.endswith(f"_{a}_joint"):+ return L["arm"]["torque_nm"][i]+ return L["leg"]["torque_nm"][LEGS.index(j) % 6]++ def mount(self, scene: ET.Element, prefix: str, pos, yaw: float, hand: str | None = "paddle", arm: str = "right",+ lod: str = "standard", accent=None, head_pitch=None, fixed_base: bool = False,+ self_collision: bool = True, **_) -> dict:+ """Add one G1 to a scene's XML tree. pos: the point on the floor under the pelvis; yaw: its facing (the robot's+ forward axis = world x rotated by yaw). The pelvis starts at the policy's stand height."""+ t = self._template(prefix, hand, arm, lod, accent, head_pitch, fixed_base)+ sc = SC.plan(t, self.decl["self_collision"], prefix=prefix) if self_collision else None # selfcollision.py+ for sec in ("default", "asset"):+ dst = scene.find(sec)+ if dst is None:+ dst = ET.SubElement(scene, sec)+ for el in t.find(sec):+ dst.append(el)+ pelvis = t.find("worldbody").find("body")+ z = PLAN_Z if fixed_base == "planar" else 0.0 if fixed_base else STAND_Z+ p = np.asarray(pos, float) + np.array([0.0, 0.0, z])+ pelvis.set("pos", _fmt(p))+ pelvis.set("quat", _fmt(quat_z(yaw)))+ scene.find("worldbody").append(pelvis)+ if sc is not None: # the robot's self-collision pairs (body.toml [self_collision])+ SC.add_pairs(scene, sc)+ act = scene.find("actuator")+ if act is None:+ act = ET.SubElement(scene, "actuator")+ for j in self.joints(arm, fixed_base):+ lim = self._effort(j)+ ET.SubElement(act, "motor", name=f"{prefix}m_{j}", joint=prefix + j, ctrlrange=f"{-lim!r} {lim!r}")+ return {**SC.info(sc), "prefix": prefix, "base": prefix + "pelvis", "hand": prefix + "hand" if hand else None,+ "tool_site": prefix + "hand_" + self.hands[hand]["site"] if hand else None,+ "contact_geoms": [prefix + "hand_" + g for g in self.hands[hand].get("contact", [])] if hand else [],+ "feet": [prefix + "left_foot_strike", prefix + "right_foot_strike"], "arm": arm,+ "cameras": [prefix + c for c in self.decl["mounts"]["cameras"]]}++ @staticmethod+ def guard_root(arm):+ """The forearm's link: the planner keeps it and everything below it out of a sport's keep-out boxes."""+ return f"{arm}_elbow_link"++ def robot_only_xml(self, hand="paddle", arm="right", lod="standard", meshdir: str | None = None,+ option: dict | None = None, header: str = "", fixed_base="planar",+ self_collision: bool = True) -> str:+ """The robot alone: by default the planar copy (the planner's model, a low-level player's model)."""+ root = ET.Element("mujoco", model=f"{self.name}_{hand}_robot_only")+ if header:+ root.append(ET.Comment(header))+ ET.SubElement(root, "compiler", angle="radian", autolimits="true", **({"meshdir": meshdir} if meshdir else {}))+ ET.SubElement(root, "option", **(option or {"timestep": "0.001", "integrator": "implicitfast"}))+ for sec in ("default", "asset", "worldbody"):+ ET.SubElement(root, sec)+ self.mount(root, "", (0.0, 0.0, 0.0), 0.0, hand=hand, arm=arm, lod=lod, fixed_base=fixed_base,+ self_collision=self_collision)+ if meshdir:+ for m in root.find("asset").findall("mesh"):+ m.set("file", Path(m.get("file")).name)+ ET.indent(root, space=" ")+ return ET.tostring(root, encoding="unicode") + "\n"++ def rig(self, model, prefix="", arm="right", hand="paddle", rest=None, walker="unitree"):+ return G1Rig(self, model, prefix, arm, hand, rest, walker)+++class WalkPolicy:+ """Unitree's walking policy (body.toml [walk]) for one robot: the observation, the LSTM memory, the leg targets. The+ network (LSTM 47 -> 64, Linear 64 -> 32, ELU, Linear 32 -> 12) runs in numpy (float64) from policy/motion.npz+ (tools/export_policy.py: the weights of Unitree's motion.pt, unchanged)."""++ def __init__(self, decl):+ W = decl["walk"]+ z = np.load(HERE / W["weights"])+ self.w_ih, self.w_hh = z["w_ih"].astype(float), z["w_hh"].astype(float)+ self.b = z["b_ih"].astype(float) + z["b_hh"].astype(float)+ self.w0, self.b0 = z["w0"].astype(float), z["b0"].astype(float)+ self.w2, self.b2 = z["w2"].astype(float), z["b2"].astype(float)+ self.nh = self.w_hh.shape[1]+ self.default = np.array(W["default_angles"], float)+ self.scale = float(W["action_scale"])+ S = W["obs_scales"]+ self.s_ang, self.s_pos, self.s_vel = S["ang_vel"], S["dof_pos"], S["dof_vel"]+ self.s_cmd = np.array(S["cmd"], float)+ self.period = float(W["gait_period_s"])+ self.reset()++ def reset(self):+ self.h = np.zeros(self.nh)+ self.c = np.zeros(self.nh)+ self.action = np.zeros(12)+ self.targets = self.default.copy()++ def net(self, x):+ g = self.w_ih @ x + self.w_hh @ self.h + self.b+ n = self.nh+ sig = lambda v: 1.0 / (1.0 + np.exp(-v))+ i, f, gg, o = sig(g[0:n]), sig(g[n:2 * n]), np.tanh(g[2 * n:3 * n]), sig(g[3 * n:4 * n])+ self.c = f * self.c + i * gg+ self.h = o * np.tanh(self.c)+ y = self.w0 @ self.h + self.b0+ y = np.where(y > 0, y, np.expm1(np.minimum(y, 0.0))) # ELU+ return self.w2 @ y + self.b2++ def step(self, quat, omega, q, qd, cmd, t):+ w, x, y, z = quat+ g = np.array([2 * (-z * x + w * y), -2 * (z * y + w * x), 1 - 2 * (w * w + z * z)])+ ph = (t % self.period) / self.period+ obs = np.concatenate([omega * self.s_ang, g, np.asarray(cmd) * self.s_cmd, (q - self.default) * self.s_pos,+ qd * self.s_vel, self.action, [math.sin(2 * math.pi * ph), math.cos(2 * math.pi * ph)]])+ self.action = self.net(obs)+ self.targets = self.action * self.scale + self.default+ return self.targets++ def state(self):+ """The policy's memory (LSTM state, last action): for hashing and copying."""+ return np.concatenate([self.h, self.c, self.action])+++class G1Rig:+ """One mounted G1 in a compiled model: upper-body addresses, limits and servo (as the wheeled humanoid's Rig), plus+ the legs: the walking policy, the kick, their PD."""++ def __init__(self, body: G1Body, model, prefix="", arm="right", hand="paddle", rest=None, walker="unitree"):+ import mujoco as mj+ if walker not in body.walkers:+ raise ValueError(f"unknown walker {walker!r}; one of {list(body.walkers)}")+ self.mj, self.B, self.m, self.prefix, self.arm, self.walker = mj, body, model, prefix, arm, walker+ D = body.decl+ jid = lambda n: mj.mj_name2id(model, mj.mjtObj.mjOBJ_JOINT, prefix + n)+ self.fixed_base = jid("left_hip_pitch_joint") < 0+ self.planar = jid("base_x") >= 0+ upper = (PLANAR if self.planar else []) + body.joints(arm, fixed_base=True)+ o = 3 if self.planar else 0 # the planar copy's base joints come first+ ids = [jid(j) for j in upper]+ if min(ids) < 0:+ raise ValueError(f"robot {prefix!r} not in the model")+ self.joints = upper+ self.qadr = np.array([model.jnt_qposadr[i] for i in ids])+ self.vadr = np.array([model.jnt_dofadr[i] for i in ids])+ self.aid = np.array([mj.mj_name2id(model, mj.mjtObj.mjOBJ_ACTUATOR, f"{prefix}m_{j}") for j in upper])+ self.tau_lim = model.actuator_ctrlrange[self.aid, 1].copy()+ # u -> upper-body joint targets: [waist yaw, roll, pitch, arm x 7, other arm x 7] = M @ u + c+ self.M = np.zeros((17 + o, 12))+ for k in range(o):+ self.M[k, k] = 1.0+ self.M[o + 0, 4] = 1.0 # waist yaw+ self.M[o + 2, 3] = 1.0 # waist pitch+ for i in range(7):+ self.M[o + 3 + i, 5 + i] = 1.0+ R = D["rest"]+ self.c = np.zeros(17 + o)+ self.c[o + 10:o + 17] = R["other_arm"]+ C, L = D["controller"], D["limits"]+ Pl = D["walk"]["planning"]+ base_kp, base_kd = (Pl["base_kp"], Pl["base_kd"]) if o else ([], [])+ self.kp = np.r_[base_kp, C["kp"]["waist"], C["kp"]["arm"], C["kp"]["arm"]]+ self.kd = np.r_[base_kd, C["kd"]["waist"], C["kd"]["arm"], C["kd"]["arm"]]+ self.o = o+ jr = model.jnt_range[ids[o:]]+ W = D["walk"]+ self.LO = np.r_[-np.array(L["walk"]["command_max"]), jr[2, 0], jr[0, 0], jr[3:10, 0]]+ self.HI = np.r_[np.array(L["walk"]["command_max"]), jr[2, 1], jr[0, 1], jr[3:10, 1]]+ self.VEL = np.r_[L["walk"]["command_accel"], L["waist"]["speed_rad_s"][2], L["waist"]["speed_rad_s"][0],+ L["arm"]["speed_rad_s"]]+ if self.planar: # the planar copy: u[0:3] = the pelvis position, as a mobile base+ self.LO[0:3], self.HI[0:3] = -np.inf, np.inf+ self.VEL[0:3] = body.base_speed, body.base_speed, body.yaw_rate+ self.STEP = self.VEL * body.dt # the walk command: its change per step; the joints: their speed+ self.rest = np.r_[0.0, 0.0, 0.0, R["waist"], R["arm"]]+ if rest is not None:+ self.rest[3:] = rest+ self.dt, self.substeps = body.dt, body.substeps+ self.tool_site = mj.mj_name2id(model, mj.mjtObj.mjOBJ_SITE, prefix + "hand_" + body.hands[hand]["site"]) \+ if hand else -1+ self.base_body = mj.mj_name2id(model, mj.mjtObj.mjOBJ_BODY, prefix + "pelvis")+ self.cmd = np.zeros(3)+ self.mode = "walk"+ self.kicker = None+ self.k = 0+ self.farms = None+ self.residual = False # FALCON's wrist residual (falcon.py); AGILE has none+ if not self.fixed_base:+ lids = [jid(j) for j in LEGS]+ self.lqadr = np.array([model.jnt_qposadr[i] for i in lids])+ self.lvadr = np.array([model.jnt_dofadr[i] for i in lids])+ self.laid = np.array([mj.mj_name2id(model, mj.mjtObj.mjOBJ_ACTUATOR, f"{prefix}m_{j}") for j in LEGS])+ self.ltau = model.actuator_ctrlrange[self.laid, 1].copy()+ fj = next(j for j in range(model.njnt) if model.jnt_bodyid[j] == self.base_body)+ self.fqadr, self.fvadr = int(model.jnt_qposadr[fj]), int(model.jnt_dofadr[fj])+ if walker != "unitree": # the optional FALCON / AGILE policy (falcon.py, agile.py; body.toml+ if walker in ("falcon", "falcon_legs"): # [walk.falcon], [walk.agile]): they read all 29 joints+ from .falcon import Falcon+ self.policy = Falcon(D, arm_actor=walker == "falcon")+ else:+ from .agile import Agile+ self.policy = Agile(D)+ self.lkp, self.lkd = self.policy.kp, self.policy.kd+ fids = [jid(j) for j in LEGS + TORSO + [f"{s}_{a}_joint" for s in ("left", "right") for a in ARM]]+ self.fq, self.fv = model.jnt_qposadr[fids], model.jnt_dofadr[fids]+ self.farms = [upper.index(f"{s}_{a}_joint") for s in ("left", "right") for a in ARM]+ self.residual = walker == "falcon"+ else:+ self.policy = WalkPolicy(D)+ self.lkp, self.lkd = np.array(W["kp"], float), np.array(W["kd"], float)+ self.leg_targets = self.policy.default.copy()+ # the servos (bodies/servo.py): the upper body's commanded joints (setpoints at the speed limits, the motor+ # curves at the output), the legs' output stage (the motor curves), the walking command (the real joystick+ # range, rate-limited)+ upper_keys = ([None] * 3 if self.planar else []) + [short(j) for j in body.joints(arm, fixed_base=True)]+ leg_keys = [] if self.fixed_base else [short(j) for j in LEGS]+ self.servo, self.legs_act, self.ACC = SV.legged_layout(model, self, D, body.dt / body.substeps, upper_keys,+ leg_keys, Pl if self.planar else None)+ self.walk = SV.WalkCommand(L["walk"], body.dt)+ self.selfcol = SC.Monitor(model, prefix + "selfcol", D["self_collision"].get("warn_force_n")) # recorded only++ # u <-> joints+ def joint_targets(self, u):+ return self.M @ np.asarray(u, float) + self.c++ def u_of(self, d):+ q, o = d.qpos[self.qadr], self.o+ return np.r_[q[0:3] if o else self.cmd, q[o + 2], q[o], q[o + 3:o + 10]]++ def ud_of(self, d):+ v, o = d.qvel[self.vadr], self.o+ return np.r_[v[0:3] if o else np.zeros(3), v[o + 2], v[o], v[o + 3:o + 10]]++ def base_pose(self, d):+ """The pelvis on the floor: (x, y, yaw) in the world (the yaw of its forward axis)."""+ R = d.xmat[self.base_body].reshape(3, 3)+ p = d.xpos[self.base_body]+ return np.array([p[0], p[1], math.atan2(R[1, 0], R[0, 0])])++ def pelvis(self, d):+ """(position, rotation matrix) of the pelvis in the world."""+ return d.xpos[self.base_body].copy(), d.xmat[self.base_body].reshape(3, 3).copy()++ def place(self, d, u, pos=None, yaw=None):+ """Teleport to standing at the mount (or at pos / yaw) with the upper body at u; the policy's memory reset."""+ d.qpos[self.qadr] = self.joint_targets(u)+ d.qvel[self.vadr] = 0.0+ if not self.fixed_base:+ m = self.m+ j = self.fqadr+ p0 = m.body_pos[self.base_body] if pos is None else np.asarray(pos, float)+ q0 = m.body_quat[self.base_body] if yaw is None else np.array(quat_z(yaw))+ d.qpos[j:j + 3] = p0+ d.qpos[j + 3:j + 7] = q0+ d.qvel[self.fvadr:self.fvadr + 6] = 0.0+ d.qpos[self.lqadr] = self.policy.default+ d.qvel[self.lvadr] = 0.0+ self.policy.reset()+ self.walk.reset()+ self.legs_act.reset()+ self.leg_targets = self.policy.default.copy()+ self.mode, self.kicker, self.cmd, self.k = "walk", None, np.zeros(3), 0+ self.sync(d)++ def sync(self, d):+ """The servo's setpoint generator to the upper body's measured state (after a teleport or a state copy)."""+ x, xd = self.u_of(d), self.ud_of(d)+ if not self.planar:+ x[0:3], xd[0:3] = 0.0, 0.0 # the walking command is not a position+ self.servo.reset(x, xd)++ # the control step+ def begin_step(self, d, u):+ """Once per 10 ms control step, before its substeps: the walking command from u, the policy every 20 ms+ (or the kick's leg targets)."""+ if self.fixed_base:+ return+ self.cmd = self.walk(u[0:3]).copy() # the real joystick range, rate-limited (bodies/servo.py)+ if self.mode == "kick":+ self.leg_targets = self.kicker.step(d)+ if self.kicker.done:+ self.mode, self.kicker = "walk", None+ self.policy.reset()+ self.k = 0+ if self.mode == "walk" and self.k % 2 == 0:+ j, v = self.fqadr, self.fvadr+ if self.walker != "unitree": # all 29 joints, u's arm targets and waist yaw (falcon.py; agile.py+ # reads the joints only)+ up = self.joint_targets(u)+ self.leg_targets = self.policy.step(d.qpos[j + 3:j + 7], d.qvel[v + 3:v + 6], d.qpos[self.fq],+ d.qvel[self.fv], self.cmd, up[self.farms], up[0])[:12]+ else:+ self.leg_targets = self.policy.step(d.qpos[j + 3:j + 7], d.qvel[v + 3:v + 6], d.qpos[self.lqadr],+ d.qvel[self.lvadr], self.cmd, self.k * self.dt)+ self.k += 1++ def apply(self, d, u_prev, u_next, j, u_prev2=None):+ """Physics substep j: the upper body through its servo (bodies/servo.py: setpoints within the limits, PD ++ bias + inertia feed-forward, the motor curves) and the legs' PD through their output stage (the motor+ curves). u_prev2 is accepted for the old signature."""+ self.selfcol.update(d) # self-collision contacts of the last physics step (recorded)+ if not self.servo.ready:+ self.sync(d)+ a, b = np.asarray(u_prev, float), np.asarray(u_next, float)+ extra = None # FALCON's balance residual of the wrists, as a target offset+ if self.residual and self.mode == "walk":+ extra = np.zeros(len(self.kp))+ extra[self.farms] = self.policy.wrist_torque(self.kp[self.farms])+ self.servo.track(d, a + (b - a) * (j / self.substeps), (b - a) / self.dt, extra)+ if not self.fixed_base:+ kp, kd = (self.kicker.kp, self.kicker.kd) if self.mode == "kick" else (self.lkp, self.lkd)+ lt = kp * (self.leg_targets - d.qpos[self.lqadr]) - kd * d.qvel[self.lvadr]+ if self.mode == "kick":+ lt = lt + self.kicker.ff+ self.legs_act.write(d, lt)++ def self_collisions(self) -> dict:+ """The self-collision record since the rig was built or reset (bodies/selfcollision.py Monitor.summary):+ events, warnings, time in contact, peak force, impulse, the worst pairs. For the match record."""+ return self.selfcol.summary()++ def check(self, u, u_prev, u_prev2=None):+ """A target row against the limits (bodies/servo.py check_row): ranges (the walking command within the real+ joystick range), per-step changes (joint speeds, the walking command's rate); with u_prev2 the planar copy's+ base acceleration. None or the reason."""+ return SV.check_row(u, u_prev, u_prev2, self.LO, self.HI, self.VEL, self.ACC, self.dt,+ self.servo.base.lim if self.servo.base is not None else None)++ def tool(self, d):+ return d.site_xpos[self.tool_site].copy(), d.site_xmat[self.tool_site].reshape(3, 3).copy()++ def kick(self, d, foot="right", speed=2.5, height=0.10, reach=0.22, target=None, direction=None):+ """Start a kick (kick.py): the legs leave the policy until it ends. target: the world point the foot's strike+ box passes through at `speed` (m/s; e.g. a little below and behind the ball's centre); direction: the swing's+ world direction (default the robot's forward axis); without a target the foot strikes `reach` beyond the+ support foot's toe line, `height` above the ground."""+ if self.fixed_base or self.mode == "kick":+ return False+ from .kick import Kick+ self.kicker = Kick(self, d, foot, speed, height, reach, target, direction)+ self.mode = "kick"+ return True++ def memory(self):+ return self.policy.state() if not self.fixed_base else np.zeros(0)+++_BODY: dict = {}+++def load() -> G1Body:+ if "g1" not in _BODY:+ _BODY["g1"] = G1Body()+ return _BODY["g1"]diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/body.toml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/body.tomlnew file mode 100644index 0000000000..3e93651a0a--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/body.toml@@ -0,0 +1,239 @@+# The RoboOlympics legged humanoid: Unitree G1 (29-DOF, rev 1.0) from MuJoCo Menagerie, walking with Unitree's own+# pretrained walking policy (unitree_rl_gym, BSD-3-Clause). For the sports where the feet matter (soccer, athletics);+# the upper-body sports use bodies/wheeled_humanoid. Data only: body.py reads it.++[body]+name = "unitree_g1"+title = "legged humanoid (Unitree G1, 29 DOF)"+revision = "g1-4" # bump on any change that alters play (model.xml, policy, limits, controllers;+ # g1-2: walking command at the real joystick limits, motor curves, bodies/servo.py)+ # g1-3: self-collision, [self_collision] (bodies/selfcollision.py, 2026-10-09)+ # g1-4: legs x legs, shin x foot (self-collision); the strike boxes out of it+model = "model.xml" # tools/make_model.py from the Menagerie model (provenance, changes)+meshes = { standard = "meshes", fine = "meshes_fine", "25k" = "meshes_25k" } # standard: 63 k faces; fine: the Menagerie meshes (419 k)+# "25k": the players' level of detail (31 k faces, in git; bodies/lod.py from meshes_fine/,+# user decision D1 2026-10-08): mount(..., lod="25k") draws the players' images with the real robot's appearance+license = "BSD-3-Clause (LICENSE: MuJoCo Menagerie unitree_g1, derived from Unitree's g1_description; policy/LICENSE.unitree_rl_gym: the walking policy); MIT (policy/LICENSE.falcon: the optional FALCON walking policy); Apache-2.0 (policy/LICENSE.agile: the optional AGILE walking policy)"+mass_kg = 33.3 # the model (datasheet "about 35 kg" with battery)+height_m = 1.32 # standing (datasheet 1,320 mm)+kind = "legged" # the base is not a joint: it moves by walking (the policy) or kicking++[dof] # the controlled vector u, in this order+names = ["walk_vx", "walk_vy", "walk_wz", "waist_pitch", "waist_yaw",+ "arm_0", "arm_1", "arm_2", "arm_3", "arm_4", "arm_5", "arm_6"]+# walk_*: the walking policy's velocity command in the robot's body frame (m/s, m/s, rad/s), held until changed;+# waist_pitch / waist_yaw: the waist (waist_roll holds 0); arm_i: the hand arm's joints (shoulder pitch, roll, yaw,+# elbow, wrist roll, pitch, yaw). The other arm holds [rest] other_arm. The legs belong to the walking policy (or the+# kick controller): they are not in u.++[walk] # the walking policy (policy/): Unitree unitree_rl_gym deploy/pre_train/g1/motion.pt+policy = "policy/motion.pt" # an LSTM actor (64 units) trained in Isaac Gym on g1_12dof, validated sim-to-sim in+ # MuJoCo by Unitree (deploy/deploy_mujoco); 50 Hz; observation 47 (angular+ # velocity, gravity, command, leg joints, velocities, last action, gait phase)+sha256 = "cf668f75b90d1abf73d2b87612a6e76bccc61ff7e083b63582d3f6aaa3c1759d"+weights = "policy/motion.npz" # its weights as arrays (tools/export_policy.py): the simulator runs it in numpy+rate_hz = 50+gait_period_s = 0.8+default_angles = [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0, -0.1, 0.0, 0.0, 0.3, -0.2, 0.0]+kp = [100, 100, 100, 150, 40, 40, 100, 100, 100, 150, 40, 40]+kd = [2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2]+action_scale = 0.25+obs_scales = { ang_vel = 0.25, dof_pos = 1.0, dof_vel = 0.05, cmd = [2.0, 2.0, 0.25] }+command_max = [1.0, 1.0, 1.0] # the policy's training range (lin_vel_x, lin_vel_y, ang_vel_yaw); measured in+ # MuJoCo: 0.49 m/s for 0.5, 0.91 m/s for 1.0, 0.30 m/s sideways for 0.4+command_accel = [2.0, 2.0, 4.0] # how fast a command may change (per second): our rule, not the policy's+[walk.planning] # a planner's model of walking (the planar copy's base): below the measured+speed_m_s = 0.6 # speeds, with the policy's lag of about 0.3 s in the acceleration; the copy's+accel_m_s2 = 1.5 # base servo is soft in yaw (base_kp / base_kd: x, y, yaw), like the standing+yaw_rate_rad_s = 0.8 # robot, whose pelvis turns against a fast waist or arm swing+yaw_accel_rad_s2 = 3.0+base_kp = [3000.0, 3000.0, 200.0]+base_kd = [150.0, 150.0, 25.0]+# FALCON (S8; MIT, policy/LICENSE.falcon): an optional walking policy, a sport opts in with rig(..., walker="falcon")+# (falcon.py), or walker="falcon_legs": FALCON on the legs only (its arm actor not applied and fed back as 0, no wrist+# residual; falcon.py). Trained in IsaacGym on the 29-DOF G1 with arm motions and forces on the hands. The weights of the+# released sim2real/models/falcon/g1_29dof.onnx (onnx_sha256), unchanged, with a parity fixture (tools/export_falcon.py).+[walk.falcon]+weights = "policy/falcon_g1_29dof.npz"+onnx_sha256 = "8ac8f51875b878a79d9b5782e702b66572697e204ed262e2002b55631f3105d0"+rate_hz = 50+history = 5 # frames of 115 numbers in the observation (falcon.py)+default_angles = [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0, -0.1, 0.0, 0.0, 0.3, -0.2, 0.0, 0.0, 0.0, 0.0,+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # 29 joints (S8 yaml)+kp = [100, 100, 100, 200, 20, 20, 100, 100, 100, 200, 20, 20] # the legs' PD (S8 yaml JOINT_KP, KD); the waist+kd = [2.5, 2.5, 2.5, 5.0, 0.2, 0.1, 2.5, 2.5, 2.5, 5.0, 0.2, 0.1] # and the arms stay on the [controller] servo+action_scale = 0.25+action_clip = 100.0+obs_scales = { ang_vel = 0.25, dof_vel = 0.05, base_height = 2.0 }+base_height_m = 0.75 # DESIRED_BASE_HEIGHT (S8 yaml)+command_max = [1.0, 1.0, 1.0] # the training range (S8 env config); [limits.walk] clips the command first+speed_min_m_s = 0.2 # training: a speed |(vx, vy)| below 0.2 is 0 (S8 env code)+turn_min_rad_s = 0.2 # ours: with no speed, a smaller yaw rate is 0 too (the robot stands)+heading_gain = 0.5 # training: yaw rate = 0.5 (heading target - heading), clipped (S8 env code)+heading_error_max_rad = 1.0 # ours: the heading target stays this close to the heading+wrist_residual_max_rad = 0.05 # ours: the arm actor's residual, added to the wrists' targets only, clipped+# AGILE (S9; Apache-2.0, policy/LICENSE.agile): another optional walking policy, a sport opts in with+# rig(..., walker="agile") (agile.py). NVIDIA's velocity-height policy, trained in Isaac Lab on the 29-DOF G1 (legs+# only; the arms and the waist yaw moved at random while it stood, held at 0 while it walked). The weights and+# constants of the released LEAPP bundle's ONNX graph (onnx_sha256), unchanged, with the bundle's joint order and a+# parity fixture (tools/export_agile.py).+[walk.agile]+weights = "policy/agile_g1_velocity_height.npz"+onnx_sha256 = "f9a8dfcb8cb8bb2816b92cf893650c53dea30bb041f4919a85f1cf73acbb29fc"+rate_hz = 50 # the bundle's pipeline frequency (S9)+history = 5 # frames of each observation term, kept by the graph (agile.py)+kp = [100, 100, 100, 200, 20, 20, 100, 100, 100, 200, 20, 20] # the legs' PD: the graph's gain outputs (S9; the+kd = [2.5, 2.5, 2.5, 5.0, 0.2, 0.1, 2.5, 2.5, 2.5, 5.0, 0.2, 0.1] # export checks them); waist, arms: [controller]+base_height_m = 0.72 # the height command: training's walking height (DEFAULT_PELVIS_HEIGHT, S9)+command_min = [-0.5, -0.5, -1.0] # the training range (vx, vy, wz; S9); [limits.walk] clips the command first+command_max = [1.5, 0.5, 1.0]+command_min_norm = 0.1 # training: a command (vx, vy, wz) of norm below 0.1 is 0 (S9 min_vel_norm)++[limits.walk] # the walking command u[0:3] (bodies/servo.py WalkCommand): vx, vy, wz+command_max = [0.8, 0.5, 1.57] # what Unitree's own deployment accepts from the joystick (audit G8, approved)+command_accel = [2.0, 2.0, 4.0] # how fast a command may change (per second)+[limits.walk.source]+command_max = "S5 (deploy/deploy_real/configs/g1.yaml:42 max_cmd [0.8, 0.5, 1.57]; the policy was trained on +-1, [walk] command_max)"+command_accel = "ESTIMATE: our rule (the joystick has no published rate limit; 0.4 s from 0 to the forward limit)"++[limits.arm] # joints 0..6 of either arm; Unitree g1_29dof_rev_1_0.urdf <limit> (S2)+speed_rad_s = [37.0, 37.0, 37.0, 37.0, 37.0, 22.0, 22.0]+torque_nm = [25.0, 25.0, 25.0, 25.0, 25.0, 5.0, 5.0]+reach_m = 0.45 # "arm span about 0.45 m" (S1)+payload_kg = 2.0+[limits.arm.source]+speed_rad_s = "S2 (URDF; reachable only near zero torque: the motor curves, S6, cut the torque from 30.9 / 15.3 rad/s)"+accel_rad_s2 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+jerk_rad_s3 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+torque_nm = "S2 (URDF effort; with the motor curves of [motors], S6)"++[limits.waist] # yaw, roll, pitch (S2)+speed_rad_s = [32.0, 37.0, 37.0]+torque_nm = [88.0, 50.0, 50.0]+range_rad = [[-2.618, 2.618], [-0.52, 0.52], [-0.52, 0.52]]+[limits.waist.source]+speed_rad_s = "S2"+accel_rad_s2 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+jerk_rad_s3 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+torque_nm = "S2 (with the motor curves, S6)"++[limits.leg] # hip pitch, roll, yaw, knee, ankle pitch, roll of either leg (S2; the datasheet+speed_rad_s = [32.0, 20.0, 32.0, 20.0, 37.0, 37.0] # gives the knee 90 N m for the 23-DOF base model, S1)+torque_nm = [88.0, 139.0, 88.0, 139.0, 50.0, 50.0]+[limits.leg.source]+speed_rad_s = "S2"+accel_rad_s2 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+jerk_rad_s3 = "NOT PUBLISHED: Unitree publishes no joint acceleration or jerk limit and its SDK passes LowCmd unchanged (S7); the motors' torque-speed curves ([motors], S6) bound what the joint can do"+torque_nm = "S2 (with the motor curves, S6)"++[controller] # waist and arms: as the wheeled humanoid's servo (M qdd_des + PD + bias,+[controller.kp] # clipped at the torques, every 1 ms); legs: the policy's PD (or the kick's)+waist = [400.0, 400.0, 400.0]+arm = [300.0, 300.0, 300.0, 300.0, 100.0, 60.0, 60.0]+[controller.kd]+waist = [10.0, 10.0, 10.0]+arm = [6.0, 6.0, 6.0, 6.0, 2.0, 1.0, 1.0]+[controller.step]+control_dt_s = 0.01+physics_dt_s = 0.001++[rest]+waist = [0.0, 0.0] # pitch, yaw+arm = [0.2, -0.2, 0.0, 1.28, 0.0, 0.0, 0.0] # the Menagerie stand keyframe's right arm+other_arm = [0.2, 0.2, 0.0, 1.28, 0.0, 0.0, 0.0]++[kick] # the kick controller (kick.py): stop, shift the weight onto the support foot, wind+gains_kp = [700, 700, 500, 900, 300, 300] # up, swing the foot through a target, recover, walk on;+gains_kd = [12, 12, 8, 15, 6, 6] # leg joints on PD at these gains (motor torques clipped)++[mounts]+wrist = "the body <side>_mount at the rubber hand of <side>_wrist_yaw_link, +z along the forearm"+cameras = ["head_left", "head_right"] # a stereo pair in front of the head, 5 cm apart, 58 degree vertical field of+ # view: the G1's head depth camera (Intel RealSense D435i: 50 mm baseline,+ # 87 x 58 degree depth field of view, S3); its tilt is a mount parameter+head_pitch_rad = 0.6++# ---------------------------------------------------------------------------------------------------------------------+# The motors (bodies/servo.py Actuators: every G1 joint's torque goes through its curve) and the low-level plan+# interface of the optional joint-group arbiter (bodies/control/arbiter.py, from the two-mode pilot of 2026-10-08).++[motors] # Unitree actuator torque-speed curves (S6): below X1 rad/s the peak torque is Y1+ # (torque along the motion) or Y2 (against it, braking); from X1 it falls+ # linearly to 0 at X2. The URDF effort (actuator ctrlrange) caps it as well.+N7520_14p3 = { X1 = 22.63, X2 = 35.52, Y1 = 71.0, Y2 = 83.3 }+N7520_22p5 = { X1 = 14.5, X2 = 22.7, Y1 = 111.0, Y2 = 131.0 }+N5020_16 = { X1 = 30.86, X2 = 40.13, Y1 = 24.8, Y2 = 31.9 }+N5020_16_x2 = { X1 = 30.86, X2 = 40.13, Y1 = 49.6, Y2 = 63.8 } # ankles, waist roll / pitch: two N5020-16 in a+W4010_25 = { X1 = 15.3, X2 = 24.76, Y1 = 4.8, Y2 = 8.6 } # parallel linkage (S6; URDF effort 50 N m)+[motors.assign] # per joint (unitree_rl_lab unitree.py UNITREE_G1_29DOF_CFG, S6)+hip_pitch = "N7520_14p3"+hip_roll = "N7520_22p5"+hip_yaw = "N7520_14p3"+knee = "N7520_22p5"+ankle_pitch = "N5020_16_x2"+ankle_roll = "N5020_16_x2"+waist_yaw = "N7520_14p3"+waist_roll = "N5020_16_x2"+waist_pitch = "N5020_16_x2"+shoulder_pitch = "N5020_16"+shoulder_roll = "N5020_16"+shoulder_yaw = "N5020_16"+elbow = "N5020_16"+wrist_roll = "N5020_16"+wrist_pitch = "W4010_25"+wrist_yaw = "W4010_25"++[lowlevel] # the low-level interface (bodies/control/arbiter.py): plan rows, servo gains+groups = ["legs", "waist", "arms"] # Unitree SDK joint order: left leg 6, right leg 6, waist yaw / roll / pitch,+ # left arm 7, right arm 7+row_dt_s = 0.01 # one plan row per control step; the PD interpolates between rows at 1 kHz+max_rows = 300 # a plan covers at most 3 s+min_plan_interval_steps = 2 # a new plan at most every 20 ms (50 Hz): the agent's loop runs outside the sim+kp_max = { legs = 1000.0, waist = 500.0, arms = 400.0 } # "estimate": the motor drivers accept any gain (LowCmd);+kd_max = { legs = 20.0, waist = 15.0, arms = 10.0 } # these caps keep the 1 kHz PD stable in simulation+[lowlevel.handover] # a group handed back to the walking policy (legs) or to the body's hold+blend_steps = 30 # legs: targets blended to the policy's stance (0.3 s), at the stand gains+blend_steps_after_skill = 0 # the kick ends in the stance itself: the policy takes over at once (as kick.py)+stand_kp = [700, 700, 500, 900, 300, 300]+stand_kd = [12, 12, 8, 15, 6, 6]+stable_tilt_rad = 0.10 # then the policy, re-initialised, takes the legs and holds a zero command until+stable_omega_rad_s = 2.0 # the robot is confirmed stable: over the last stable_window steps (half a gait+stable_com_speed_m_s = 0.20 # period) pelvis tilt, angular rate and CoM speed stayed under these (marching in+stable_window = 40 # place sways up to 0.07 rad, 1.4 rad/s, 0.13 m/s); the agent's command applies+timeout_steps = 200 # from then on; not confirmed in 2 s: logged (stable_timeout), let through+++# ---------------------------------------------------------------------------------------------------------------------+# Self-collision (real limits B0, 2026-10-09: the real arm cannot pass through its own body, so the simulated one+# cannot either). bodies/selfcollision.py turns this into MuJoCo <pair>s at mount(): parts by body name (without the+# prefix; a body matching nothing takes its parent's part, one below an arm is that arm's tool), the rules say which+# parts touch, the exclusions say which pairs do not and why. Automatic exclusions (not listed): geoms of one rigid+# group (a link, its mount, its tool) and of two rigid groups joined by one joint (the joint's housing).+# Recorded during play (rig.self_collisions()): events, time in contact, peak force; above warn_force_n a warning.+# No penalty yet (the sports decide). Check: python -m bodies.selfcollision check <robot> (CI: check-robot-limits).+[self_collision]+parts.left_arm = "left_(shoulder_(pitch|roll|yaw)|elbow|wrist_(roll|pitch|yaw))_link"+parts.right_arm = "right_(shoulder_(pitch|roll|yaw)|elbow|wrist_(roll|pitch|yaw))_link"+parts.body = "pelvis|waist_(yaw|roll)_link|torso_link"+parts.left_leg = "left_(hip_(pitch|roll|yaw)|knee|ankle_(pitch|roll))_link"+parts.right_leg = "right_(hip_(pitch|roll|yaw)|knee|ankle_(pitch|roll))_link"+rules = { arm_body = true, arm_arm = true, tool_own_arm = true, same_arm = false, leg_leg = true, same_leg = true }+ # leg_leg / same_leg (audit, Changhe 2026-10-10): the walking policy's sidesteps+ # crossed the legs by up to 52 mm; shin x foot of one leg (the ankle between)+ignore_geoms = "(left|right)_foot_strike" # the kick's strike boxes (contype 8): sensing volumes, not the shell+warn_force_n = 20.0 # a self-collision event above this peak normal force is a warning+exclude = [] # none beyond the automatic ones: the Menagerie collision meshes clear each other+ # at the stand pose and in every random legal pose class (check: 0 structural)+[self_collision.source]+warn_force_n = "ESTIMATE: no vendor publishes a self-contact threshold for this robot; the Franka's collision threshold (20 N, bodies/franka_panda S4) for every body, so one rule reads the same everywhere"++[sources]+S1 = "Unitree Robotics, G1 product page, specifications: https://www.unitree.com/g1/ (1,320 mm, about 35 kg, 23 DOF base model / 29-43 DOF EDU, knee 90 N m, arm load about 2 kg, arm span about 0.45 m, depth camera + 3D LiDAR)"+S2 = "Unitree Robotics, g1_description g1_29dof_rev_1_0.urdf joint <limit> (effort, velocity, lower, upper), as shipped in unitree_rl_gym resources/robots/g1_description (commit 276801e46c5d433564f24658bac64f254b7d2d4b): https://github.com/unitreerobotics/unitree_rl_gym"+S3 = "Intel RealSense D435i datasheet (stereo baseline 50 mm, depth field of view 87 x 58 degrees): https://www.intelrealsense.com/depth-camera-d435i/"+S4 = "MuJoCo Menagerie unitree_g1 (BSD-3-Clause), commit f054586a8e90465d49ee5be15335c4a0c7f57caf: https://github.com/google-deepmind/mujoco_menagerie/tree/main/unitree_g1"+S5 = "Unitree unitree_rl_gym (BSD-3-Clause), deploy/pre_train/g1/motion.pt, deploy/deploy_mujoco/configs/g1.yaml, deploy/deploy_real/configs/g1.yaml, legged_gym/envs/g1/g1_config.py, commit 276801e46c5d433564f24658bac64f254b7d2d4b"+S6 = "Unitree unitree_rl_lab, source/unitree_rl_lab/unitree_rl_lab/assets/robots/unitree_actuators.py (UnitreeActuator torque-speed curves) and unitree.py (UNITREE_G1_29DOF_CFG joint-to-motor assignment), commit 4960b84732b0c2ec593dccbfe963fda1bcd7b1e3"+S7 = "Unitree unitree_sdk2 (BSD-3-Clause), commit 63096d0: LowCmd (q, dq, kp, kd, tau per motor) is sent to the motors unchanged: no joint position, velocity or acceleration limiting in the SDK, https://github.com/unitreerobotics/unitree_sdk2"+S8 = "LeCAR-Lab FALCON (MIT, Copyright (c) 2025 Yuanhang Zhang), commit a967a6d8494f57777cf8d266a644ac8e45833301: sim2real/models/falcon/g1_29dof.onnx (the policy), sim2real/config/g1/g1_29dof_falcon.yaml (gains, default angles, scales, base height), humanoidverse/config/env/decoupled_locomotion_stand_height_waist_wbc_ma_diff_force.yaml and humanoidverse/envs/decoupled_locomotion/decoupled_locomotion_stand_height_waist_wbc_ma.py (command ranges, the 0.2 m/s speed threshold, the heading controller); Y. Zhang et al., FALCON: Learning Force-Adaptive Humanoid Loco-Manipulation, arXiv:2505.06776: https://github.com/LeCAR-Lab/FALCON"+S9 = "NVIDIA WBC-AGILE (Apache-2.0, Copyright (c) NVIDIA CORPORATION & AFFILIATES), commit 6830cf995714e81c91ce63247e8e016d36e28f14: agile/data/policy/velocity_height_g1/leapp/Velocity-Height-G1-History-v0/ (Velocity-Height-G1-History-v0.onnx: the policy with its observation, history and gains in the graph; .yaml: joint order, quaternion order, 50 Hz, feedback), agile/rl_env/tasks/locomotion_height/g1/velocity_height_env_cfg.py (observation terms, command ranges, 200 Hz physics, random upper-body motion while standing), agile/rl_env/mdp/actions/random_actions.py (the upper body at its default pose while walking), agile/rl_env/mdp/commands/commands_cfg.py (min_vel_norm 0.1), agile/rl_env/assets/robots/unitree_g1.py (DEFAULT_PELVIS_HEIGHT 0.72); H. Zhao et al., AGILE: A Comprehensive Workflow for Humanoid Loco-Manipulation Learning, arXiv:2603.20147: https://github.com/nvidia-isaac/WBC-AGILE"diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/falcon.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/falcon.pynew file mode 100644index 0000000000..2c51fd9717--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/falcon.py@@ -0,0 +1,192 @@+"""FALCON's walking policy for the G1 (optional; body.toml [walk.falcon]): a whole-body-trained walking and balance+policy that a sport may choose instead of Unitree's legs-only policy (body.py WalkPolicy, the default):++ rig = B.rig(model, prefix, hand="paddle", walker="falcon") # the arm actor's wrist residual on (below)+ rig = B.rig(model, prefix, hand="paddle", walker="falcon_legs") # FALCON drives the legs only (below)++Source: LeCAR-Lab/FALCON (MIT, Copyright (c) 2025 Yuanhang Zhang; policy/LICENSE.falcon), the released policy+sim2real/models/falcon/g1_29dof.onnx; Y. Zhang et al., "FALCON: Learning Force-Adaptive Humanoid Loco-Manipulation",+arXiv:2505.06776. Trained in IsaacGym on the 29-DOF G1 (PD at 200 Hz, policy at 50 Hz) with upper-body motions+replayed on the arms and external forces on the hands (x, y within +-40 N, z within -50..5 N). policy/falcon_g1_29dof.npz holds the ONNX graph's weights+unchanged (float32, evaluated in float64; tools/export_falcon.py) and a parity fixture: observations with the outputs+onnxruntime gave for them (parity() checks this port against them).++The network: two MLPs on the same input, 575 -> 512 -> 256 -> 128 (ELU) -> 15 (legs + waist) and -> 14 (arms). The+observation is the last 5 frames (oldest first) of 115 numbers, its terms sorted by name as FALCON's deployment code+(sim2real/rl_policy, config/g1/g1_29dof_falcon.yaml) builds them:+ [0:29] last action (clipped to +-100) [29:32] pelvis angular velocity (pelvis frame) x 0.25+ [32] yaw-rate command [33] base height command (m) x 2+ [34:36] vx, vy command (m/s, robot frame) [36] stepping flag (1 stepping, 0 standing)+ [37:40] waist yaw, roll, pitch command (rad) [40:69] q - default (29 joints, Unitree's motor order)+ [69:98] joint speeds x 0.05 [98:101] gravity (0, 0, -1) in the pelvis frame+ [101:115] arm joint targets (rad; left arm 7, right arm 7)+Targets: default + 0.25 x action. On the rig (body.py G1Rig) and under the arbiter (bodies/control/arbiter.py) the+legs follow FALCON's 12 leg targets on its PD gains (body.toml [walk.falcon] kp, kd); the waist and the arms stay the+sport's (the rig's u, the arbiter's plans or holds): FALCON gets the arm targets and the waist's yaw as its commands+(roll and pitch go in as 0: training never commanded them, their input weights are untrained), its waist targets are+not used, and of its arm actor's output (a residual that FALCON adds to the arm targets) only the wrists' part is+kept, clipped to wrist_residual_max_rad (without it that output runs away within seconds and the standing robot slides+off; measured on this model).++walker="falcon_legs" (Falcon(decl, arm_actor=False)): the arm actor's output is not applied at all and its part of the+last action in the observation is 0 (as if the arms tracked their targets perfectly), no wrist residual: the arms+are wholly the sport's (the rig's servo, the arbiter's plans and holds). This is how basketball's low level (PR #58,+sports/basketball3x3/falcon.py) and the fencing study (docs/screening/fencing) use FALCON. Without the residual but+with the unapplied arm output fed back the standing robot shuffles away (2.5 m in 5 s, PR #58); with it zeroed it+stands and walks (conformance 3b: 10 s at rest with the paddle 7.3 cm, "falcon" 1.4 cm; on guard with an epee 0.08 m+and 2 deg, "falcon" 0.03 m and 10 deg; footwork at the joystick cap 0.77 m/s forward, 0.86 back, no fall in 34+footwork and disturbance runs), and the arms follow their plans undisturbed: on the same 7 reachable targets a re-planned arm+thrust comes within 0.4-0.8 cm (median), 1.0-2.2 cm with "falcon", though "falcon" is closer at the planned end+time (4.4 against 5.7-6.6 cm; fencing F0, docs/screening/fencing.md). Its waist output is not used either way (the+waist is the sport's).++As in its training: a walking speed |(vx, vy)| below 0.2 m/s is 0; here a yaw rate below 0.2 rad/s with no speed is 0+too, then the robot stands (stepping flag 0). Its yaw-rate input was a heading controller there, 0.5 (heading target -+heading) clipped to +-1, so here the yaw-rate command turns a heading target and the input is the command plus that+feedback (the robot keeps its heading when walking straight), clipped to the training range; base height 0.75 m.+FALCON saw a waist command (yaw within +-1 rad) only when standing: a sport that turns the waist while walking is+outside its training. Deterministic: plain float64 numpy.+"""++from __future__ import annotations++import math+from pathlib import Path++import numpy as np++HERE = Path(__file__).resolve().parent+N_LOWER, N_ARM, N_FRAME = 15, 14, 115+++def mlp(layers, x):+ """An actor: Gemm + ELU per hidden layer, a linear output."""+ for k, (w, b) in enumerate(layers):+ x = w @ x + b+ if k < len(layers) - 1:+ x = np.where(x > 0, x, np.expm1(np.minimum(x, 0.0)))+ return x+++def gravity_in(quat):+ """(0, 0, -1) in the frame of the quaternion (w, x, y, z)."""+ w, x, y, z = quat+ return np.array([2 * (-z * x + w * y), -2 * (z * y + w * x), 1 - 2 * (w * w + z * z)])+++def heading_of(quat):+ """The yaw (rad) of the quaternion (w, x, y, z)."""+ w, x, y, z = quat+ return math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))+++class Falcon:+ """FALCON for one robot: the observation history, the last action, the heading target; step() every 20 ms.+ For the rig like body.py WalkPolicy (default: the legs' stance, reset, state); its step() sees more."""++ WRISTS = [4, 5, 6, 11, 12, 13] # of the 14 arm joints (left, right): the wrists' roll, pitch, yaw++ def __init__(self, decl, arm_actor=True):+ F = decl["walk"]["falcon"]+ self.arm_actor = bool(arm_actor) # False: walker "falcon_legs" (no residual, its arm output fed back as 0)+ z = np.load(HERE / F["weights"])+ self.lower, self.upper = (+ [(z[f"{a}_w{k}"].astype(float), z[f"{a}_b{k}"].astype(float)) for k in range(4)] for a in ("lower", "upper")+ )+ self.fixture = z["parity_obs"], z["parity_action"]+ self.default_all = np.array(F["default_angles"], float) # 29 joints, Unitree's motor order+ self.default = self.default_all[:12] # the legs' stance (as WalkPolicy.default)+ self.kp, self.kd = np.array(F["kp"], float), np.array(F["kd"], float) # the legs' PD (12)+ self.scale, self.clip = float(F["action_scale"]), float(F["action_clip"])+ self.history_len = int(F["history"])+ S = F["obs_scales"]+ self.s_ang, self.s_vel, self.s_height = S["ang_vel"], S["dof_vel"], S["base_height"]+ self.height = float(F["base_height_m"])+ self.cmd_max = np.array(F["command_max"], float)+ self.speed_min, self.turn_min = float(F["speed_min_m_s"]), float(F["turn_min_rad_s"])+ self.k_heading, self.heading_err_max = float(F["heading_gain"]), float(F["heading_error_max_rad"])+ self.dt = 1.0 / float(F["rate_hz"])+ self.wrist_max = float(F["wrist_residual_max_rad"])+ self.reset()++ def reset(self):+ self.action = np.zeros(N_LOWER + N_ARM)+ self.history = np.zeros(self.history_len * N_FRAME)+ self.heading = None # the heading target: taken from the robot when it starts stepping+ self.targets = self.default_all[:N_LOWER].copy()++ def command(self, cmd):+ """The walking command as FALCON was trained on it: clipped to its range, small speeds and turns zeroed."""+ c = np.clip(np.asarray(cmd, float), -self.cmd_max, self.cmd_max)+ if math.hypot(c[0], c[1]) < self.speed_min:+ c[0:2] = 0.0+ if abs(c[2]) < self.turn_min:+ c[2] = 0.0+ return c++ def frame(self, quat, gyro, q, dq, cmd, arms, waist_yaw):+ """One observation frame (115) and the next heading target."""+ c = self.command(cmd)+ stepping = bool(np.any(c != 0.0))+ yaw = heading_of(quat)+ wz = 0.0+ if stepping:+ ref = yaw if self.heading is None else self.heading + c[2] * self.dt+ err = (ref - yaw + math.pi) % (2 * math.pi) - math.pi+ err = min(max(err, -self.heading_err_max), self.heading_err_max)+ wz = min(max(c[2] + self.k_heading * err, -self.cmd_max[2]), self.cmd_max[2])+ heading = yaw + err+ else:+ heading = None+ f = np.empty(N_FRAME)+ f[0:29] = self.action+ f[29:32] = np.asarray(gyro, float) * self.s_ang+ f[32] = wz+ f[33] = self.height * self.s_height+ f[34:36] = c[0:2]+ f[36] = float(stepping)+ f[37:40] = (waist_yaw, 0.0, 0.0) # yaw, roll, pitch+ f[40:69] = np.asarray(q, float) - self.default_all+ f[69:98] = np.asarray(dq, float) * self.s_vel+ f[98:101] = gravity_in(quat)+ f[101:115] = arms+ return f, heading++ def forward(self, obs):+ """The two actors on an observation (575): the action (29: legs + waist, arms), clipped as in deployment."""+ return np.clip(np.r_[mlp(self.lower, obs), mlp(self.upper, obs)], -self.clip, self.clip)++ def step(self, quat, gyro, q, dq, cmd, arms, waist_yaw):+ """One policy tick. quat (w, x, y, z) and gyro (pelvis frame) of the pelvis; q, dq: the 29 joints in Unitree's+ motor order (legs, waist yaw / roll / pitch, left arm, right arm); cmd: vx, vy, wz (robot frame); arms: the 14+ arm targets (left, right); waist_yaw: the waist's yaw command. Returns the 15 leg + waist targets."""+ f, self.heading = self.frame(quat, gyro, q, dq, cmd, arms, waist_yaw)+ self.history = np.r_[self.history[N_FRAME:], f]+ self.action = self.forward(self.history)+ if not self.arm_actor: # falcon_legs: the arm actor's output is never applied, so it is not fed back+ self.action[N_LOWER:] = 0.0+ self.targets = self.default_all[:N_LOWER] + self.scale * self.action[:N_LOWER]+ return self.targets++ def wrist_offsets(self):+ """The arm actor's residual on the six wrist joints (rad), clipped: added to their targets (0 for falcon_legs)."""+ if not self.arm_actor:+ return np.zeros(len(self.WRISTS))+ return np.clip(self.scale * self.action[N_LOWER:][self.WRISTS], -self.wrist_max, self.wrist_max)++ def wrist_torque(self, kp):+ """The residual as extra PD torque on the 14 arm joints (left, right) at their gains kp: kp x wrist_offsets()+ on the wrists, 0 elsewhere (= the wrists' targets moved by the offsets). The rig and the arbiter add it while+ FALCON has the legs."""+ t = np.zeros(N_ARM)+ t[self.WRISTS] = np.asarray(kp, float)[self.WRISTS] * self.wrist_offsets()+ return t++ def state(self):+ """The policy's memory (last action, history, heading target): for hashing and copying."""+ return np.r_[self.action, self.history, self.heading is not None, self.heading or 0.0]++ def parity(self):+ """max |this port - onnxruntime| over the fixture stored with the weights (tools/export_falcon.py)."""+ obs, ref = self.fixture+ return float(max(np.max(np.abs(self.forward(o.astype(float)) - r)) for o, r in zip(obs, ref)))diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/kick.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/kick.pynew file mode 100644index 0000000000..ecfba744b8--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/kick.py@@ -0,0 +1,313 @@+"""The G1's kick: a model-based whole-leg motion (the walking policy cannot kick), run on the legs' PD at the kick+gains (body.toml [kick]) with the motors' torque limits.++ stand the leg targets go from where the policy left them to the stance (0.25 s), feet down+ shift the pelvis moves over the support foot (0.55 s); a centre-of-mass loop keeps the CoM over the support+ foot's centre during the whole kick (the support foot stays where it is in the world)+ lift the kicking foot rises by `height` and winds back 0.15 m (0.25 s)+ swing the foot travels `reach` beyond the support foot's toe line along the robot's forward axis at `speed`+ (a minimum-jerk profile: its peak speed is about 1.9 x the mean), the instep at ball height+ recover follow-through, the foot back under the hip and down, the pelvis back between the feet, stand; then the+ walking policy takes the legs again (its memory reset)+Each control step the leg targets come from inverse kinematics of the two feet (position and a level orientation,+the support foot fixed in the world, the kicking foot on its path) relative to the desired pelvis pose. The kick+does not aim: the robot aims by walking and turning before it (the foot moves along its forward axis)."""+from __future__ import annotations++import math++import numpy as np++FOOT_STRIKE_FORWARD = 0.035 # the strike box's centre ahead of the ankle (model.xml)+BACK = -0.10 # the wind-up: the foot 10 cm behind where it stood+FOLLOW = 0.10 # with a target: the swing ends this far beyond it+STRIKE_IN_SITE = np.array([0.035, 0.0, -0.02]) # the strike box's centre in the foot site's frame (model.xml)+OUTSIDE = 0.012 # the balance target this much outside the support foot's centre line (the+ # swinging leg pulls the body toward the kicking side)+STAND_MAX = 60 # the stand waits until both feet are down and still (or this)+LOWER_MAX = 40 # the lowering goes on until the kicking foot is down (or this)+HOLD_MAX = 60 # the hold lasts until the capture point is within 1 cm of the target (or this)+CROUCH = 0.05 # the pelvis goes down this much for the kick (the support knee bent more)+OMEGA = math.sqrt(9.81 / 0.68) # the linear inverted pendulum's natural frequency at the G1's CoM height+++def minjerk(s):+ s = min(max(s, 0.0), 1.0)+ return 10 * s ** 3 - 15 * s ** 4 + 6 * s ** 5+++def yaw_of(R):+ return math.atan2(R[1, 0], R[0, 0])+++def rot_z(a):+ c, s = math.cos(a), math.sin(a)+ return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])+++class Kick:+ def __init__(self, rig, d, foot="right", speed=3.0, height=0.07, reach=0.22, target=None, direction=None):+ import mujoco as mj+ self.mj, self.rig, self.m = mj, rig, rig.m+ K = rig.B.decl["kick"]+ self.kp, self.kd = np.array(K["gains_kp"] * 2, float), np.array(K["gains_kd"] * 2, float)+ self.kin = mj.MjData(self.m)+ self.foot = foot+ self.sup = "left" if foot == "right" else "right"+ site = lambda n: mj.mj_name2id(self.m, mj.mjtObj.mjOBJ_SITE, rig.prefix + n)+ self.site = {"left": site("left_foot"), "right": site("right_foot")}+ self.legcols = {"left": np.arange(0, 6), "right": np.arange(6, 12)}+ p_pel, R_pel = rig.pelvis(d)+ self.yaw0 = yaw_of(R_pel)+ self.Rlevel = rot_z(self.yaw0)+ self.fw = self.Rlevel[:, 0]+ self.left_ax = self.Rlevel[:, 1]+ self.p0 = p_pel.copy()+ self.feet0 = {s: d.site_xpos[self.site[s]].copy() for s in ("left", "right")}+ self.q_start = d.qpos[rig.lqadr].copy()+ self.q = self.q_start.copy()+ self.com_off = np.zeros(2)+ self.com_fast = np.zeros(2)+ self.hold_extra = 0+ self.stand_extra = 0+ self.lower_extra = 0+ self.speed, self.height, self.reach = float(speed), float(height), float(reach)+ self.target = None if target is None else np.asarray(target, float).copy()+ if direction is not None: # the swing's direction (world, horizontal); default: forward+ a = np.array([direction[0], direction[1], 0.0], float)+ self.aim = a / max(np.linalg.norm(a), 1e-9)+ else:+ self.aim = self.fw.copy()+ dist = 0.15 + reach + 0.10 # the swing's nominal length: its duration (`speed` is the nominal+ n_sw = max(6, int(round(1.875 * dist / max(speed, 0.5) / rig.dt))) # peak; the real one is about 0.7 x)+ self.phases = [("stand", 40), ("shift", 140), ("hold", 30), ("lift", 30), ("swing", n_sw), ("follow", 10),+ ("retract", 50), ("lower", 40), ("unshift", 1), ("settle", 1)]+ self.delta = np.zeros(3)+ self.i, self.pi, self.done = 0, 0, False+ self.log = []+ self.ff = np.zeros(12)+ self.ik_err = {"left": 0.0, "right": 0.0}+ idx = [self.m.jnt_qposadr.tolist().index(a) for a in rig.lqadr]+ self.qlo, self.qhi = self.m.jnt_range[idx, 0].copy(), self.m.jnt_range[idx, 1].copy()+ self.qlo[[3, 9]] = 0.15 # the knees stay bent (no straight-leg singularity)+ self.qpel0 = np.array([math.cos(self.yaw0 / 2), 0.0, 0.0, math.sin(self.yaw0 / 2)])++ # ------------------------------------------------------------------ targets+ def _phase(self):+ name, n = self.phases[self.pi]+ return name, n, self.i / n++ def _pelvis_target(self, name, s):+ """The pelvis moves by `delta` (the vector that puts the centre of mass over the support foot's centre,+ measured when the shift starts), plus the balance correction while on one foot."""+ if name in ("stand", "settle"):+ k = 0.0+ elif name == "shift":+ k = minjerk(s)+ elif name == "unshift":+ k = 1.0 - minjerk(s)+ else:+ k = 1.0+ off = self.com_off + self.com_fast+ corr = self.fw * off[0] + self.left_ax * off[1]+ return self.p0 + self.delta * k + corr++ def _path(self):+ """The kicking foot's path (foot site, world), set when the stance is reached, along `aim` from where the foot+ stood: wound back 10 cm and lifted to the strike height, then swung forward to its end point, back above+ where it stood and down. Without a target the end point is `reach` beyond the support foot's toe line at+ `height`; with one (where the strike box's centre should meet the ball) the end is 10 cm beyond it, the+ height is the target's and the path is shifted sideways onto it (each within the leg's reach: at most 8 cm+ sideways, 3-12 cm up, 5-32 cm beyond the toe line)."""+ f0, sup = self.feet0[self.foot], self.feet0[self.sup]+ aim = self.aim+ lat = np.array([-aim[1], aim[0], 0.0])+ toe = float((sup - f0) @ aim)+ if self.target is None:+ x_end, side, h = toe + self.reach, 0.0, self.height+ else:+ rel = self.target - self.Rlevel @ STRIKE_IN_SITE - f0+ x_end, side, h = float(rel @ aim) + FOLLOW, float(rel @ lat), float(rel[2])+ x_end = float(np.clip(x_end, toe + 0.05, toe + 0.32))+ side = float(np.clip(side, -0.08, 0.08))+ h = float(np.clip(h, 0.03, 0.12))+ self.x_back, self.x_end, self.side, self.h = BACK, x_end, side, h++ def _at(self, x, z, side_k=1.0):+ f0 = self.feet0[self.foot]+ lat = np.array([-self.aim[1], self.aim[0], 0.0])+ return f0 + self.aim * x + lat * (self.side * side_k) + np.array([0.0, 0.0, z])++ def _kick_foot_target(self, name, s):+ f0 = self.feet0[self.foot]+ if name in ("stand", "shift", "settle", "unshift"):+ return f0.copy()+ if not hasattr(self, "x_end"):+ self._path()+ k = minjerk(s)+ if name == "lift": # wound back and up (and over onto the strike line)+ return self._at(self.x_back * k, self.h * k, k)+ if name == "swing": # forward through the strike point+ return self._at(self.x_back + (self.x_end - self.x_back) * k, self.h)+ if name == "follow":+ return self._at(self.x_end + 0.02, self.h)+ if name == "retract": # back above where it stood, at the strike height (clear of a ball)+ return self._at((self.x_end + 0.02) * (1 - k), self.h + 0.02 * math.sin(math.pi * k), 1 - k)+ if name == "lower": # down to 1 cm below where it stood (a firm landing)+ return f0 + np.array([0, 0, self.h - (self.h + 0.01) * k])+ return f0.copy()++ # ------------------------------------------------------------------ inverse kinematics of the feet+ def _ik(self, d, p_pel, foot_targets, iters=10):+ mj, m, kd, rig = self.mj, self.m, self.kin, self.rig+ kd.qpos[:] = d.qpos+ j = rig.fqadr+ kd.qpos[j:j + 3] = p_pel+ kd.qpos[j + 3:j + 7] = self.qpel0+ q = self.q.copy()+ jp = np.zeros((3, m.nv)); jr = np.zeros((3, m.nv))+ for _ in range(iters):+ kd.qpos[rig.lqadr] = q+ mj.mj_kinematics(m, kd)+ mj.mj_comPos(m, kd)+ for side in ("left", "right"):+ sid = self.site[side]+ p = kd.site_xpos[sid]+ R = kd.site_xmat[sid].reshape(3, 3)+ e = np.r_[foot_targets[side] - p, 0.5 * (np.cross(R[:, 0], self.Rlevel[:, 0]) ++ np.cross(R[:, 1], self.Rlevel[:, 1]) ++ np.cross(R[:, 2], self.Rlevel[:, 2]))]+ mj.mj_jacSite(m, kd, jp, jr, sid)+ cols = rig.lvadr[self.legcols[side]]+ J = np.vstack([jp[:, cols], jr[:, cols]])+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-3 * np.eye(6), e)+ n = np.abs(dq).max()+ if n > 0.15: # small steps: stay on the bent-knee branch+ dq *= 0.15 / n+ c = self.legcols[side]+ q[c] = np.clip(q[c] + dq, self.qlo[c], self.qhi[c])+ self.ik_err[side] = float(np.linalg.norm(e[:3]))+ return q++ def _nominal_pelvis(self, d, q_legs):+ """The level pelvis position that the leg angles q_legs put above the feet where they stand."""+ mj, m, kd, rig = self.mj, self.m, self.kin, self.rig+ kd.qpos[:] = d.qpos+ j = rig.fqadr+ kd.qpos[j:j + 3] = 0.0+ kd.qpos[j + 3:j + 7] = (math.cos(self.yaw0 / 2), 0.0, 0.0, math.sin(self.yaw0 / 2))+ kd.qpos[rig.lqadr] = q_legs+ mj.mj_kinematics(m, kd)+ off = [self.feet0[sd] - kd.site_xpos[self.site[sd]] for sd in ("left", "right")]+ return 0.5 * (off[0] + off[1])++ def _balance_target(self, d=None):+ """The support foot's centre (where it is now: it may slip or turn under a hard swing), a little outside."""+ out = self.left_ax * (OUTSIDE if self.sup == "left" else -OUTSIDE)+ p = self.feet0[self.sup] if d is None else d.site_xpos[self.site[self.sup]]+ return p + self.fw * FOOT_STRIKE_FORWARD + out++ def _site_vel(self, d, side):+ v = np.zeros(6)+ self.mj.mj_objectVelocity(self.m, d, self.mj.mjtObj.mjOBJ_SITE, self.site[side], v, 0)+ return v[3:]++ def _com_vel(self, d, com):+ prev = getattr(self, "_com_prev", None)+ self._com_prev = com.copy()+ return np.zeros(3) if prev is None else (com - prev) / self.rig.dt++ def _support_ff(self, d, name):+ """Leg torques that carry the robot's weight (static equilibrium with the feet's contact forces): tau =+ bias - J_c^T F, the weight split between the feet by where the centre of mass is (all of it on the support+ foot while the other is off the ground). Without it the stance legs sag under the PD and the kick drifts."""+ mj, m, rig = self.mj, self.m, self.rig+ com = d.subtree_com[rig.base_body].copy()+ W = float(m.body_subtreemass[rig.base_body]) * 9.81+ one_foot = name in ("lift", "swing", "follow", "retract")+ if one_foot:+ share = {self.sup: 1.0, self.foot: 0.0}+ else:+ pl, pr = d.site_xpos[self.site["left"]], d.site_xpos[self.site["right"]]+ ax = pl[:2] - pr[:2]+ t = float(np.clip((com[:2] - pr[:2]) @ ax / max(ax @ ax, 1e-9), 0.0, 1.0))+ share = {"left": t, "right": 1.0 - t}+ gen = np.zeros(m.nv)+ jp = np.zeros((3, m.nv)); jr = np.zeros((3, m.nv))+ for side, w in share.items():+ if w <= 0:+ continue+ p = d.site_xpos[self.site[side]]+ F = np.array([0.0, 0.0, w * W])+ r = np.array([com[0] - p[0], com[1] - p[1], 0.0])+ mj.mj_jacSite(m, d, jp, jr, self.site[side])+ gen += jp.T @ F + jr.T @ np.cross(r, F)+ return d.qfrc_bias[rig.lvadr] - gen[rig.lvadr]++ # ------------------------------------------------------------------ one control step+ def step(self, d):+ name, n, s = self._phase()+ rig = self.rig+ if name == "stand":+ k = minjerk(s)+ stand = rig.policy.default+ self.q = self.q_start + (stand - self.q_start) * k+ q = self.q+ if self.i == n - 1 and self.stand_extra < STAND_MAX:+ z = [d.site_xpos[self.site[sd]][2] for sd in ("left", "right")]+ vz = [np.linalg.norm(self._site_vel(d, sd)) for sd in ("left", "right")]+ if abs(z[0] - z[1]) > 0.006 or max(vz) > 0.05: # a foot still in the air or moving: wait+ self.stand_extra += 1+ self.ff = self._support_ff(d, name)+ return q.copy() # (the step counter stays)+ if self.i == n - 1: # the stance reached: the feet as they are now, the pelvis+ self.feet0 = {sd: d.site_xpos[self.site[sd]].copy() for sd in ("left", "right")}+ p_now, R_now = rig.pelvis(d) # the pelvis as it stands (the support torques hold it+ self.p0 = p_now.copy() # there: no sag, no creeping); its tilt is kept+ self.qpel0 = np.zeros(4)+ self.mj.mju_mat2Quat(self.qpel0, R_now.reshape(-1))+ c = self._balance_target()+ dl = c - d.subtree_com[rig.base_body]+ self.delta = np.array([dl[0], dl[1], -CROUCH]) # and a little lower: room for the support leg+ mid = 0.5 * (self.feet0["left"] + self.feet0["right"]) + self.fw * FOOT_STRIKE_FORWARD+ self.com_start = np.r_[mid[:2], 0.0] # the shift starts from the middle of the feet+ else:+ if name == "unshift" and self.i == 0: # both feet down again: where the kicking foot landed+ self.feet0[self.foot] = d.site_xpos[self.site[self.foot]].copy()+ self.mid_end = 0.5 * (self.feet0["left"] + self.feet0["right"]) + self.fw * FOOT_STRIKE_FORWARD+ if True: # balance: the capture point (CoM + v / omega) onto its+ com = d.subtree_com[rig.base_body] # target (the support foot's centre; on the way there during+ v = self._com_vel(d, com) # the shifts), the pelvis moved by the error+ bt = self._balance_target(d)+ if name == "shift":+ c = self.com_start + (bt - self.com_start) * minjerk(s)+ elif name == "unshift":+ c = bt + (self.mid_end - bt) * minjerk(s)+ elif name == "settle":+ c = self.mid_end+ else:+ c = bt+ xi = com[:2] + v[:2] / OMEGA+ err = c[:2] - xi+ e_loc = np.array([err @ self.fw[:2], err @ self.left_ax[:2]])+ self.com_off = np.clip(self.com_off + 0.05 * e_loc, -0.08, 0.08) # slow integral of the error+ self.com_fast = np.clip(1.3 * e_loc, -0.06, 0.06) # plus a direct term+ if name == "lower" and self.i == n - 1 and self.lower_extra < LOWER_MAX and \+ d.site_xpos[self.site[self.foot]][2] > self.feet0[self.foot][2] + 0.01:+ self.lower_extra += 1 # the foot not down yet: keep lowering+ self.i -= 1+ if name == "hold" and self.i == n - 1 and np.linalg.norm(e_loc) > 0.01 and self.hold_extra < HOLD_MAX:+ self.hold_extra += 1 # not settled yet: hold on+ self.i -= 1+ p_pel = self._pelvis_target(name, s)+ feet = {self.sup: self.feet0[self.sup], self.foot: self._kick_foot_target(name, s)}+ self.q = self._ik(d, p_pel, feet)+ q = self.q+ self.ff = self._support_ff(d, name)+ self.i += 1+ if self.i >= n:+ self.i = 0+ self.pi += 1+ if self.pi >= len(self.phases):+ self.done = True+ return q.copy()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/head_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/head_link.stlnew file mode 100644index 0000000000..9a687b6f68Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/head_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_pitch_link.stlnew file mode 100644index 0000000000..26fd113d1cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_roll_link.stlnew file mode 100644index 0000000000..64c8440b1cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_elbow_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_elbow_link.stlnew file mode 100644index 0000000000..2e3bcc0359Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_pitch_link.stlnew file mode 100644index 0000000000..fa2be04d4fBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_roll_link.stlnew file mode 100644index 0000000000..80f5c636f0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_yaw_link.stlnew file mode 100644index 0000000000..87acd9d78cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_knee_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_knee_link.stlnew file mode 100644index 0000000000..6e301535efBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_rubber_hand.stlnew file mode 100644index 0000000000..efcd64fe67Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_pitch_link.stlnew file mode 100644index 0000000000..9946d36c7bBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_roll_link.stlnew file mode 100644index 0000000000..47c8a6fc62Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_yaw_link.stlnew file mode 100644index 0000000000..ed007fd15eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_pitch_link.stlnew file mode 100644index 0000000000..7622aeda73Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_roll_link.stlnew file mode 100644index 0000000000..760a95030eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_yaw_link.stlnew file mode 100644index 0000000000..5d2dbbea9cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/left_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/logo_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/logo_link.stlnew file mode 100644index 0000000000..b3ef6197ffBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/logo_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/pelvis.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/pelvis.stlnew file mode 100644index 0000000000..bdec5cca41Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/pelvis.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/pelvis_contour_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/pelvis_contour_link.stlnew file mode 100644index 0000000000..dd144151eeBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/pelvis_contour_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_pitch_link.stlnew file mode 100644index 0000000000..302f4e98c0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_roll_link.stlnew file mode 100644index 0000000000..9b992e55e1Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_elbow_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_elbow_link.stlnew file mode 100644index 0000000000..161d89568aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_pitch_link.stlnew file mode 100644index 0000000000..ed34062feeBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_roll_link.stlnew file mode 100644index 0000000000..f544e5bb8eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_yaw_link.stlnew file mode 100644index 0000000000..66d519e64eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_knee_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_knee_link.stlnew file mode 100644index 0000000000..238d291e68Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_rubber_hand.stlnew file mode 100644index 0000000000..abcdfd3850Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_pitch_link.stlnew file mode 100644index 0000000000..8ed9408ffcBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_roll_link.stlnew file mode 100644index 0000000000..73642e511fBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_yaw_link.stlnew file mode 100644index 0000000000..9dd2c5aa83Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_pitch_link.stlnew file mode 100644index 0000000000..7aef0edb06Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_roll_link.stlnew file mode 100644index 0000000000..8ff67c7477Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_yaw_link.stlnew file mode 100644index 0000000000..163e832bfeBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/right_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/torso_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/torso_link_rev_1_0.stlnew file mode 100644index 0000000000..8bcdb1229dBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/torso_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/waist_roll_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/waist_roll_link_rev_1_0.stlnew file mode 100644index 0000000000..a0c249370eBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/waist_roll_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/waist_yaw_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/waist_yaw_link_rev_1_0.stlnew file mode 100644index 0000000000..291dbe7c71Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes/waist_yaw_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/head_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/head_link.stlnew file mode 100644index 0000000000..b39d344584Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/head_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_pitch_link.stlnew file mode 100644index 0000000000..08c38c32ceBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_roll_link.stlnew file mode 100644index 0000000000..41025f4050Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_elbow_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_elbow_link.stlnew file mode 100644index 0000000000..6fbc2a6fcbBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_pitch_link.stlnew file mode 100644index 0000000000..a9fcc7e61fBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_roll_link.stlnew file mode 100644index 0000000000..907db4c599Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_yaw_link.stlnew file mode 100644index 0000000000..9d2bcf3a84Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_knee_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_knee_link.stlnew file mode 100644index 0000000000..c9026a83d4Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_rubber_hand.stlnew file mode 100644index 0000000000..d7f9fce032Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_pitch_link.stlnew file mode 100644index 0000000000..5e3b5e0d0bBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_roll_link.stlnew file mode 100644index 0000000000..51635e335aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_yaw_link.stlnew file mode 100644index 0000000000..ccea58c6b9Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_pitch_link.stlnew file mode 100644index 0000000000..72db7ab8ffBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_roll_link.stlnew file mode 100644index 0000000000..2f3dad2903Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_yaw_link.stlnew file mode 100644index 0000000000..7a6f6c777dBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/left_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/lod.json b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/lod.jsonnew file mode 100644index 0000000000..fbf46adbbe--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/lod.json@@ -0,0 +1,224 @@+{+ "files": {+ "head_link.stl": {+ "sha256": "b0b7459e77a9b361cbd3b42d75cdf8f54280e5771ae6655890920a15048d31e0",+ "source": "head_link.STL",+ "source_sha256": "005fb67fbd3eff94aa8bf4a6e83238174e9f91b6721f7111594322f223724411",+ "triangles": 1184+ },+ "left_ankle_pitch_link.stl": {+ "sha256": "d61e414cbeb7f87800c8216959a5d4f34dea746fcdf390f6920f7abe7f473d82",+ "source": "left_ankle_pitch_link.STL",+ "source_sha256": "d49e3abc6f5b12e532062cd575b87b5ef40cd2a3fc18f54a1ca5bba4f773d51d",+ "triangles": 90+ },+ "left_ankle_roll_link.stl": {+ "sha256": "ac56add2f6f6c4cd2b3b33274d8b8a10b49acceed658cffc6b36cb4a317923ea",+ "source": "left_ankle_roll_link.STL",+ "source_sha256": "c4092af943141d4d9f74232f3cfa345afc6565f46a077793b8ae0e68b39dc33f",+ "triangles": 830+ },+ "left_elbow_link.stl": {+ "sha256": "6043e71584dec9e8832f1e1e0e061074ad868ed4cf83c63a2684a47650547b32",+ "source": "left_elbow_link.STL",+ "source_sha256": "fa752198accd104d5c4c3a01382e45165b944fbbc5acce085059223324e5bed3",+ "triangles": 111+ },+ "left_hip_pitch_link.stl": {+ "sha256": "7c5fe35b1d28fad41dbe2865dd6a395255ab54911e5702ea11553635b808261e",+ "source": "left_hip_pitch_link.STL",+ "source_sha256": "4725168105ee768ee31638ef22b53f6be2d7641bfd7cfefe803488d884776fa4",+ "triangles": 230+ },+ "left_hip_roll_link.stl": {+ "sha256": "7e0f0ff6a935a6bdf79dd79b7cd206b6225ef1d813aa81bad3b1e8627fae4f24",+ "source": "left_hip_roll_link.STL",+ "source_sha256": "91f25922ee8a7c3152790051bebad17b4d9cd243569c38fe340285ff93a97acf",+ "triangles": 244+ },+ "left_hip_yaw_link.stl": {+ "sha256": "cf13b4e40a0f06ee8f3cf89e5e2a962223912251dd8707a5f8474e66b3df7e5c",+ "source": "left_hip_yaw_link.STL",+ "source_sha256": "a16d88aa6ddac8083aa7ad55ed317bea44b1fa003d314fba88965b7ed0f3b55b",+ "triangles": 377+ },+ "left_knee_link.stl": {+ "sha256": "78fa5f7cfea0b075e32de93ee5303cfcb3fe30b21cbb9422d9d3e307ef513530",+ "source": "left_knee_link.STL",+ "source_sha256": "8d92b9e3d3a636761150bb8025e32514c4602b91c7028d523ee42b3e632de477",+ "triangles": 1226+ },+ "left_rubber_hand.stl": {+ "sha256": "03a87a3e22dddf9d77fb7ce8189ead6629e90cde3ad8479acf4480afd15f3926",+ "source": "left_rubber_hand.STL",+ "source_sha256": "cff2221a690fa69303f61fce68f2d155c1517b52efb6ca9262dd56e0bc6e70fe",+ "triangles": 2906+ },+ "left_shoulder_pitch_link.stl": {+ "sha256": "3163bd3e1e473e4fa48900a74c844a5647b46f6c6ae30e94a1d51183d026cc75",+ "source": "left_shoulder_pitch_link.STL",+ "source_sha256": "f0d1cfd02fcf0d42f95e678eeca33da3afbcc366ffba5c052847773ec4f31d52",+ "triangles": 224+ },+ "left_shoulder_roll_link.stl": {+ "sha256": "8fe40e7a3c4c62735346e16900e1bf3de7e9373273bb881f232c4a0be7ca470d",+ "source": "left_shoulder_roll_link.STL",+ "source_sha256": "fb9df21687773522598dc384f1a2945c7519f11cbc8bd372a49170316d6eee88",+ "triangles": 508+ },+ "left_shoulder_yaw_link.stl": {+ "sha256": "2ef7a79abb015d2fefed54ced7c46b7949c3c6dcb774b6500b2f59522a7ebd52",+ "source": "left_shoulder_yaw_link.STL",+ "source_sha256": "1aa97e9748e924336567992181f78c7cd0652fd52a4afcca3df6b2ef6f9e712e",+ "triangles": 316+ },+ "left_wrist_pitch_link.stl": {+ "sha256": "50baada401939b9ee9e8cd03988f1ad800727394491eef6f4dd88a136f8f1f12",+ "source": "left_wrist_pitch_link.STL",+ "source_sha256": "b251d8e05047f695d0f536cd78c11973cfa4e78d08cfe82759336cc3471de3a9",+ "triangles": 108+ },+ "left_wrist_roll_link.stl": {+ "sha256": "233ba263c0ad165460af24c49172d112c476333c64c23cc65f4eec130f75defc",+ "source": "left_wrist_roll_link.STL",+ "source_sha256": "edc387c9a0ba8c2237e9b296d32531426fabeb6f53e58df45c76106bca74148c",+ "triangles": 452+ },+ "left_wrist_yaw_link.stl": {+ "sha256": "354af14f646a5a29a41142ed1436e9dbda1903755ebe96030d4b518cde989445",+ "source": "left_wrist_yaw_link.STL",+ "source_sha256": "83f8fb3a726bf9613d65dd14f0f447cb918c3c95b3938042a0c9c09749267d3b",+ "triangles": 404+ },+ "logo_link.stl": {+ "sha256": "555ec8563662a7d9dc8c02d731a9657fa77194858a3a252f444aa946aa5f339e",+ "source": "logo_link.STL",+ "source_sha256": "8571a0a19bc4916fa55f91449f51d5fdefd751000054865a842449429d5f155b",+ "triangles": 306+ },+ "pelvis.stl": {+ "sha256": "a5e7b076649f4899a0fbfcf7e1ee0368cf84fbb2e68bab695398ab6c1ca77d99",+ "source": "pelvis.STL",+ "source_sha256": "5ba6bbc888e630550140d3c26763f10206da8c8bd30ed886b8ede41c61f57a31",+ "triangles": 1349+ },+ "pelvis_contour_link.stl": {+ "sha256": "d016ed38115363429e2740aaa047dbd1d4e49fe796f24232099ade2295adcaa0",+ "source": "pelvis_contour_link.STL",+ "source_sha256": "5cc5c2c7a312329e3feeb2b03d3fc09fc29705bd01864f6767e51be959662420",+ "triangles": 8692+ },+ "right_ankle_pitch_link.stl": {+ "sha256": "0c5c9eca53d7370207426be70e45032afcb9f41be13dce246f259e5252e0c6b7",+ "source": "right_ankle_pitch_link.STL",+ "source_sha256": "15be426539ec1be70246d4d82a168806db64a41301af8b35c197a33348c787a9",+ "triangles": 90+ },+ "right_ankle_roll_link.stl": {+ "sha256": "e3ac204d29d5f91e97e1cef60691d5edb1fdda026b954e2169c914ab541cffd3",+ "source": "right_ankle_roll_link.STL",+ "source_sha256": "4b66222ea56653e627711b56d0a8949b4920da5df091da0ceb343f54e884e3a5",+ "triangles": 830+ },+ "right_elbow_link.stl": {+ "sha256": "233ae8c8f2f55588be7cc6d17cfaa66f9b5c37d0eaf32dbdee3807542478244d",+ "source": "right_elbow_link.STL",+ "source_sha256": "1be925d7aa268bb8fddf5362b9173066890c7d32092c05638608126e59d1e2ab",+ "triangles": 112+ },+ "right_hip_pitch_link.stl": {+ "sha256": "9b744118b6b7ffe69d7982ce4579eb20b35a9496b8a13d6aa6ab3145f1163e34",+ "source": "right_hip_pitch_link.STL",+ "source_sha256": "e4f3c99d7f4a7d34eadbef9461fc66e3486cb5442db1ec50c86317d459f1a9c6",+ "triangles": 230+ },+ "right_hip_roll_link.stl": {+ "sha256": "4c9c886c2977ba0881e87a3ed9712a90a149e5e996cb7a47b7c263926fa99856",+ "source": "right_hip_roll_link.STL",+ "source_sha256": "4c254ef66a356f492947f360dd931965477b631e3fcc841f91ccc46d945d54f6",+ "triangles": 244+ },+ "right_hip_yaw_link.stl": {+ "sha256": "79954979142fddcf9f234c3cf8b946529ac2b87bc18295b762bf305885e80051",+ "source": "right_hip_yaw_link.STL",+ "source_sha256": "e479c2936ca2057e9eb2f7dff6c189b7419d7b8484dea0b298cbb36a2a6aa668",+ "triangles": 376+ },+ "right_knee_link.stl": {+ "sha256": "807714c0d515988cbc17ee929e91e4538e3ce16d867d11fd0b07b2153d5dc210",+ "source": "right_knee_link.STL",+ "source_sha256": "63c4008449c9bbe701a6e2b557b7a252e90cf3a5abcf54cee46862b9a69f8ec8",+ "triangles": 1098+ },+ "right_rubber_hand.stl": {+ "sha256": "6ba8ebbdf198df47a175a0fc8c7c14597ebb7e2b6bfeae81f538baf6452aa03f",+ "source": "right_rubber_hand.STL",+ "source_sha256": "99533b778bca6246144fa511bb9d4e555e075c641f2a0251e04372869cd99d67",+ "triangles": 2786+ },+ "right_shoulder_pitch_link.stl": {+ "sha256": "c0ccf9540f9cbde63165983e7b62d9aa58ef38e8c552d0e3fcff75f7fec5d715",+ "source": "right_shoulder_pitch_link.STL",+ "source_sha256": "24cdb387e0128dfe602770a81c56cdce3a0181d34d039a11d1aaf8819b7b8c02",+ "triangles": 224+ },+ "right_shoulder_roll_link.stl": {+ "sha256": "e5787ae15464c086f4542b29c2dab43f5bd528c5f3ee56f2812545fe5e519bdf",+ "source": "right_shoulder_roll_link.STL",+ "source_sha256": "962b97c48f9ce9e8399f45dd9522e0865d19aa9fd299406b2d475a8fc4a53e81",+ "triangles": 510+ },+ "right_shoulder_yaw_link.stl": {+ "sha256": "f4a044687ef796f79e286a3bad4dc2c80be65b212132f938e3582a3ca268e399",+ "source": "right_shoulder_yaw_link.STL",+ "source_sha256": "a0b76489271da0c72461a344c9ffb0f0c6e64f019ea5014c1624886c442a2fe5",+ "triangles": 318+ },+ "right_wrist_pitch_link.stl": {+ "sha256": "226f48f17024005dccaa4f3d3ad5f7e8e16bc357a1aba87de173b20cc6ce6d82",+ "source": "right_wrist_pitch_link.STL",+ "source_sha256": "d22f8f3b3127f15a63e5be1ee273cd5075786c3142f1c3d9f76cbf43d2a26477",+ "triangles": 100+ },+ "right_wrist_roll_link.stl": {+ "sha256": "fec3af45b3b66aa16bf046cb320f72d0c9933dfed6266e253d78f9223ae925c9",+ "source": "right_wrist_roll_link.STL",+ "source_sha256": "a7ee9212ff5b94d6cb7f52bb1bbf3f352194d5b598acff74f4c77d340c5b344f",+ "triangles": 452+ },+ "right_wrist_yaw_link.stl": {+ "sha256": "b1f689265c15a16c51cd48cbcae54485486a95596de623b8d13b003456295200",+ "source": "right_wrist_yaw_link.STL",+ "source_sha256": "bc9dece2d12509707e0057ba2e48df8f3d56db0c79410212963a25e8a50f61a6",+ "triangles": 434+ },+ "torso_link_rev_1_0.stl": {+ "sha256": "3edf21bb662f94969e70da9a8688851c11cc7a5539ffd7548a2fe0caf16040f7",+ "source": "torso_link_rev_1_0.STL",+ "source_sha256": "11ddb46f2098efbbd8816b1d65893632d8e78be936376c7cdcd6771899ccc723",+ "triangles": 3267+ },+ "waist_roll_link_rev_1_0.stl": {+ "sha256": "8d994abdb0d933c51fa1e70f3f409b68cb505f4b4fe230f9e52267e96102ef51",+ "source": "waist_roll_link_rev_1_0.STL",+ "source_sha256": "b67c347a05abc3e8ddae600d98a082bee273bb39f8e651647708b0a7140a8a97",+ "triangles": 108+ },+ "waist_yaw_link_rev_1_0.stl": {+ "sha256": "8cc0d812b24b8ce39eb563e74e90570415c4016242a290a557276a5afe2c3284",+ "source": "waist_yaw_link_rev_1_0.STL",+ "source_sha256": "ec6db442b11f25eed898b5add07940c85d804f300de24dcbd264ccd8be7d554c",+ "triangles": 786+ }+ },+ "level": "25k",+ "note": "Levels of detail of the library's robots (the players' images, renderer rule 6; user decision D1, 2026-10-08): a robot's fine meshes (meshes_fine/, the unchanged upstream meshes, not in git) decimated to a triangle budget and committed as meshes_<level>/ (e.g. meshes_25k/), so that a sport draws its players' images of the robot with the appearance of the real robot at a small cost (a body's mount(..., lod=\"25k\")).",+ "robot": "unitree_g1",+ "source_triangles": 393270,+ "target_triangles": 25000,+ "tools": {+ "fast-simplification": "0.2.0",+ "trimesh": "5.1.1"+ },+ "triangles": 31522+}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/logo_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/logo_link.stlnew file mode 100644index 0000000000..26947d877cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/logo_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis.stlnew file mode 100644index 0000000000..4d4e3d8296Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis_contour_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis_contour_link.stlnew file mode 100644index 0000000000..b9747ed8c7Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/pelvis_contour_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_pitch_link.stlnew file mode 100644index 0000000000..b1712477dcBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_roll_link.stlnew file mode 100644index 0000000000..7671142be0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_ankle_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_elbow_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_elbow_link.stlnew file mode 100644index 0000000000..501a46b885Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_elbow_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_pitch_link.stlnew file mode 100644index 0000000000..84be1f9232Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_roll_link.stlnew file mode 100644index 0000000000..eeaac37289Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_yaw_link.stlnew file mode 100644index 0000000000..d91378c241Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_hip_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_knee_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_knee_link.stlnew file mode 100644index 0000000000..94b2f41031Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_knee_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_rubber_hand.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_rubber_hand.stlnew file mode 100644index 0000000000..2e40f4a68aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_rubber_hand.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_pitch_link.stlnew file mode 100644index 0000000000..633ab8a7daBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_roll_link.stlnew file mode 100644index 0000000000..97cc10dd87Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_yaw_link.stlnew file mode 100644index 0000000000..bbef2ead35Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_shoulder_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_pitch_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_pitch_link.stlnew file mode 100644index 0000000000..0dee469ca5Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_pitch_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_roll_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_roll_link.stlnew file mode 100644index 0000000000..8069b6ae41Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_roll_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_yaw_link.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_yaw_link.stlnew file mode 100644index 0000000000..db62034ff0Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/right_wrist_yaw_link.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/torso_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/torso_link_rev_1_0.stlnew file mode 100644index 0000000000..25f5e97ab9Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/torso_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stlnew file mode 100644index 0000000000..a7d09b7bfdBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_roll_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stl b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stlnew file mode 100644index 0000000000..5f750aad7aBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/meshes_25k/waist_yaw_link_rev_1_0.stl differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/model.xml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/model.xmlnew file mode 100644index 0000000000..e089140a20--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/model.xml@@ -0,0 +1,265 @@+<mujoco model="unitree_g1">+ <!-- Generated by bodies/unitree_g1/tools/make_model.py from MuJoCo Menagerie unitree_g1/g1.xml (commit f054586a8e90465d49ee5be15335c4a0c7f57caf, BSD-3-Clause, LICENSE; derived from Unitree's g1_description g1_29dof_rev_1_0). Template of the RoboOlympics Unitree G1 body: read by body.py, which prefixes every name, picks the mesh level and mounts the hand and the motors. Do not edit. -->+ <compiler angle="radian" meshdir="meshes" autolimits="true" />+ <default>+ <default class="g1_g1">+ <site rgba="1 0 0 1" size="0.01" group="5" />+ <joint armature="0.01" frictionloss="0.3" />+ <position kp="500" dampratio="1" inheritrange="1" />+ <default class="g1_visual">+ <geom group="2" type="mesh" contype="0" conaffinity="0" density="0" material="g1_m_metal" />+ </default>+ <default class="g1_collision">+ <geom group="3" type="mesh" contype="4" conaffinity="0" />+ <default class="g1_foot">+ <geom type="sphere" size="0.005" priority="1" friction="0.6" condim="3" contype="1" conaffinity="1" />+ </default>+ </default>+ </default>+ </default>+ <asset>+ <material name="g1_m_black" rgba="0.2 0.2 0.2 1" />+ <material name="g1_m_metal" rgba="0.7 0.7 0.7 1" />+ <mesh file="pelvis.stl" name="g1_pelvis" />+ <mesh file="pelvis_contour_link.stl" name="g1_pelvis_contour_link" />+ <mesh file="left_hip_pitch_link.stl" name="g1_left_hip_pitch_link" />+ <mesh file="left_hip_roll_link.stl" name="g1_left_hip_roll_link" />+ <mesh file="left_hip_yaw_link.stl" name="g1_left_hip_yaw_link" />+ <mesh file="left_knee_link.stl" name="g1_left_knee_link" />+ <mesh file="left_ankle_pitch_link.stl" name="g1_left_ankle_pitch_link" />+ <mesh file="left_ankle_roll_link.stl" name="g1_left_ankle_roll_link" />+ <mesh file="right_hip_pitch_link.stl" name="g1_right_hip_pitch_link" />+ <mesh file="right_hip_roll_link.stl" name="g1_right_hip_roll_link" />+ <mesh file="right_hip_yaw_link.stl" name="g1_right_hip_yaw_link" />+ <mesh file="right_knee_link.stl" name="g1_right_knee_link" />+ <mesh file="right_ankle_pitch_link.stl" name="g1_right_ankle_pitch_link" />+ <mesh file="right_ankle_roll_link.stl" name="g1_right_ankle_roll_link" />+ <mesh name="g1_waist_yaw_link" file="waist_yaw_link_rev_1_0.stl" />+ <mesh name="g1_waist_roll_link" file="waist_roll_link_rev_1_0.stl" />+ <mesh name="g1_torso_link" file="torso_link_rev_1_0.stl" />+ <mesh file="logo_link.stl" name="g1_logo_link" />+ <mesh file="head_link.stl" name="g1_head_link" />+ <mesh file="left_shoulder_pitch_link.stl" name="g1_left_shoulder_pitch_link" />+ <mesh file="left_shoulder_roll_link.stl" name="g1_left_shoulder_roll_link" />+ <mesh file="left_shoulder_yaw_link.stl" name="g1_left_shoulder_yaw_link" />+ <mesh file="left_elbow_link.stl" name="g1_left_elbow_link" />+ <mesh file="left_wrist_roll_link.stl" name="g1_left_wrist_roll_link" />+ <mesh file="left_wrist_pitch_link.stl" name="g1_left_wrist_pitch_link" />+ <mesh file="left_wrist_yaw_link.stl" name="g1_left_wrist_yaw_link" />+ <mesh file="left_rubber_hand.stl" name="g1_left_rubber_hand" />+ <mesh file="right_shoulder_pitch_link.stl" name="g1_right_shoulder_pitch_link" />+ <mesh file="right_shoulder_roll_link.stl" name="g1_right_shoulder_roll_link" />+ <mesh file="right_shoulder_yaw_link.stl" name="g1_right_shoulder_yaw_link" />+ <mesh file="right_elbow_link.stl" name="g1_right_elbow_link" />+ <mesh file="right_wrist_roll_link.stl" name="g1_right_wrist_roll_link" />+ <mesh file="right_wrist_pitch_link.stl" name="g1_right_wrist_pitch_link" />+ <mesh file="right_wrist_yaw_link.stl" name="g1_right_wrist_yaw_link" />+ <mesh file="right_rubber_hand.stl" name="g1_right_rubber_hand" />+ </asset>+ <worldbody>+ <body name="pelvis" pos="0 0 0.793" childclass="g1_g1">+ <inertial pos="0 0 -0.07605" quat="1 0 -0.000399148 0" mass="3.813" diaginertia="0.010549 0.0093089 0.0079184" />+ <freejoint name="floating_base_joint" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_pelvis" />+ <geom class="g1_visual" mesh="g1_pelvis_contour_link" />+ <geom class="g1_collision" mesh="g1_pelvis_contour_link" />+ <site name="imu_in_pelvis" pos="0.04525 0 -0.08339" size="0.01" />+ <body name="left_hip_pitch_link" pos="0 0.064452 -0.1027">+ <inertial pos="0.002741 0.047791 -0.02606" quat="0.954862 0.293964 0.0302556 0.030122" mass="1.35" diaginertia="0.00181517 0.00153422 0.00116212" />+ <joint name="left_hip_pitch_joint" axis="0 1 0" range="-2.5307 2.8798" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_left_hip_pitch_link" />+ <geom class="g1_collision" material="g1_m_black" mesh="g1_left_hip_pitch_link" />+ <body name="left_hip_roll_link" pos="0 0.052 -0.030465" quat="0.996179 0 -0.0873386 0">+ <inertial pos="0.029812 -0.001045 -0.087934" quat="0.977808 -1.97119e-05 0.205576 -0.0403793" mass="1.52" diaginertia="0.00254986 0.00241169 0.00148755" />+ <joint name="left_hip_roll_joint" axis="1 0 0" range="-0.5236 2.9671" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_left_hip_roll_link" />+ <geom class="g1_collision" mesh="g1_left_hip_roll_link" />+ <body name="left_hip_yaw_link" pos="0.025001 0 -0.12412">+ <inertial pos="-0.057709 -0.010981 -0.15078" quat="0.600598 0.15832 0.223482 0.751181" mass="1.702" diaginertia="0.00776166 0.00717575 0.00160139" />+ <joint name="left_hip_yaw_joint" axis="0 0 1" range="-2.7576 2.7576" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" mesh="g1_left_hip_yaw_link" />+ <geom class="g1_collision" mesh="g1_left_hip_yaw_link" />+ <body name="left_knee_link" pos="-0.078273 0.0021489 -0.17734" quat="0.996179 0 0.0873386 0">+ <inertial pos="0.005457 0.003964 -0.12074" quat="0.923418 -0.0327699 0.0158246 0.382067" mass="1.932" diaginertia="0.0113804 0.0112778 0.00146458" />+ <joint name="left_knee_joint" axis="0 1 0" range="-0.087267 2.8798" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_left_knee_link" />+ <geom class="g1_collision" mesh="g1_left_knee_link" />+ <body name="left_ankle_pitch_link" pos="0 -9.4445e-05 -0.30001">+ <inertial pos="-0.007269 0 0.011137" quat="0.603053 0.369225 0.369225 0.603053" mass="0.074" diaginertia="1.89e-05 1.40805e-05 6.9195e-06" />+ <joint name="left_ankle_pitch_joint" axis="0 1 0" range="-0.87267 0.5236" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_left_ankle_pitch_link" />+ <geom class="g1_collision" mesh="g1_left_ankle_pitch_link" />+ <body name="left_ankle_roll_link" pos="0 0 -0.017558">+ <inertial pos="0.026505 0 -0.016425" quat="-0.000481092 0.728482 -0.000618967 0.685065" mass="0.608" diaginertia="0.00167218 0.0016161 0.000217621" />+ <joint name="left_ankle_roll_joint" axis="1 0 0" range="-0.2618 0.2618" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_left_ankle_roll_link" />+ <geom class="g1_foot" pos="-0.05 0.025 -0.03" />+ <geom class="g1_foot" pos="-0.05 -0.025 -0.03" />+ <geom class="g1_foot" pos="0.12 0.03 -0.03" />+ <geom class="g1_foot" pos="0.12 -0.03 -0.03" />+ <site name="left_foot" />+ <geom name="left_foot_strike" type="box" pos="0.035 0 -0.02" size="0.105 0.04 0.022" contype="8" conaffinity="0" group="3" mass="0" density="0" rgba="0.2 0.6 0.9 0.3" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="right_hip_pitch_link" pos="0 -0.064452 -0.1027">+ <inertial pos="0.002741 -0.047791 -0.02606" quat="0.954862 -0.293964 0.0302556 -0.030122" mass="1.35" diaginertia="0.00181517 0.00153422 0.00116212" />+ <joint name="right_hip_pitch_joint" axis="0 1 0" range="-2.5307 2.8798" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_right_hip_pitch_link" />+ <geom class="g1_collision" material="g1_m_black" mesh="g1_right_hip_pitch_link" />+ <body name="right_hip_roll_link" pos="0 -0.052 -0.030465" quat="0.996179 0 -0.0873386 0">+ <inertial pos="0.029812 0.001045 -0.087934" quat="0.977808 1.97119e-05 0.205576 0.0403793" mass="1.52" diaginertia="0.00254986 0.00241169 0.00148755" />+ <joint name="right_hip_roll_joint" axis="1 0 0" range="-2.9671 0.5236" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_right_hip_roll_link" />+ <geom class="g1_collision" mesh="g1_right_hip_roll_link" />+ <body name="right_hip_yaw_link" pos="0.025001 0 -0.12412">+ <inertial pos="-0.057709 0.010981 -0.15078" quat="0.751181 0.223482 0.15832 0.600598" mass="1.702" diaginertia="0.00776166 0.00717575 0.00160139" />+ <joint name="right_hip_yaw_joint" axis="0 0 1" range="-2.7576 2.7576" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" mesh="g1_right_hip_yaw_link" />+ <geom class="g1_collision" mesh="g1_right_hip_yaw_link" />+ <body name="right_knee_link" pos="-0.078273 -0.0021489 -0.17734" quat="0.996179 0 0.0873386 0">+ <inertial pos="0.005457 -0.003964 -0.12074" quat="0.923439 0.0345276 0.0116333 -0.382012" mass="1.932" diaginertia="0.011374 0.0112843 0.00146452" />+ <joint name="right_knee_joint" axis="0 1 0" range="-0.087267 2.8798" actuatorfrcrange="-139 139" />+ <geom class="g1_visual" mesh="g1_right_knee_link" />+ <geom class="g1_collision" mesh="g1_right_knee_link" />+ <body name="right_ankle_pitch_link" pos="0 9.4445e-05 -0.30001">+ <inertial pos="-0.007269 0 0.011137" quat="0.603053 0.369225 0.369225 0.603053" mass="0.074" diaginertia="1.89e-05 1.40805e-05 6.9195e-06" />+ <joint name="right_ankle_pitch_joint" axis="0 1 0" range="-0.87267 0.5236" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_right_ankle_pitch_link" />+ <geom class="g1_collision" mesh="g1_right_ankle_pitch_link" />+ <body name="right_ankle_roll_link" pos="0 0 -0.017558">+ <inertial pos="0.026505 0 -0.016425" quat="0.000481092 0.728482 0.000618967 0.685065" mass="0.608" diaginertia="0.00167218 0.0016161 0.000217621" />+ <joint name="right_ankle_roll_joint" axis="1 0 0" range="-0.2618 0.2618" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" material="g1_m_black" mesh="g1_right_ankle_roll_link" />+ <geom class="g1_foot" pos="-0.05 0.025 -0.03" />+ <geom class="g1_foot" pos="-0.05 -0.025 -0.03" />+ <geom class="g1_foot" pos="0.12 0.03 -0.03" />+ <geom class="g1_foot" pos="0.12 -0.03 -0.03" />+ <site name="right_foot" />+ <geom name="right_foot_strike" type="box" pos="0.035 0 -0.02" size="0.105 0.04 0.022" contype="8" conaffinity="0" group="3" mass="0" density="0" rgba="0.2 0.6 0.9 0.3" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="waist_yaw_link">+ <inertial pos="0.003494 0.000233 0.018034" quat="0.289697 0.591001 -0.337795 0.672821" mass="0.214" diaginertia="0.000163531 0.000107714 0.000102205" />+ <joint name="waist_yaw_joint" axis="0 0 1" range="-2.618 2.618" actuatorfrcrange="-88 88" />+ <geom class="g1_visual" mesh="g1_waist_yaw_link" />+ <body name="waist_roll_link" pos="-0.0039635 0 0.044">+ <inertial pos="0 2.3e-05 0" quat="0.5 0.5 -0.5 0.5" mass="0.086" diaginertia="8.245e-06 7.079e-06 6.339e-06" />+ <joint name="waist_roll_joint" axis="1 0 0" range="-0.52 0.52" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_waist_roll_link" />+ <body name="torso_link">+ <inertial pos="0.00203158 0.000339683 0.184568" quat="0.999803 -6.03319e-05 0.0198256 0.00131986" mass="7.818" diaginertia="0.121847 0.109825 0.0273735" />+ <joint name="waist_pitch_joint" axis="0 1 0" range="-0.52 0.52" actuatorfrcrange="-50 50" />+ <geom class="g1_visual" mesh="g1_torso_link" />+ <geom class="g1_collision" mesh="g1_torso_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_visual" material="g1_m_black" mesh="g1_logo_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_collision" material="g1_m_black" mesh="g1_logo_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_visual" material="g1_m_black" mesh="g1_head_link" />+ <geom pos="0.0039635 0 -0.044" quat="1 0 0 0" class="g1_collision" material="g1_m_black" mesh="g1_head_link" />+ <site name="imu_in_torso" pos="-0.03959 -0.00224 0.14792" size="0.01" />+ <body name="left_shoulder_pitch_link" pos="0.0039563 0.10022 0.24778" quat="0.990264 0.139201 1.38722e-05 -9.86868e-05">+ <inertial pos="0 0.035892 -0.011628" quat="0.654152 0.0130458 -0.326267 0.68225" mass="0.718" diaginertia="0.000465864 0.000432842 0.000406394" />+ <joint name="left_shoulder_pitch_joint" axis="0 1 0" range="-3.0892 2.6704" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_shoulder_pitch_link" />+ <geom size="0.03 0.025" pos="0 0.04 -0.01" quat="0.707107 0 0.707107 0" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="left_shoulder_roll_link" pos="0 0.038 -0.013831" quat="0.990268 -0.139172 0 0">+ <inertial pos="-0.000227 0.00727 -0.063243" quat="0.701256 -0.0196223 -0.00710317 0.712604" mass="0.643" diaginertia="0.000691311 0.000618011 0.000388977" />+ <joint name="left_shoulder_roll_joint" axis="1 0 0" range="-1.5882 2.2515" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_shoulder_roll_link" />+ <geom size="0.03 0.015" pos="-0.004 0.006 -0.053" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="left_shoulder_yaw_link" pos="0 0.00624 -0.1032">+ <inertial pos="0.010773 -0.002949 -0.072009" quat="0.716879 -0.0964829 -0.0679942 0.687134" mass="0.734" diaginertia="0.00106187 0.00103217 0.000400661" />+ <joint name="left_shoulder_yaw_joint" axis="0 0 1" range="-2.618 2.618" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_shoulder_yaw_link" />+ <geom class="g1_collision" mesh="g1_left_shoulder_yaw_link" />+ <body name="left_elbow_link" pos="0.015783 0 -0.080518">+ <inertial pos="0.064956 0.004454 -0.010062" quat="0.541765 0.636132 0.388821 0.388129" mass="0.6" diaginertia="0.000443035 0.000421612 0.000259353" />+ <joint name="left_elbow_joint" axis="0 1 0" range="-1.0472 2.0944" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_elbow_link" />+ <geom class="g1_collision" mesh="g1_left_elbow_link" />+ <body name="left_wrist_roll_link" pos="0.1 0.00188791 -0.01">+ <inertial pos="0.0171394 0.000537591 4.8864e-07" quat="0.575338 0.411667 -0.574906 0.411094" mass="0.085445" diaginertia="5.48211e-05 4.96646e-05 3.57798e-05" />+ <joint name="left_wrist_roll_joint" axis="1 0 0" range="-1.97222 1.97222" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_left_wrist_roll_link" />+ <geom class="g1_collision" mesh="g1_left_wrist_roll_link" />+ <body name="left_wrist_pitch_link" pos="0.038 0 0">+ <inertial pos="0.0229999 -0.00111685 -0.00111658" quat="0.249998 0.661363 0.293036 0.643608" mass="0.48405" diaginertia="0.000430353 0.000429873 0.000164648" />+ <joint name="left_wrist_pitch_joint" axis="0 1 0" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_left_wrist_pitch_link" />+ <geom class="g1_collision" mesh="g1_left_wrist_pitch_link" />+ <body name="left_wrist_yaw_link" pos="0.046 0 0">+ <inertial pos="0.0708244 0.000191745 0.00161742" quat="0.510571 0.526295 0.468078 0.493188" mass="0.254576" diaginertia="0.000646113 0.000559993 0.000147566" />+ <joint name="left_wrist_yaw_joint" axis="0 0 1" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_left_wrist_yaw_link" />+ <geom class="g1_collision" mesh="g1_left_wrist_yaw_link" />+ <geom pos="0.0415 0.003 0" quat="1 0 0 0" class="g1_visual" mesh="g1_left_rubber_hand" />+ <body name="left_mount" pos="0.08 0.0030 0" quat="0.7071068 0 0.7071068 0" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="right_shoulder_pitch_link" pos="0.0039563 -0.10021 0.24778" quat="0.990264 -0.139201 1.38722e-05 9.86868e-05">+ <inertial pos="0 -0.035892 -0.011628" quat="0.68225 -0.326267 0.0130458 0.654152" mass="0.718" diaginertia="0.000465864 0.000432842 0.000406394" />+ <joint name="right_shoulder_pitch_joint" axis="0 1 0" range="-3.0892 2.6704" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_shoulder_pitch_link" />+ <geom size="0.03 0.025" pos="0 -0.04 -0.01" quat="0.707107 0 0.707107 0" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="right_shoulder_roll_link" pos="0 -0.038 -0.013831" quat="0.990268 0.139172 0 0">+ <inertial pos="-0.000227 -0.00727 -0.063243" quat="0.712604 -0.00710317 -0.0196223 0.701256" mass="0.643" diaginertia="0.000691311 0.000618011 0.000388977" />+ <joint name="right_shoulder_roll_joint" axis="1 0 0" range="-2.2515 1.5882" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_shoulder_roll_link" />+ <geom size="0.03 0.015" pos="-0.004 -0.006 -0.053" type="cylinder" rgba="0.7 0.7 0.7 1" class="g1_collision" />+ <body name="right_shoulder_yaw_link" pos="0 -0.00624 -0.1032">+ <inertial pos="0.010773 0.002949 -0.072009" quat="0.687134 -0.0679942 -0.0964829 0.716879" mass="0.734" diaginertia="0.00106187 0.00103217 0.000400661" />+ <joint name="right_shoulder_yaw_joint" axis="0 0 1" range="-2.618 2.618" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_shoulder_yaw_link" />+ <geom class="g1_collision" mesh="g1_right_shoulder_yaw_link" />+ <body name="right_elbow_link" pos="0.015783 0 -0.080518">+ <inertial pos="0.064956 -0.004454 -0.010062" quat="0.388129 0.388821 0.636132 0.541765" mass="0.6" diaginertia="0.000443035 0.000421612 0.000259353" />+ <joint name="right_elbow_joint" axis="0 1 0" range="-1.0472 2.0944" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_elbow_link" />+ <geom class="g1_collision" mesh="g1_right_elbow_link" />+ <body name="right_wrist_roll_link" pos="0.1 -0.00188791 -0.01">+ <inertial pos="0.0171394 -0.000537591 4.8864e-07" quat="0.411667 0.575338 -0.411094 0.574906" mass="0.085445" diaginertia="5.48211e-05 4.96646e-05 3.57798e-05" />+ <joint name="right_wrist_roll_joint" axis="1 0 0" range="-1.97222 1.97222" actuatorfrcrange="-25 25" />+ <geom class="g1_visual" mesh="g1_right_wrist_roll_link" />+ <geom class="g1_collision" mesh="g1_right_wrist_roll_link" />+ <body name="right_wrist_pitch_link" pos="0.038 0 0">+ <inertial pos="0.0229999 0.00111685 -0.00111658" quat="0.643608 0.293036 0.661363 0.249998" mass="0.48405" diaginertia="0.000430353 0.000429873 0.000164648" />+ <joint name="right_wrist_pitch_joint" axis="0 1 0" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_right_wrist_pitch_link" />+ <geom class="g1_collision" mesh="g1_right_wrist_pitch_link" />+ <body name="right_wrist_yaw_link" pos="0.046 0 0">+ <inertial pos="0.0708244 -0.000191745 0.00161742" quat="0.493188 0.468078 0.526295 0.510571" mass="0.254576" diaginertia="0.000646113 0.000559993 0.000147566" />+ <joint name="right_wrist_yaw_joint" axis="0 0 1" range="-1.61443 1.61443" actuatorfrcrange="-5 5" />+ <geom class="g1_visual" mesh="g1_right_wrist_yaw_link" />+ <geom class="g1_collision" mesh="g1_right_wrist_yaw_link" />+ <geom pos="0.0415 -0.003 0" quat="1 0 0 0" class="g1_visual" mesh="g1_right_rubber_hand" />+ <body name="right_mount" pos="0.08 -0.0030 0" quat="0.7071068 0 0.7071068 0" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ </body>+ <body name="head_cam" pos="0.08 0 0.39">+ <camera name="head_left" pos="0 0.025 0" xyaxes="0 -1 0 0 0 1" fovy="58" />+ <camera name="head_right" pos="0 -0.025 0" xyaxes="0 -1 0 0 0 1" fovy="58" />+ <site name="head_center" size="0.01" group="5" />+ </body>+ </body>+ </body>+ </body>+ </body>+ </worldbody>+</mujoco>diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.agile b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.agilenew file mode 100644index 0000000000..096d7552fb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.agile@@ -0,0 +1,260 @@+================================================================================+DUAL LICENSE NOTICE+================================================================================++This repository contains code under two different licenses:++1. BSD 3-Clause License:+ - Applies to: third_party/rsl_rl/patches/ (RSL-RL compatibility patch)+ - Copyright holders: ETH Zurich, NVIDIA CORPORATION & AFFILIATES+ - See Section A below for full license text++2. Apache License 2.0:+ - Applies to: ALL OTHER portions of this repository+ - Copyright holder: NVIDIA CORPORATION & AFFILIATES+ - See Section B below for full license text++When using or distributing this software, you must comply with the license+terms applicable to each portion of the code. If you modify or redistribute+the RSL-RL compatibility patch (third_party/rsl_rl/patches/), you must comply+with the BSD 3-Clause License terms. For all other portions, you must comply with+the Apache 2.0 License terms.++================================================================================+SECTION A: BSD 3-Clause License (for third_party/rsl_rl/patches/)+================================================================================++Copyright (c) 2025, ETH Zurich+Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES+All rights reserved.++Redistribution and use in source and binary forms, with or without modification,+are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its contributors+ may be used to endorse or promote products derived from this software without+ specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++================================================================================+SECTION B: Apache License 2.0 (for all other portions of this repository)+================================================================================++Apache License+Version 2.0, January 2005+http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++"License" shall mean the terms and conditions for use, reproduction,+and distribution as defined by Sections 1 through 9 of this document.++"Licensor" shall mean the copyright owner or entity authorized by+the copyright owner that is granting the License.++"Legal Entity" shall mean the union of the acting entity and all+other entities that control, are controlled by, or are under common+control with that entity. For the purposes of this definition,+"control" means (i) the power, direct or indirect, to cause the+direction or management of such entity, whether by contract or+otherwise, or (ii) ownership of fifty percent (50%) or more of the+outstanding shares, or (iii) beneficial ownership of such entity.++"You" (or "Your") shall mean an individual or Legal Entity+exercising permissions granted by this License.++"Source" form shall mean the preferred form for making modifications,+including but not limited to software source code, documentation+source, and configuration files.++"Object" form shall mean any form resulting from mechanical+transformation or translation of a Source form, including but+not limited to compiled object code, generated documentation,+and conversions to other media types.++"Work" shall mean the work of authorship, whether in Source or+Object form, made available under the License, as indicated by a+copyright notice that is included in or attached to the work+(an example is provided in the Appendix below).++"Derivative Works" shall mean any work, whether in Source or Object+form, that is based on (or derived from) the Work and for which the+editorial revisions, annotations, elaborations, or other modifications+represent, as a whole, an original work of authorship. For the purposes+of this License, Derivative Works shall not include works that remain+separable from, or merely link (or bind by name) to the interfaces of,+the Work and Derivative Works thereof.++"Contribution" shall mean any work of authorship, including+the original version of the Work and any modifications or additions+to that Work or Derivative Works thereof, that is intentionally+submitted to Licensor for inclusion in the Work by the copyright owner+or by an individual or Legal Entity authorized to submit on behalf of+the copyright owner. For the purposes of this definition, "submitted"+means any form of electronic, verbal, or written communication sent+to the Licensor or its representatives, including but not limited to+communication on electronic mailing lists, source code control systems,+and issue tracking systems that are managed by, or on behalf of, the+Licensor for the purpose of discussing and improving the Work, but+excluding communication that is conspicuously marked or otherwise+designated in writing by the copyright owner as "Not a Contribution."++"Contributor" shall mean Licensor and any individual or Legal Entity+on behalf of whom a Contribution has been received by Licensor and+subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of+this License, each Contributor hereby grants to You a perpetual,+worldwide, non-exclusive, no-charge, royalty-free, irrevocable+copyright license to reproduce, prepare Derivative Works of,+publicly display, publicly perform, sublicense, and distribute the+Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of+this License, each Contributor hereby grants to You a perpetual,+worldwide, non-exclusive, no-charge, royalty-free, irrevocable+(except as stated in this section) patent license to make, have made,+use, offer to sell, sell, import, and otherwise transfer the Work,+where such license applies only to those patent claims licensable+by such Contributor that are necessarily infringed by their+Contribution(s) alone or by combination of their Contribution(s)+with the Work to which such Contribution(s) was submitted. If You+institute patent litigation against any entity (including a+cross-claim or counterclaim in a lawsuit) alleging that the Work+or a Contribution incorporated within the Work constitutes direct+or contributory patent infringement, then any patent licenses+granted to You under this License for that Work shall terminate+as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the+Work or Derivative Works thereof in any medium, with or without+modifications, and in Source or Object form, provided that You+meet the following conditions:++(a) You must give any other recipients of the Work or+Derivative Works a copy of this License; and++(b) You must cause any modified files to carry prominent notices+stating that You changed the files; and++(c) You must retain, in the Source form of any Derivative Works+that You distribute, all copyright, patent, trademark, and+attribution notices from the Source form of the Work,+excluding those notices that do not pertain to any part of+the Derivative Works; and++(d) If the Work includes a "NOTICE" text file as part of its+distribution, then any Derivative Works that You distribute must+include a readable copy of the attribution notices contained+within such NOTICE file, excluding those notices that do not+pertain to any part of the Derivative Works, in at least one+of the following places: within a NOTICE text file distributed+as part of the Derivative Works; within the Source form or+documentation, if provided along with the Derivative Works; or,+within a display generated by the Derivative Works, if and+wherever such third-party notices normally appear. The contents+of the NOTICE file are for informational purposes only and+do not modify the License. You may add Your own attribution+notices within Derivative Works that You distribute, alongside+or as an addendum to the NOTICE text from the Work, provided+that such additional attribution notices cannot be construed+as modifying the License.++You may add Your own copyright statement to Your modifications and+may provide additional or different license terms and conditions+for use, reproduction, or distribution of Your modifications, or+for any such Derivative Works as a whole, provided Your use,+reproduction, and distribution of the Work otherwise complies with+the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise,+any Contribution intentionally submitted for inclusion in the Work+by You to the Licensor shall be under the terms and conditions of+this License, without any additional terms or conditions.+Notwithstanding the above, nothing herein shall supersede or modify+the terms of any separate license agreement you may have executed+with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade+names, trademarks, service marks, or product names of the Licensor,+except as required for reasonable and customary use in describing the+origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or+agreed to in writing, Licensor provides the Work (and each+Contributor provides its Contributions) on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+implied, including, without limitation, any warranties or conditions+of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+PARTICULAR PURPOSE. You are solely responsible for determining the+appropriateness of using or redistributing the Work and assume any+risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory,+whether in tort (including negligence), contract, or otherwise,+unless required by applicable law (such as deliberate and grossly+negligent acts) or agreed to in writing, shall any Contributor be+liable to You for damages, including any direct, indirect, special,+incidental, or consequential damages of any character arising as a+result of this License or out of the use or inability to use the+Work (including but not limited to damages for loss of goodwill,+work stoppage, computer failure or malfunction, or any and all+other commercial damages or losses), even if such Contributor+has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing+the Work or Derivative Works thereof, You may choose to offer,+and charge a fee for, acceptance of support, warranty, indemnity,+or other liability obligations and/or rights consistent with this+License. However, in accepting such obligations, You may act only+on Your own behalf and on Your sole responsibility, not on behalf+of any other Contributor, and only if You agree to indemnify,+defend, and hold each Contributor harmless for any liability+incurred by, or claims asserted against, such Contributor by reason+of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++To apply the Apache License to your work, attach the following+boilerplate notice, with the fields enclosed by brackets "[]"+replaced with your own identifying information. (Don't include+the brackets!) The text should be enclosed in the appropriate+comment syntax for the file format. We also recommend that a+file or class name and description of purpose be included on the+same "printed page" as the copyright notice for easier+identification within third-party archives.++Copyright [yyyy] [name of copyright owner]++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.falcon b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.falconnew file mode 100644index 0000000000..69ceb6b302--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.falcon@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 Yuanhang Zhang+s+Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.unitree_rl_gym b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.unitree_rl_gymnew file mode 100644index 0000000000..9ad8f6dbb0--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/LICENSE.unitree_rl_gym@@ -0,0 +1,23 @@+BSD 3-Clause License+Copyright (c) 2016-2023 HangZhou YuShu TECHNOLOGY CO.,LTD. ("Unitree Robotics")+All rights reserved.+Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:+1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.+3. Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/agile_g1_velocity_height.npz b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/agile_g1_velocity_height.npznew file mode 100644index 0000000000..fe7e262950Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/agile_g1_velocity_height.npz differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/falcon_g1_29dof.npz b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/falcon_g1_29dof.npznew file mode 100644index 0000000000..d220b17c01Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/falcon_g1_29dof.npz differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/g1_deploy_mujoco.yaml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/g1_deploy_mujoco.yamlnew file mode 100644index 0000000000..db18fdfa78--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/g1_deploy_mujoco.yaml@@ -0,0 +1,26 @@+#+policy_path: "{LEGGED_GYM_ROOT_DIR}/deploy/pre_train/g1/motion.pt"+xml_path: "{LEGGED_GYM_ROOT_DIR}/resources/robots/g1_description/scene.xml"++# Total simulation time+simulation_duration: 60.0+# Simulation time step+simulation_dt: 0.002+# Controller update frequency (meets the requirement of simulation_dt * controll_decimation=0.02; 50Hz)+control_decimation: 10++kps: [100, 100, 100, 150, 40, 40, 100, 100, 100, 150, 40, 40]+kds: [2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2]++default_angles: [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0,+ -0.1, 0.0, 0.0, 0.3, -0.2, 0.0]++ang_vel_scale: 0.25+dof_pos_scale: 1.0+dof_vel_scale: 0.05+action_scale: 0.25+cmd_scale: [2.0, 2.0, 0.25]+num_actions: 12+num_obs: 47++cmd_init: [0.5, 0, 0]\ No newline at end of filediff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/motion.npz b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/motion.npznew file mode 100644index 0000000000..40ea903b13Binary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/bodies/unitree_g1/policy/motion.npz differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/README.md b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/README.mdnew file mode 100644index 0000000000..1bd69c7076--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/README.md@@ -0,0 +1,21 @@+# core/++The match core (docs/framework_zh.md §5): it hosts every match under one set of rules and never names a sport or a+harness. Version: `VERSION` in `__init__.py` (bump on every change; every sport's golden replay must still pass).++| File | Contract / job |+|---|---|+| `sport.py` | ② the sport interface: `MatchConfig` (seats, sides, format, modes, renderer), `Phase`, `Refused`, `MatchBase` (the optional hooks and their defaults), `ActionLayer` / `LowLayer` / `SchemaLayer`, `check_command`; request validation (core 0.2.11): `check_body` (every request), `check_action` + `parse_action` (every act: any exception while reading an action is the player's 400, never a technical failure; core 0.2.13: an `entity` from a seat without entities is refused) |+| `http.py`, `client.py`, `game.py` | ① the player protocol: the HTTP envelope (`/<seat>/<endpoint>`, limits; core 0.2.16: each authenticated seat its own budget), the client loop of built-in players, the generic `game` CLI (core 0.2.13: a shortcut sends `entity` as written, true / false as booleans and an enum value as text) |+| `realtime.py`, `turn.py`, `service.py` | flow: `eai-standard-realtime/1.0` (slowdown, freeze and review, act pipeline, delayed effects, entities) and `eai-standard-turn/1.0` (turns, chess clocks, reviews); what both share (seats and sides, observations, team channel, retirement, final.json); core 0.2.13: the realtime clock and the act segment restart when `Match.resume()` has returned; core 0.2.18: a declared reaction delay D (`sport.toml [timing] reaction_delay_steps`, `spec.reaction_delay`): an act takes effect at max(the next boundary, the step of the seat's latest world state + D), `local.py` alike; core 0.2.20: the team channel (`channel.py`) is read with a read mark and never consumed: every message has a per-side `seq`, `observe` / `status` / `wait` show the teammates' messages after `team_since` (else the recent ones) and `team_seq`, `POST /<seat>/team {"since": n}` pages through the log (before 0.2.20 each message went to whichever client of the seat read first); core 0.2.23: the reaction report (report only, no effect on validity or grading): every realtime act's `cmd` row logs `seen` (the step of the seat's latest world state), the header logs the timing, and final.json `reaction` gives per seat the acts that took effect within D (effect step - seen step <= D; D = 0: the next boundary) as a count and a share and the actual delay in steps (median, p90, max); the fresh-process replay recomputes it (`episode.reaction_report`, replay_check.json `reaction`; final.json `reaction.replayed`); core 0.2.26: after the end `observe` / `act` answer 409 with the final state and draw nothing, and once the match is finalized a late request's failure is only logged (it never voids a finished match) |+| `episode.py` | ③ the match record: `episode.jsonl` and the fresh-process replay (`python -m core.episode PLUGIN DIR`) |+| `diaglog.py`, `diagnose.py` | diagnostics (core 0.2.25; information only, never replayed, in no hash): the rows `observe` (k, view_steps), `act_received` (k, act_id, obs_id_last, seen), `effect`, `act_dropped`, `event` (what `Match.step()` returns), `team_delivered`, written by the service and by `local.py`; the post-match diagnosis `python -m core.diagnose PLUGIN RUN_DIR` (`load()` -> the `rep` dict with a deterministic `world()` replay; the sport's analysis `sports/<sport>/diagnose.py`: `units`, `implied`, `metrics`; writes `diag/units.jsonl`, `claims.jsonl`, `summary.json`); a sport's `diagnose.py` is never copied into a task |+| `outcome.py`, `grading.py` | judgement: the no-draw chain, N-side ranking, solo scoring; the verifier (validity, reward fields, no-code audit hookup; core 0.2.14: hidden official seeds and the continuous score; core 0.2.19: once a hidden seed set is registered only its seeds are official, over the sport's own `official_config`, which can only lower it) |+| `seeds.py` | hidden official seeds (core 0.2.14): the private set's format, the salted commitments, the registered sha256 and the membership test the verifier runs (copied into every task as `tests/seeds.py`) |+| `score.py` | the continuous score (core 0.2.14): sport.toml `[score]` (`share`, `margin`, `own` from `scores()`, or the `Match.continuous_score()` hook), one number per side, larger is better; a forfeiting side gets the declared `forfeit` value; final.json `continuous`, replayed and checked by the verifier |+| `observe.py`, `channel.py`, `rng.py`, `spec.py` | the observation whitelist and camera tiles (through `renderers/`), the reply images of an action (`Match.reply_views`, core 0.2.8: snapshotted under the lock, drawn off it by the same camera worker, attached to the reply as `observation`), the team channel, random streams by name, sport.toml |+| `seats.py`, `metering/` | per-seat counters, locks and chess clocks; the metering hookup (`think_clock.py`, `api_errors.py`: byte-identical copies); player modes (`PLAYER_MODE_<seat>`): `model` (metered by the seat's proxy, required for validity), `oracle` (exempt), `unmetered` (core 0.2.29: the runner meters the model itself, e.g. a plain Harbor with native agents; no proxy, no meter required) |+| `spectator.py` | the broadcast log (`broadcast.jsonl`, the legacy writer copied as `spectator/broadcast_log.py`) and the replay video (`replay.mp4`, a fresh-process replay drawn by the spectator renderer; core 0.2.13: written as `replay.part.mp4` and renamed when complete, so a killed render leaves no `replay.mp4`; core 0.2.28: a sport's own `Sport.spectator_scene(cfg)` + `Match.spectator_state()` when defined); never read back |+| final.json compatibility | `service.py` `COMPAT`: the sport's fields are lifted to the top level (unless a core field has the name) and `score` is set, so the Season-1 readers work; the sport fields also stay under `sport_fields` |+| `workers.py`, `serve.py`, `launch.py` | worker processes (plan, render, camera), the service entry point, the launcher (one metering proxy per seat; core 0.2.22: a seat's proxy keeps no RO_SEAT_* and no other seat's per-seat variable, and a seat on route `chatgpt` no task-wide credential; none for an unmetered seat, core 0.2.29) |+| `local.py`, `testkit.py`, `tests/` | in-process matches of built-in players, the generic test suite of every sport (core 0.2.12: `prestart_no_show` asks for the no-show decision at step 0, not for an unfinished world: a sport's forfeit hook may end its world; core 0.2.13: `fairness` plays a format with its declared sides and counts sides, not seats; core 0.2.17: the fresh-process replays of `determinism` and `solo_quit` may take the sport's `[timing] replay_timeout_s` when it is above 1800 s), the core's own tests |diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/__init__.pynew file mode 100644index 0000000000..1dff7faa1f--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/__init__.py@@ -0,0 +1,26 @@+"""RoboOlympics match core (docs/framework_zh.md §5): hosts every match under one set of rules.++Flow (clock, slowdown, freeze and review, seats and turns), rules (formats, modes), records (episode log, replay,+metering) and judgement (outcome, validity). It names no sport and no harness (ci_checks/check-core-purity.sh), computes+no physics, and changes only in its own commits with a version bump (VERSION) and every sport's golden replay passing.+"""+VERSION = "0.2.29" # 0.2.29: player mode "unmetered" (PLAYER_MODE_<seat>: the runner meters the model; no proxy, no meter)+# (fexam-export, renumbered above main again; it was 0.2.27 there)+# 0.2.28: a sport's own spectator scene for the replay video (Sport.spectator_scene(cfg) with+# Match.spectator_state(); core/spectator.py), never the players' images (0.2.27 is skipped: an unmerged branch uses it)+# 0.2.26: after the end, observe / act answer 409 with the final state and draw nothing (realtime and+# turn); after finalization a late draw returns no images and a late failure is only logged, never an error+# 0.2.25: diagnostic records (information only, never replayed, in no hash; core/diaglog.py):+# observe rows carry k and view_steps (both protocols), act_received k / act_id / obs_id_last / seen, new rows effect,+# act_dropped, event (what Match.step() returns) and team_delivered; core/local.py writes the same; the post-match+# diagnosis python -m core.diagnose PLUGIN RUN_DIR (core/diagnose.py: load() -> rep with a replayed world(), the+# sport's diagnose.py). 0.2.24 is skipped+# 0.2.23: the reaction report (report only): final.json `reaction` per seat, acts within the+# declared reaction delay D (count, share) and the actual delay (median, p90, max); act rows log `seen`, the replay+# recomputes it (core/episode.reaction_report)+# 0.2.22: a seat's metering proxy holds no other seat's credentials (launch.seat_env), a ChatGPT-subscription seat no task-wide key+# 0.2.21: built-in players may talk on the team channel (message(view); core/client.py, core/local.py);+# a preview format ([formats.<f>] preview = true) is never an official configuration+# 0.2.20: the team channel is read with a read mark (seq, team_since, POST /team), never consumed+# 0.2.19: once frozen (hidden seeds registered) only a registered hidden seed is official, over the sport's own rule; 0.2.18: a declared reaction delay+PROTOCOLS = {"realtime": "eai-standard-realtime/1.0", "turn": "eai-standard-turn/1.0"}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/channel.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/channel.pynew file mode 100644index 0000000000..d0bf924897--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/channel.py@@ -0,0 +1,132 @@+"""The team channel (docs/framework_zh.md §6.1, one player per robot): short text messages between the seats of one+side, a core service so that no sport writes it. Declared in sport.toml:++ [team_channel]+ max_bytes = 120 # per message (UTF-8)+ min_interval_s = 1.0 # game time between two messages of one seat+ max_messages = 200 # per seat and match+ recent_s = 2.0 # optional: the default window of observe / status without a read mark (game seconds)+ recent_max = 20 # optional: at most this many messages in that window++A message is stamped with the sender's game time (step k) and a sequence number `seq` (1, 2, ... per side, core+0.2.20) and shown to the other seats of the SAME side only, from that step on; the other side never sees it. Every+message is a row of the episode (`team`, information only: it does not change the world, so the replay does not need+it).++Reading never consumes (core 0.2.20; before 0.2.20 every message was handed out once per seat, so an agent's own+`status` call or monitor script took messages away from its program): `observe` and `status` show the teammates'+messages with seq > `team_since` when the request gives that read mark, else the RECENT ones (the last `recent_s` game+seconds, at most `recent_max` messages: a bounded default that repeats across calls), always with `team_seq`, the+newest seq of the side. `POST /<seat>/team {"since": n}` reads the log after n (at most `page_max` per reply, `more`+when there are more). Every client of a seat (the agent, its program, a monitor) reads the same log with its own+read mark.++The task parameter RO_TEAM_CHANNEL=off switches a declared channel off (the no-communication setting of the+multi-agent taxonomy: same teams, same rules, the teammates cannot talk); the default is on."""+from __future__ import annotations++import os++from .sport import Refused+++class TeamChannel:+ def __init__(self, cfg, conf: dict | None):+ self.cfg, self.conf = cfg, dict(conf or {})+ self.declared = bool(conf) and any(len(cfg.seats_of(s)) > 1 for s in cfg.side_list())+ self.switched_off = os.environ.get("RO_TEAM_CHANNEL", "on").strip().lower() == "off"+ self.enabled = self.declared and not self.switched_off+ self.max_bytes = int(self.conf.get("max_bytes", 120))+ self.min_interval_s = float(self.conf.get("min_interval_s", 1.0))+ self.max_messages = int(self.conf.get("max_messages", 200))+ self.recent_s = float(self.conf.get("recent_s", 2.0))+ self.recent_max = int(self.conf.get("recent_max", 20))+ self.page_max = 500+ self.log: list[dict] = []+ self.last_k: dict[str, int] = {}+ self.seq: dict[str, int] = {} # side -> the newest seq+ self.delivered: dict[str, set] = {} # seat -> seqs already returned to it (core 0.2.25, diagnostics)++ def deliver(self, seat: str, rows: list[dict], k: int) -> list[dict]:+ """The messages of `rows` (as messages() / page() return them) returned to `seat` for the first time, as+ team_delivered rows (core 0.2.25, diagnostics only: when each recipient first got each message)."""+ got = self.delivered.setdefault(seat, set())+ out = []+ for r in rows:+ if r["seq"] not in got:+ got.add(r["seq"])+ out.append({"seat": seat, "from": r["from"], "seq": r["seq"], "sent_k": r["k"], "k": int(k)})+ return out++ def say(self, seat: str, text, k: int, dt: float) -> tuple[int, dict]:+ if not self.enabled:+ if self.declared:+ return 403, {"error": "the team channel is off in this task (no-communication setting)"}+ return 404, {"error": "this task has no team channel"}+ if not isinstance(text, str) or not text.strip():+ return 400, {"error": "text must be a non-empty string"}+ if len(text.encode()) > self.max_bytes:+ return 400, {"error": f"at most {self.max_bytes} bytes per message"}+ sent = sum(1 for m in self.log if m["seat"] == seat)+ if sent >= self.max_messages:+ return 429, {"error": f"at most {self.max_messages} messages per match"}+ gap = self.min_interval_s / dt if dt else 0+ if seat in self.last_k and k - self.last_k[seat] < gap:+ return 429, {"error": f"at most one message every {self.min_interval_s} game seconds"}+ self.last_k[seat] = k+ side = self.cfg.side_of(seat)+ self.seq[side] = self.seq.get(side, 0) + 1+ msg = {"seat": seat, "side": side, "k": k, "seq": self.seq[side], "text": text}+ self.log.append(msg)+ return 200, {"sent": {"k": k, "t_sim": k * dt, "seq": msg["seq"]}}++ @staticmethod+ def since_arg(value, name: str = "team_since"):+ """A client's read mark: None (absent) or a non-negative integer seq; anything else is the caller's error."""+ if value is None:+ return None+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):+ raise Refused(f"{name} must be a non-negative integer (a seq)")+ try:+ n = int(value)+ except (TypeError, ValueError, OverflowError):+ raise Refused(f"{name} must be a non-negative integer (a seq)") from None+ if n < 0 or n != float(value):+ raise Refused(f"{name} must be a non-negative integer (a seq)")+ return n++ def _side_log(self, seat: str, k: int) -> list[dict]:+ side = self.cfg.side_of(seat)+ return [m for m in self.log if m["side"] == side and m["k"] <= k]++ @staticmethod+ def _row(m) -> dict:+ return {"from": m["seat"], "seq": m["seq"], "k": m["k"], "text": m["text"]}++ def messages(self, seat: str, k: int, dt: float, since: int | None = None) -> tuple[list[dict], int]:+ """(the teammates' messages for `seat` at step k, the side's newest seq). With a read mark: every message with+ seq > since (at most page_max, the oldest first); without: the recent ones (the last recent_s game seconds,+ at most recent_max). Never consumes."""+ if not self.enabled:+ return [], 0+ log = self._side_log(seat, k)+ top = log[-1]["seq"] if log else 0+ mates = [m for m in log if m["seat"] != seat]+ if since is None:+ lo = k - (self.recent_s / dt if dt else 0)+ out = [m for m in mates if m["k"] >= lo][-self.recent_max:]+ else:+ out = [m for m in mates if m["seq"] > since][:self.page_max]+ return [self._row(m) for m in out], top++ def page(self, seat: str, k: int, since) -> tuple[int, dict]:+ """POST /<seat>/team {"since": n}: the teammates' messages after seq n (default 0), at most page_max."""+ if not self.enabled:+ if self.declared:+ return 403, {"error": "the team channel is off in this task (no-communication setting)"}+ return 404, {"error": "this task has no team channel"}+ n = self.since_arg(since if since is not None else 0, "since")+ log = self._side_log(seat, k)+ mates = [m for m in log if m["seat"] != seat and m["seq"] > n]+ return 200, {"messages": [self._row(m) for m in mates[:self.page_max]],+ "team_seq": log[-1]["seq"] if log else 0, "more": len(mates) > self.page_max}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/client.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/client.pynew file mode 100644index 0000000000..84258d872b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/client.py@@ -0,0 +1,147 @@+"""Contract ①, the player's side: a stdlib client of the match service and the loop that lets a built-in player (the+sport's reference player, scripted opponents, check policies) play over HTTP exactly as a model's program would.++A built-in player is an object made by factory(spec, seat, seed) with+ act(view) -> body | None view = {"state": <the seat's state>, "observation": <the /observe observation>}+ (body = the /act request; None = nothing now, realtime only)+ review(reply) -> (why, plan) optional; called after each own action (turn) or at each review (realtime)+ message(view) -> text | None optional (realtime, core 0.2.21): a team-channel message to the seat's teammates+ (POST /say; refused messages, e.g. faster than the channel allows, are dropped)++ python3 -m core.client MODULE:FACTORY (SIM_URL, SEAT; e.g. the task's solution/oracle_play.py)+"""+from __future__ import annotations++import importlib+import json+import os+import sys+import time+import urllib.error+import urllib.request+++class Seat:+ """One seat's calls. The service allows 20 requests per second and 4 open requests per seat: the client keeps+ under that (MIN_GAP_S between calls) and retries a request the HTTP layer refused before reading it (a bare 429+ or a reset connection), which never reached the match."""+ MIN_GAP_S = 0.06++ def __init__(self, base: str, seat: str, timeout: float = 600):+ self.base, self.seat, self.timeout, self.last = base.rstrip("/"), seat, timeout, 0.0++ def call(self, ep: str, body: dict | None = None, tries: int = 20) -> dict:+ for i in range(tries):+ time.sleep(max(0.0, self.last + self.MIN_GAP_S - time.monotonic()))+ self.last = time.monotonic()+ req = urllib.request.Request(f"{self.base}/{self.seat}/{ep}",+ data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=self.timeout) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ raw = e.read()+ if e.code == 429 and not raw and i + 1 < tries: # the HTTP layer's limit, not the match's+ time.sleep(0.25 * (i + 1))+ continue+ try:+ out = json.loads(raw)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+ except urllib.error.URLError as e:+ if isinstance(e.reason, (BrokenPipeError, ConnectionResetError, ConnectionRefusedError)) and \+ i + 1 < tries:+ time.sleep(0.25 * (i + 1))+ continue+ raise+ raise RuntimeError("the match service kept refusing")+++def wait_for(base: str, seat: str, deadline_s: float = 300) -> dict:+ t = time.time()+ while time.time() - t < deadline_s:+ try:+ out = Seat(base, seat, 10).call("spec")+ if "error" not in out:+ return out+ except OSError:+ pass+ time.sleep(1)+ raise RuntimeError("the match service did not answer")+++def review_of(player, reply) -> tuple[str, str]:+ f = getattr(player, "review", None)+ return f(reply) if f else ("played as planned", "go on with the same plan")+++REPLY_IMAGES = [0] # acts whose reply carried images of their result (core 0.2.8)+++def play_turn(c: Seat, player) -> dict:+ c.call("start", {})+ while True:+ st = c.call("wait", {"timeout_s": 60}).get("state") or {}+ if st.get("done"):+ return st+ if not st.get("your_turn"):+ continue+ if st.get("awaiting_review"):+ why, plan = review_of(player, st)+ c.call("ready", {"why": why, "plan": plan})+ continue+ view = c.call("observe", {})+ body = player.act({"state": view.get("state") or {}, "observation": view.get("observation") or {}})+ reply = c.call("act", body)+ REPLY_IMAGES[0] += bool((reply.get("observation") or {}).get("image_png_b64"))+ if (reply.get("state") or {}).get("done"):+ return reply["state"]+ if reply.get("http_status"):+ print("refused:", json.dumps(reply)[:300], file=sys.stderr)+ continue+ why, plan = review_of(player, reply)+ c.call("ready", {"why": why, "plan": plan})+++def play_realtime(c: Seat, player, every_s: float = 0.05) -> dict:+ c.call("start", {})+ while True:+ view = c.call("observe", {})+ now = view.get("now") or {}+ if now.get("done"):+ return now+ if now.get("world") == "frozen" and now.get("phase") == "review" and not now.get("ready", {}).get(c.seat):+ why, plan = review_of(player, now)+ c.call("ready", {"why": why, "plan": plan})+ continue+ if now.get("world") == "running":+ v = {"state": now, "observation": view.get("observation") or {}}+ body = player.act(v)+ if body is not None:+ c.call("act", body)+ say = getattr(player, "message", None)+ text = say(v) if say is not None else None+ if text:+ c.call("say", {"text": text})+ c.call("wait", {"dt": every_s})+++def main(argv):+ mod, _, name = argv[0].partition(":")+ sys.path.insert(0, os.getcwd())+ factory = getattr(importlib.import_module(mod), name or "Reference")+ base, seat = os.environ.get("SIM_URL", "http://sim:8000"), os.environ.get("SEAT", "A")+ spec = wait_for(base, seat)+ player = factory(spec, seat, int(os.environ.get("RO_PLAYER_SEED", "0")))+ c = Seat(base, seat)+ proto = spec.get("protocol", "")+ end = play_turn(c, player) if proto.startswith("eai-standard-turn") else play_realtime(c, player)+ print(json.dumps({"final_state": {k: end.get(k) for k in ("reason", "won", "winner", "scores") if k in end},+ "replies_with_images": REPLY_IMAGES[0]}))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/diaglog.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/diaglog.pynew file mode 100644index 0000000000..76eefa943d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/diaglog.py@@ -0,0 +1,93 @@+"""Diagnostic records (core 0.2.25): environment-side rows of episode.jsonl for the post-match diagnosis+(core/diagnose.py). They are information only: no replay reads them, they are not in commands_sha or any state hash,+they never change what a seat is sent, and a failure to write one never ends a match.++Rows (every row also has the episode's "ev", "ts", "wall"):+ {"ev": "observe", "seat", "obs_id", "k", "view_steps", "query", ...} an observation returned to the seat: k = the+ step of the world state it reports; view_steps = the step of each image frame (the sport's camera job may+ report older frames, e.g. a short history; [k] for the core's cameras; [] without images); obs_id counts the+ seat's observations (1, 2, ...)+ {"ev": "act_received", "seat", "k", "act_id", "obs_id_last", "seen", "entity", "decision", ...} an act accepted+ for its effect: act_id = 1, 2, ... per seat (the order the service accepted them); obs_id_last = the seat's+ latest observation returned before the act arrived (None: none yet); seen = the step of the latest world state+ sent to the seat in any reply (the reaction report's s, core 0.2.23)+ {"ev": "effect", "seat", "act_id", "k", "entity", ["rejected"], ["info"]} that act's command took effect before+ step k (it follows its `cmd` row; the cmd row itself is unchanged); turn protocol: info = Match.apply's answer+ {"ev": "act_dropped", "seat", "act_id", "k", "why"} that act never took effect; why: unit_over (the unit ended+ before its effect step), unit_over_planning (it ended while the act was planned), unit_changed, match_over+ {"ev": "event", "k", "events"} what Match.step() returned for the step that ended at k (non-empty lists only)+ {"ev": "team_delivered", "seat", "from", "seq", "sent_k", "k"} a teammate's message first returned to `seat` at+ step k (sent at sent_k), once per recipient and message+"""+from __future__ import annotations++import math++DIAG_ROWS = ("observe", "act_received", "effect", "act_dropped", "event", "team_delivered")+++def jsonable(x, depth: int = 0):+ """A JSON-safe copy of what a sport returned (numpy scalars and arrays, tuples, sets; anything else as its repr)."""+ if depth > 12:+ return repr(x)[:200]+ if x is None or isinstance(x, (bool, str, int)):+ return x+ if isinstance(x, float):+ return x if math.isfinite(x) else None+ if isinstance(x, dict):+ return {str(k): jsonable(v, depth + 1) for k, v in x.items()}+ if isinstance(x, (list, tuple, set, frozenset)):+ return [jsonable(v, depth + 1) for v in x]+ tolist = getattr(x, "tolist", None) # numpy arrays and scalars+ if callable(tolist):+ try:+ return jsonable(tolist(), depth + 1)+ except Exception: # noqa: BLE001+ pass+ return repr(x)[:200]+++def view_steps(meta: dict | None, job, k: int) -> list[int]:+ """The step of each image frame of an observation: the sport's own (camera job meta `view_steps`), else [k] when+ images were made from the state now, else []."""+ vs = (meta or {}).get("view_steps")+ if isinstance(vs, (list, tuple)):+ try:+ return [int(v) for v in vs]+ except (TypeError, ValueError):+ pass+ return [] if job is None else [int(k)]+++class Acts:+ """Per-seat act ids and the latest observation returned to each seat (what act_received links to)."""++ def __init__(self, seats):+ self.next = {s: 0 for s in seats}+ self.last_obs: dict = {s: None for s in seats}++ def new(self, seat) -> int:+ self.next[seat] = self.next.get(seat, 0) + 1+ return self.next[seat]++ def observed(self, seat, obs_id):+ self.last_obs[seat] = obs_id++ def new_obs(self, seat) -> int:+ """In-process play (core/local.py): the next observation id, returned at once."""+ n = (self.last_obs.get(seat) or 0) + 1+ self.last_obs[seat] = n+ return n+++def safe(write):+ """A row writer that never raises (a diagnostic row must not end a match)."""+ def w(ev, **row):+ try:+ write(ev, **row)+ except Exception: # noqa: BLE001+ try:+ write(ev, **{k: jsonable(v) for k, v in row.items()})+ except Exception: # noqa: BLE001+ pass+ return wdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/diagnose.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/diagnose.pynew file mode 100644index 0000000000..a006962eba--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/diagnose.py@@ -0,0 +1,443 @@+"""Post-match diagnosis (core 0.2.25; capability measurement framework §7): read a finished match's records, replay+its world deterministically, and run the sport's analysis (sports/<sport>/diagnose.py). Nothing here is part of a+match: no match imports it, it changes no record, and a bug in it changes no official result.++ python -m core.diagnose PLUGIN RUN_DIR [--diagnose FILE] [--out DIR] [--no-sport]++RUN_DIR holds episode.jsonl (or episode.jsonl.gz) and, when there are any, final.json, replay_check.json,+local_result.json and the program snapshots (snapshots/, or ../snapshots/ and ../../snapshots/ of a Harbor trial:+tools/snapshot_watch.py). Writes RUN_DIR/diag/ (or --out): units.jsonl, claims.jsonl, summary.json.++The sport's analysis, sports/<sport>/diagnose.py (never copied into a task: tools/sportlib.NOT_IN_SIM):+ units(rep) -> [{"id", "seat", "k0", "k1", ...}] decision units (one incoming ball, one possession ...)+ implied(rep, units) -> [{"unit", "seat", "k_cmd", "act_id", "quantity", "implied", "truth", "err_space",+ "err_time", ...}] claims read from the commands, with the true value+ metrics(units, claims) -> {seat: {metric_id: {"value", "capability", "status", ...}}}+ capability in A1 A2 A3 A4 B1 B2 B3 C1 C2; status in official conditional behaviour unvalidated+Looked up as --diagnose, else diagnose.py next to PLUGIN, else sports/<sport>/diagnose.py of this repository.++rep = load(run_dir, plugin) (INTERFACE "diag/1"):+ interface, run_dir, plugin, sport, protocol, revision, core_version, header, cfg (dict), seats, sides+ {seat: side}, dt (control step, s; None without a plugin)+ rows every row of episode.jsonl, in order+ cmd, observe, act_received, effect, act_dropped, event, team, team_delivered, unit_over, resume, ready, review,+ forfeit, retire, end the rows of that "ev", in order ([] when the episode has none)+ has {name: bool}: which diagnostic rows the episode has (core >= 0.2.25 writes them)+ obs {seat: {obs_id: observe row}}+ acts {seat: [act]} in act_id order; act = {act_id, seat, entity, k_recv, unit, decision,+ obs_id_last, obs (its observe row or None), k_obs, view_steps, seen, k_effect (None:+ no effect), cmd (the low-level command that took effect, or None), rejected, dropped+ (why, or None)}+ events [{"k", **event}]: every event Match.step() returned (event rows, flattened)+ final, replay_check, local_result those JSON files, or None+ snapshots {"dir", "rows": snapshots.jsonl rows, "procs": procs.jsonl rows} per seat, or {}+ world world(build=None) -> World: a fresh deterministic replay (below); build(cfg) -> Match+ replaces the sport's build (e.g. a screening variant's patched opponent)+World (realtime: k = control steps; turn: k = Match.k, the actions so far):+ w.at(k, after=False) the Match with m.k == k, as the seats saw it at k: before the rows logged at k+ (commands that took effect before step k); after=True: after them. Forward is cheap,+ backward rebuilds from the start.+ w.m, w.k the match now and its step+ w.events {k: events} that Match.step() returned while replaying (also for old episodes)+ w.run(fn) calls fn(m) at every step to the end (realtime: after each step; turn: after each row)+ w.fork() an independent match in the same state (counterfactual play): a deep copy, else a+ second replay to the same point+"""+from __future__ import annotations++import argparse+import copy+import gzip+import hashlib+import importlib.util+import json+import math+import os+import statistics+import sys+from pathlib import Path++from .episode import REPLAYED, _dispatch, header_cfg, load_plugin+from .sport import FINISHED++INTERFACE = "diag/1"+ROWS = ("cmd", "observe", "act_received", "effect", "act_dropped", "event", "team", "team_delivered", "unit_over",+ "resume", "ready", "review", "forfeit", "retire", "end")+DIAG = ("observe", "act_received", "effect", "act_dropped", "event", "team_delivered")+CAPABILITIES = ("A1", "A2", "A3", "A4", "B1", "B2", "B3", "C1", "C2")+STATUSES = ("official", "conditional", "behaviour", "unvalidated")+ROOT = Path(__file__).resolve().parents[1]+++def read_episode(run_dir) -> list[dict]:+ d = Path(run_dir)+ if (d / "episode.jsonl").exists():+ text = (d / "episode.jsonl").read_text()+ elif (d / "episode.jsonl.gz").exists():+ with gzip.open(d / "episode.jsonl.gz", "rt") as f:+ text = f.read()+ else:+ raise FileNotFoundError(f"no episode.jsonl in {d}")+ out = []+ for line in text.splitlines():+ if line.strip():+ try:+ out.append(json.loads(line))+ except json.JSONDecodeError: # a line cut by a killed writer: the rest is still usable+ continue+ return out+++def _json(p: Path):+ try:+ return json.loads(p.read_text())+ except (OSError, json.JSONDecodeError):+ return None+++def _jsonl(p: Path) -> list[dict]:+ try:+ return [json.loads(x) for x in p.read_text().splitlines() if x.strip()]+ except (OSError, json.JSONDecodeError):+ return []+++def find_snapshots(run_dir) -> dict:+ """Program snapshots of the match (tools/snapshot_watch.py): {seat: {"dir", "rows", "procs"}}."""+ d = Path(run_dir).resolve()+ for base in (d / "snapshots", d.parent / "snapshots", d.parent.parent / "snapshots"):+ if base.is_dir():+ out = {}+ for s in sorted(x for x in base.iterdir() if x.is_dir()):+ out[s.name] = {"dir": str(s), "rows": _jsonl(s / "snapshots.jsonl"), "procs": _jsonl(s / "procs.jsonl")}+ return out+ return {}+++def link_acts(rows: list[dict]) -> tuple[dict, dict]:+ """(acts by seat, observations by seat): every accepted act with its observation, effect step and command."""+ obs: dict = {}+ acts: dict = {}+ last_cmd: dict = {} # seat -> the latest cmd row (an effect row follows its cmd row)+ for r in rows:+ ev = r.get("ev")+ if ev == "observe" and "obs_id" in r:+ obs.setdefault(r["seat"], {})[r["obs_id"]] = r+ elif ev == "cmd":+ last_cmd[r["seat"]] = r+ elif ev == "act_received" and r.get("act_id") is not None:+ seat = r["seat"]+ o = obs.get(seat, {}).get(r.get("obs_id_last"))+ acts.setdefault(seat, {})[r["act_id"]] = {+ "act_id": r["act_id"], "seat": seat, "entity": r.get("entity"), "k_recv": r.get("k"),+ "unit": r.get("unit"), "decision": r.get("decision"), "obs_id_last": r.get("obs_id_last"), "obs": o,+ "k_obs": o.get("k") if o else None, "view_steps": o.get("view_steps") if o else None,+ "seen": r.get("seen"), "k_effect": None, "cmd": None, "rejected": False, "dropped": None}+ elif ev == "effect":+ a = acts.get(r["seat"], {}).get(r.get("act_id"))+ if a is not None:+ c = last_cmd.get(r["seat"])+ a["k_effect"] = r.get("k")+ a["cmd"] = c.get("cmd") if c is not None and c.get("k") == r.get("k") else None+ a["rejected"] = bool(r.get("rejected"))+ if "info" in r:+ a["info"] = r["info"]+ elif ev == "act_dropped":+ a = acts.get(r["seat"], {}).get(r.get("act_id"))+ if a is not None:+ a["dropped"] = r.get("why")+ return {s: [v[i] for i in sorted(v)] for s, v in acts.items()}, obs+++class World:+ """A deterministic replay of the episode's world, stepped forward on demand (see the module text)."""++ def __init__(self, sport, rows: list[dict], build=None):+ self.sport, self.build, self.rows = sport, build, rows+ self.head = next(r for r in rows if r["ev"] == "header")+ self.cfg = header_cfg(self.head)+ self.rep = [r for r in rows if r["ev"] in REPLAYED and r["ev"] != "header"]+ end = next((r for r in self.rep if r["ev"] == "end"), None)+ self.turn = sport.protocol == "turn"+ if not self.turn:+ self.at_k: dict = {}+ for r in self.rep:+ self.at_k.setdefault(int(r["k"]), []).append(r)+ self.k_end = int(end["k"]) if end else max(self.at_k, default=0)+ self.events: dict = {}+ self.reset()++ def reset(self):+ self.m = (self.build or self.sport.build)(self.cfg)+ self.forfeits, self.retired = [], []+ self.done_k = None # realtime: the step whose rows were applied+ self.i = 0 # turn: the next row++ @property+ def k(self) -> int:+ return int(self.m.k)++ def _apply_rows(self):+ if self.done_k != self.m.k:+ for r in self.at_k.get(self.m.k, []):+ _dispatch(self.m, r, self.forfeits, self.retired)+ self.done_k = self.m.k++ def _step(self) -> bool:+ """Realtime: the rows of this step, then one step; False at the end of the match."""+ self._apply_rows()+ if self.m.phase().state == FINISHED or self.m.k >= self.k_end:+ return False+ ev = self.m.step()+ if ev:+ self.events[self.m.k] = ev+ return True++ def at(self, k: int, after: bool = False):+ k = int(k)+ if self.turn:+ if self.i:+ last = int(self.rep[self.i - 1].get("k", 0))+ if last > k or (last == k and not after):+ self.reset()+ while self.i < len(self.rep):+ r = self.rep[self.i]+ rk = int(r.get("k", self.m.k))+ if rk > k or (rk == k and not after):+ break+ _dispatch(self.m, r, self.forfeits, self.retired)+ self.i += 1+ return self.m+ if k < self.k or (k == self.k and self.done_k == k and not after):+ self.reset()+ while self.k < k:+ if not self._step():+ break+ if after and self.k == k:+ self._apply_rows()+ return self.m++ def run(self, fn=None):+ """To the end of the match, fn(m) after every step (turn: after every row)."""+ if self.turn:+ while self.i < len(self.rep):+ _dispatch(self.m, self.rep[self.i], self.forfeits, self.retired)+ self.i += 1+ if fn is not None:+ fn(self.m)+ return self.m+ while self._step():+ if fn is not None:+ fn(self.m)+ return self.m++ def fork(self):+ """An independent match in the state of this one, for counterfactual play: a deep copy, or (a match that+ cannot be copied, e.g. one holding MuJoCo rollout objects) a second replay to the same point."""+ try:+ return copy.deepcopy(self.m)+ except Exception: # noqa: BLE001+ w = World(self.sport, self.rows, self.build)+ if self.turn:+ while w.i < self.i:+ _dispatch(w.m, w.rep[w.i], w.forfeits, w.retired)+ w.i += 1+ else:+ w.at(self.k, after=self.done_k == self.k)+ return w.m+++def load(run_dir, plugin: str | None = None, build=None) -> dict:+ """The records of one match as the sport's analysis reads them (the module text lists the keys)."""+ d = Path(run_dir)+ rows = read_episode(d)+ head = next((r for r in rows if r.get("ev") == "header"), None)+ if head is None:+ raise ValueError(f"{d}: the episode has no header")+ cfg = head["cfg"]+ seats = list(cfg["seats"])+ sides = {s: (cfg.get("sides") or {}).get(s, s) for s in seats}+ by = {name: [] for name in ROWS}+ for r in rows:+ if r.get("ev") in by:+ by[r["ev"]].append(r)+ acts, obs = link_acts(rows)+ events = [{"k": r["k"], **(e if isinstance(e, dict) else {"value": e})} for r in by["event"]+ for e in (r.get("events") or [])]+ sport = load_plugin(plugin) if plugin else None+ dt = None+ if sport is not None:+ try:+ dt = float((build or sport.build)(header_cfg(head)).dt or 0) or None+ except Exception: # noqa: BLE001+ dt = None++ def world(build_override=None):+ if sport is None:+ raise RuntimeError("load(run_dir, plugin) without a plugin has no world()")+ return World(sport, rows, build_override or build)++ rep = {"interface": INTERFACE, "run_dir": str(d), "plugin": plugin, "sport": head.get("sport"),+ "protocol": head.get("protocol") or (sport.protocol if sport else None), "revision": head.get("revision"),+ "core_version": (head.get("versions") or {}).get("core"), "header": head, "cfg": cfg, "seats": seats,+ "sides": sides, "dt": dt, "rows": rows, **by, "has": {n: bool(by[n]) for n in DIAG}, "obs": obs,+ "acts": acts, "events": events, "final": _json(d / "final.json"),+ "replay_check": _json(d / "replay_check.json"), "local_result": _json(d / "local_result.json"),+ "snapshots": find_snapshots(d), "world": world}+ return rep+++def _q(v: list, p: float):+ if not v:+ return None+ x = sorted(v)+ return x[min(len(x) - 1, max(0, math.ceil(p * len(x)) - 1))]+++def linkage(rep: dict) -> dict:+ """Per seat: how completely the acts link to an observation and to an effect or a drop (the logging check)."""+ out = {}+ for seat in rep["seats"]:+ A = rep["acts"].get(seat, [])+ ids = [a["act_id"] for a in A]+ eff = [a for a in A if a["k_effect"] is not None]+ drop = [a for a in A if a["dropped"] is not None]+ lag_obs = [a["k_effect"] - a["k_obs"] for a in eff if a["k_obs"] is not None]+ lag_recv = [a["k_effect"] - a["k_recv"] for a in eff if a["k_recv"] is not None]+ out[seat] = {+ "acts": len(A), "act_ids_contiguous": ids == list(range(1, len(A) + 1)),+ "with_observation": sum(a["obs"] is not None for a in A),+ "obs_id_unknown": sum(a["obs_id_last"] is not None and a["obs"] is None for a in A),+ "before_any_observation": sum(a["obs_id_last"] is None for a in A),+ "effect": len(eff), "effect_with_cmd": sum(a["cmd"] is not None for a in eff),+ "dropped": len(drop), "dropped_by": {w: sum(a["dropped"] == w for a in drop)+ for w in sorted({a["dropped"] for a in drop})},+ "unresolved": sum(a["k_effect"] is None and a["dropped"] is None for a in A),+ "both": sum(a["k_effect"] is not None and a["dropped"] is not None for a in A),+ "obs_to_effect_steps": {"median": statistics.median(lag_obs) if lag_obs else None,+ "p90": _q(lag_obs, 0.9), "max": max(lag_obs, default=None)},+ "recv_to_effect_steps": {"median": statistics.median(lag_recv) if lag_recv else None,+ "max": max(lag_recv, default=None)},+ "observations": len(rep["obs"].get(seat, {})),+ }+ return out+++def c1(rep: dict) -> dict:+ """C1 (description only, framework §3): the program's reliability from the core's rows, per seat."""+ out = {}+ dt = rep.get("dt") or 0.0+ refused = {}+ for r in rep["rows"]:+ if r.get("ev") in ("refused_invalid", "refused_not_model", "refused_query"):+ refused.setdefault(r.get("seat"), {}).setdefault(r["ev"], 0)+ refused[r.get("seat")][r["ev"]] += 1+ for seat in rep["seats"]:+ A = rep["acts"].get(seat, [])+ eff = [a for a in A if a["k_effect"] is not None]+ ks = [a["k_effect"] for a in eff]+ gaps = [b - a for a, b in zip(ks, ks[1:])]+ out[seat] = {"acts": len(A), "effects": len(eff), "rejected": sum(a["rejected"] for a in eff),+ "dropped": sum(a["dropped"] is not None for a in A), "refused": refused.get(seat, {}),+ "first_effect_k": ks[0] if ks else None,+ "first_effect_s": round(ks[0] * dt, 4) if ks and dt else None,+ "effect_gap_steps": {"median": statistics.median(gaps) if gaps else None, "p90": _q(gaps, 0.9),+ "max": max(gaps, default=None)},+ "observations": len(rep["obs"].get(seat, {}))}+ return out+++def load_diagnoser(path):+ spec = importlib.util.spec_from_file_location("ro_sport_diagnose", path)+ mod = importlib.util.module_from_spec(spec)+ sys.path.insert(0, str(Path(path).resolve().parent))+ spec.loader.exec_module(mod)+ return mod+++def find_diagnoser(plugin: str | None, sport: str | None, given: str | None = None):+ if given:+ return Path(given)+ for p in ([Path(plugin).resolve().parent / "diagnose.py"] if plugin else []) + \+ ([ROOT / "sports" / sport / "diagnose.py"] if sport else []):+ if p.is_file():+ return p+ return None+++def check_metrics(metrics) -> list[str]:+ """The shape of metrics() (the shared interface): per seat {metric_id: {value, capability, status}}."""+ bad = []+ if not isinstance(metrics, dict):+ return ["metrics() must return {seat: {metric_id: {...}}}"]+ for seat, ms in metrics.items():+ if not isinstance(ms, dict):+ bad.append(f"{seat}: not a dict")+ continue+ for mid, v in ms.items():+ if not isinstance(v, dict) or "value" not in v:+ bad.append(f"{seat}.{mid}: needs value")+ continue+ if v.get("capability") not in CAPABILITIES:+ bad.append(f"{seat}.{mid}: capability {v.get('capability')!r} not in {CAPABILITIES}")+ if v.get("status") not in STATUSES:+ bad.append(f"{seat}.{mid}: status {v.get('status')!r} not in {STATUSES}")+ return bad+++def _dump(x):+ from .diaglog import jsonable+ return json.dumps(jsonable(x))+++def diagnose(rep: dict, mod=None, out: Path | None = None) -> dict:+ """Run the sport's analysis (mod: its diagnose module, or None for the core's part only) and write out/."""+ out = Path(out or Path(rep["run_dir"]) / "diag")+ out.mkdir(parents=True, exist_ok=True)+ units, claims, metrics, errors = [], [], {}, []+ if mod is not None:+ units = list(mod.units(rep))+ claims = list(mod.implied(rep, units))+ metrics = mod.metrics(units, claims)+ errors += check_metrics(metrics)+ (out / "units.jsonl").write_text("".join(_dump(u) + "\n" for u in units))+ (out / "claims.jsonl").write_text("".join(_dump(c) + "\n" for c in claims))+ fin = rep.get("final") or rep.get("local_result") or {}+ summary = {"interface": INTERFACE, "sport": rep["sport"], "revision": rep["revision"],+ "core_version": rep["core_version"], "run_dir": rep["run_dir"], "seats": rep["seats"],+ "has": rep["has"], "outcome": {k: fin.get(k) for k in ("scores", "winner", "valid_trial", "reason")+ if k in fin},+ "diagnoser": None if mod is None else {+ "file": getattr(mod, "__file__", None),+ "sha256": hashlib.sha256(Path(mod.__file__).read_bytes()).hexdigest() if getattr(+ mod, "__file__", None) else None,+ "validity": getattr(mod, "VALIDITY_REPORT", None)},+ "units": len(units), "claims": len(claims), "metrics": metrics, "linkage": linkage(rep),+ "c1": c1(rep), "events": len(rep["events"]), "snapshots": {+ s: {"snapshots": len(v["rows"]), "saved": sum(1 for r in v["rows"] if r.get("tar")),+ "procs": len(v["procs"])} for s, v in rep["snapshots"].items()},+ "errors": errors}+ (out / "summary.json").write_text(_dump(summary))+ return summary+++def main(argv=None):+ ap = argparse.ArgumentParser(prog="python -m core.diagnose")+ ap.add_argument("plugin")+ ap.add_argument("run_dir")+ ap.add_argument("--diagnose", default=None, help="the sport's diagnose.py (default: next to PLUGIN, else "+ "sports/<sport>/diagnose.py)")+ ap.add_argument("--out", default=None)+ ap.add_argument("--no-sport", action="store_true", help="only the core's part (linkage, C1)")+ a = ap.parse_args(argv)+ rep = load(a.run_dir, a.plugin)+ path = None if a.no_sport else find_diagnoser(a.plugin, rep["sport"], a.diagnose)+ mod = load_diagnoser(path) if path else None+ s = diagnose(rep, mod, Path(a.out) if a.out else None)+ print(json.dumps({k: s[k] for k in ("sport", "units", "claims", "errors")} | {"diagnoser": str(path) if path+ else None}))+ return 1 if s["errors"] else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/episode.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/episode.pynew file mode 100644index 0000000000..c395b61f24--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/episode.py@@ -0,0 +1,255 @@+"""Contract ③ (docs/framework_zh.md §4.3): the episode log (episode.jsonl) and the fresh-process replay.++episode.jsonl is append-only, one JSON object per line. Rows the replay reads (everything else is information):+ {"ev": "header", "cfg": MatchConfig, "sport", "revision", "protocol", "source_sha", "versions"}+ (+ realtime, core 0.2.23: "timing": {reaction_delay_steps,+ effect_delay_steps})+ {"ev": "cmd", "k": K, "seat": S, "cmd": LOW_LEVEL_COMMAND} applied before control step K (turn: as action K);+ a delayed command is logged at its effect step; a+ realtime act's row also has "seen" (core 0.2.23)+ {"ev": "resume", "k": K} a review ended before step K+ {"ev": "forfeit", "k": K, "seat": S, "why": W} a core decision that ends the match+ {"ev": "retire", "k": K, "seat": S, "side": D, "why": W} a side leaves, the match goes on (N sides)+ {"ev": "end", "k": K, "reason": R}+Diagnostic rows (core 0.2.25; core/diaglog.py lists them: observe, act_received, effect, act_dropped, event,+team_delivered) are information only, like every row not listed above: the replay never reads them.+Replay (python -m core.episode PLUGIN DIR) rebuilds the match from the header, re-applies the rows at their steps and+writes DIR/replay_check.json: state_sha, scores, winner, ranking, k, commands_sha, source_sha, the continuous+score by side (sport.toml [score], core 0.2.14; null without one) and the reaction report (core 0.2.23,+reaction_report: the same numbers as final.json `reaction`).+Reply images are a pure function of the replayed match (core 0.2.8): python -m core.episode PLUGIN DIR --reply N+draws the reply image of the N-th command row (1-based) into DIR/reply_N.png (+ reply_N.json: the tiles).+"""+from __future__ import annotations++import hashlib+import importlib.util+import json+import math+import os+import statistics+import sys+import threading+import time+from pathlib import Path++from . import score as score_mod+from . import seeds as seeds_mod+from . import spec as spec_mod+from .outcome import decide+from .sport import FINISHED, MatchConfig, sha_json++REPLAYED = ("header", "cmd", "resume", "forfeit", "retire", "end")+++def source_sha(*dirs) -> str:+ """Every file under the given directories (path + bytes), so a changed simulator invalidates old episodes."""+ h = hashlib.sha256()+ for d in dirs:+ d = Path(d)+ for p in sorted(x for x in d.rglob("*") if x.is_file() and "__pycache__" not in x.parts):+ h.update(str(p.relative_to(d)).encode())+ h.update(p.read_bytes())+ return h.hexdigest()+++def load_plugin(path: str):+ """The plugin module at `path` (its directory goes first on sys.path, so its simulator modules import)."""+ path = os.path.abspath(path)+ sys.path.insert(0, os.path.dirname(path))+ spec = importlib.util.spec_from_file_location("ro_plugin", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod.SPORT+++class Episode:+ def __init__(self, path):+ self.path = Path(path)+ self.lock = threading.Lock()+ self.t0 = time.monotonic()+ self.commands = [] # the replayed rows, for commands_sha++ def write(self, ev: str, **row):+ rec = {"ev": ev, "ts": round(time.time(), 3), "wall": round(time.monotonic() - self.t0, 4), **row}+ with self.lock:+ if ev in REPLAYED and ev != "header":+ self.commands.append({k: v for k, v in rec.items() if k not in ("ts", "wall")})+ with self.path.open("a") as f:+ f.write(json.dumps(rec, default=float) + "\n")++ def commands_sha(self) -> str:+ with self.lock:+ return sha_json(self.commands)+++def reaction_report(rows, seats, react: int = 0, effect_delay: int = 0) -> dict:+ """The reaction report (core 0.2.23; report only, no effect on validity or grading). A realtime act's command row+ carries `seen` = s, the step of the latest world state the service had sent to the seat when the act arrived (any+ reply's `now`), and is logged at its effect step k; its actual delay is k - s control steps. It took effect within+ the declared reaction delay D (sport.toml [timing] reaction_delay_steps; core 0.2.18) when k - s <= D ++ effect_delay (the action layer's fixed `delay_steps`, 0 in every sport today); with D = 0 that is the next+ control-step boundary after s. Per seat: acts (rows with a known s), within_d, share = within_d / acts (None+ without acts), delay_steps {median, p90 (nearest rank), max} (None without acts), unseen (act rows without s: the+ seat had been sent no world state). Rows without `seen` (layer ticks, episodes before 0.2.23) are not acts here."""+ lags: dict = {s: [] for s in seats}+ unseen = {s: 0 for s in seats}+ for r in rows:+ if r.get("ev") != "cmd" or "seen" not in r:+ continue+ seat = r["seat"]+ lags.setdefault(seat, [])+ unseen.setdefault(seat, 0)+ if r["seen"] is None:+ unseen[seat] += 1+ else:+ lags[seat].append(int(r["k"]) - int(r["seen"]))+ limit = int(react) + int(effect_delay)+ by_seat = {}+ for seat, v in lags.items():+ x = sorted(v)+ n, within = len(x), sum(1 for d in x if d <= limit)+ by_seat[seat] = {"acts": n, "within_d": within, "share": round(within / n, 6) if n else None,+ "delay_steps": {"median": float(statistics.median(x)), "p90": x[math.ceil(0.9 * n) - 1],+ "max": x[-1]} if n else None,+ "unseen": unseen[seat]}+ return {"policy": "report_only", "reaction_delay_steps": int(react), "effect_delay_steps": int(effect_delay),+ "rule": "within D: effect step - seen step <= reaction_delay_steps + effect_delay_steps (D = 0: the next "+ "control-step boundary)", "by_seat": by_seat}+++def _dispatch(match, row, forfeits, retired, on_cmd=None):+ if row["ev"] == "cmd":+ info = match.apply(row["seat"], row["cmd"]) or {}+ if on_cmd is not None:+ on_cmd(match, row, info)+ elif row["ev"] == "resume":+ match.resume()+ elif row["ev"] == "forfeit":+ match.forfeit(row["seat"], row["why"])+ forfeits.append(row)+ elif row["ev"] == "retire":+ match.retire(row["side"], row["why"])+ retired.append(row["side"])+++def header_cfg(head: dict) -> MatchConfig:+ """The match configuration of an episode header. A hidden official seed (core/seeds.py; core 0.2.14) is written+ as -1 with its commitment: the seed comes from the environment (RO_SEED, RO_SEED_SALT: the sim service's own, or+ `tools/seeds.py resolve` on the official run host) and must give that commitment."""+ d = dict(head["cfg"])+ hid = head.get("seed_hidden")+ if hid:+ seed, salt = os.environ.get("RO_SEED", ""), os.environ.get("RO_SEED_SALT", "")+ if not seed or not salt:+ raise ValueError("a hidden-seed episode: set RO_SEED and RO_SEED_SALT (tools/seeds.py resolve)")+ if seeds_mod.commitment(head.get("sport", d.get("sport", "")), int(seed), salt) != hid.get("commitment"):+ raise ValueError("a hidden-seed episode: RO_SEED / RO_SEED_SALT do not give its commitment")+ d["seed"] = int(seed)+ return MatchConfig.from_json(d)+++def replay(sport, rows: list[dict], observer=None, on_cmd=None, decl: dict | None = None) -> dict:+ """observer(match): called with the initial state, after every turn-protocol row and after every realtime step+ (spectator video; it must not change the match). on_cmd(match, row, info): right after each command row took+ effect, with what Match.apply returned (reply images; it must not change the match either). With the sport's+ declarations (`decl`, sport.toml), also the continuous score of every side (core/score.py, core 0.2.14)."""+ head = next(r for r in rows if r["ev"] == "header")+ cfg = header_cfg(head)+ match = sport.build(cfg)+ rep = [r for r in rows if r["ev"] in REPLAYED and r["ev"] != "header"]+ end = next((r for r in rep if r["ev"] == "end"), None)+ forfeits: list[dict] = []+ retired: list[str] = []+ seen = observer or (lambda m: None)+ seen(match)+ if sport.protocol == "turn":+ for r in rep:+ _dispatch(match, r, forfeits, retired, on_cmd)+ if r["ev"] == "cmd":+ seen(match)+ else:+ at: dict[int, list] = {}+ for r in rep:+ at.setdefault(int(r["k"]), []).append(r)+ k_end = int(end["k"]) if end else max(at, default=0)+ while True:+ for r in at.pop(match.k, []):+ _dispatch(match, r, forfeits, retired, on_cmd)+ if match.phase().state == FINISHED or match.k >= k_end:+ break+ match.step()+ seen(match)+ if at:+ raise ValueError(f"rows after the end of the match at steps {sorted(at)[:5]}")+ fo = forfeits[0] if forfeits else None+ out = decide(match, fo["seat"] if fo else None, fo["why"] if fo else None, cfg.side_list(), cfg.side_of,+ retired)+ return {"state_sha": match.state_digest(), "scores": match.scores(), "winner": out.winner,+ "ranking": out.ranking, "decided_by": out.decided_by, "k": match.k,+ "finished": match.phase().state == FINISHED,+ "commands_sha": sha_json([{k: v for k, v in r.items() if k not in ("ts", "wall")} for r in rep]),+ "source_sha": head.get("source_sha"), "revision": head.get("revision"), "cfg": head["cfg"],+ "continuous": _continuous(match, decl, cfg, fo, retired),+ "reaction": None if sport.protocol == "turn" else+ reaction_report(rep, cfg.seats, *(int((head.get("timing") or {}).get(k) or 0)+ for k in ("reaction_delay_steps", "effect_delay_steps")))}+++def _continuous(match, decl, cfg, fo, retired):+ """The replayed continuous score by side (as Service.continuous), None without a declaration."""+ if not decl:+ return None+ gone = list(retired) + ([cfg.side_of(fo["seat"])] if fo else [])+ c = score_mod.compute(match, decl, cfg.side_list(), gone)+ return c and c["by_side"]+++def read_rows(path) -> list[dict]:+ return [json.loads(x) for x in Path(path).read_text().splitlines() if x.strip()]+++def reply_image(plugin: str, rows: list[dict], n: int) -> dict | None:+ """The reply image of the n-th command row (1-based), drawn from the replayed match as the live service drew it+ (the same job, the task's renderer of the header's cfg, the players' scene): {"png", "tiles", ...} or None."""+ from . import spec as spec_mod+ from .observe import CameraWorker, players_scene, reply_job+ sport = load_plugin(plugin)+ columns = int((spec_mod.load(plugin).get("observation") or {}).get("columns", 2))+ got, count = [], [0]++ def on_cmd(match, row, info):+ count[0] += 1+ if count[0] == n and hasattr(match, "reply_views"):+ got.append(reply_job(match, match.reply_views(row["seat"], row["cmd"], info), columns))+ replay(sport, rows, on_cmd=on_cmd)+ if not got or got[0] is None:+ return None+ cfg = header_cfg(next(r for r in rows if r["ev"] == "header"))+ return CameraWorker(players_scene(sport, plugin, cfg), cfg.renderer).draw_job(got[0])+++def main(argv):+ plugin, d = argv[0], Path(argv[1])+ if "--reply" in argv:+ n = int(argv[argv.index("--reply") + 1])+ img = reply_image(plugin, read_rows(d / "episode.jsonl"), n)+ if img is None:+ print(json.dumps({"reply": n, "image": False}))+ return+ (d / f"reply_{n}.png").write_bytes(img["png"])+ (d / f"reply_{n}.json").write_text(json.dumps({k: v for k, v in img.items() if k != "png"}))+ print(json.dumps({"reply": n, "image": str(d / f"reply_{n}.png"), "tiles": len(img["tiles"])}))+ return+ sport = load_plugin(plugin)+ rows = read_rows(d / "episode.jsonl")+ out = replay(sport, rows, decl=spec_mod.load(plugin))+ hid = next(r for r in rows if r["ev"] == "header").get("seed_hidden")+ if hid: # the commitment the replay's seed gave (never the seed)+ out["seed_commitment"] = hid["commitment"]+ (d / "replay_check.json").write_text(json.dumps(out, default=float))+ print(json.dumps({k: out[k] for k in ("state_sha", "scores", "winner", "k")}, default=float))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/game.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/game.pynew file mode 100644index 0000000000..10223a69ca--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/game.py@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""game - your seat in the match (the same commands for every sport; the actions are the sport's, see `game spec`).++ game spec the sport: actions (types, fields, ranges), cameras, units, rules, timing+ game status the current state, no images+ game start you are ready (preparation over); the match begins when every seat has started+ game wait [SECONDS] turn-based: block until it is your turn; real time: let the world run SECONDS (<= 1)+ game observe [QUERY_JSON] the state and the camera images (saved as PNG under /app/output/views/)+ game act ACTION_JSON one action, e.g. game act '{"type": "throw", ...}' (if the sport shows the result+ in images, they are saved like observe's, as reply_*.png)+ game ready "WHY" "PLAN" your review (after each of your actions, turn-based; at each review, real time)+ game say "TEXT" team formats: a message to your teammates (never shown to the other side)+ game team [SINCE] team formats: your teammates' messages after seq SINCE (default 0); reading never+ consumes them (observe / status show the recent ones and team_seq, the newest seq)+Sport shortcuts (generated from the sport's declaration):+@@SHORTCUTS@@"""+import base64+import json+import os+import sys+import tempfile+import urllib.error+import urllib.request++COMMANDS = json.loads('@@COMMANDS@@') # shortcut -> [action type, field, field, ...]+VIEWS = "/app/output/views"+BASE = os.environ.get("SIM_URL", "http://sim:8000") + "/" + os.environ.get("SEAT", "A")+++def call(ep, body=None):+ req = urllib.request.Request(BASE + "/" + ep, data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=600) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ try:+ out = json.load(e)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+++def save(b64, name):+ os.makedirs(VIEWS, exist_ok=True)+ fd, p = tempfile.mkstemp(dir=VIEWS, prefix=name + "_", suffix=".png")+ with os.fdopen(fd, "wb") as f:+ f.write(base64.b64decode(b64))+ return p+++def show(o):+ ob = o.get("observation")+ if isinstance(ob, dict) and ob.get("image_png_b64"):+ ob["image_file"] = save(ob.pop("image_png_b64"), "reply" if ob.get("of") else "obs")+ for k in [k for k in o if k.endswith("_image_b64")]:+ if o[k]:+ o[k[:-4] + "_file"] = save(o.pop(k), k[:-10])+ else:+ o.pop(k)+ print(json.dumps(o, indent=1))+++def arg(name, x):+ """A shortcut's argument as the act body carries it: `entity` as written (an id), true / false as booleans, a+ number as a number, anything else (an enum value) as written; the core checks every field against the schema."""+ if name == "entity":+ return x+ if x in ("true", "false"):+ return x == "true"+ try:+ return float(x)+ except ValueError:+ return x+++def main(a):+ turn = call("spec").get("protocol", "").startswith("eai-standard-turn") if a[:1] == ["wait"] else None+ if a == ["spec"]:+ show(call("spec"))+ elif a == ["status"]:+ show(call("status"))+ elif a == ["start"]:+ show(call("start", {}))+ elif a[:1] == ["wait"] and len(a) <= 2:+ if turn:+ while True:+ o = call("wait", {"timeout_s": 60})+ st = o.get("state") or {}+ if "error" in o or st.get("done") or st.get("your_turn"):+ break+ show(o)+ else:+ show(call("wait", {"dt": float(a[1]) if len(a) == 2 else 0.1}))+ elif a[:1] == ["observe"] and len(a) <= 2:+ show(call("observe", {"query": json.loads(a[1])} if len(a) == 2 else {}))+ elif a[:1] == ["act"] and len(a) == 2:+ show(call("act", json.loads(a[1])))+ elif a[:1] == ["ready"] and len(a) == 3:+ show(call("ready", {"why": a[1], "plan": a[2]}))+ elif a[:1] == ["say"] and len(a) == 2:+ show(call("say", {"text": a[1]}))+ elif a[:1] == ["team"] and len(a) <= 2:+ show(call("team", {"since": int(a[1]) if len(a) == 2 else 0}))+ elif a and a[0] in COMMANDS and len(a) == len(COMMANDS[a[0]]):+ kind, *names = COMMANDS[a[0]]+ show(call("act", {"type": kind, **{n: arg(n, x) for n, x in zip(names, a[1:])}}))+ else:+ sys.exit(__doc__)+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/grading.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/grading.pynew file mode 100644index 0000000000..f63442d2ca--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/grading.py@@ -0,0 +1,198 @@+"""The verifier (separate sandbox, no network, no simulator): reads what the sim wrote (/data/final.json,+/data/replay_check.json), checks the fresh-process replay agrees with the live match, applies the one validity rule+(technical failures void the trial; a player's own problems are a valid loss, among them a side that never started+in its start window or before the player sessions ended: reason no_show, no_show = 1, <seat>_no_show = 1, core 0.2.7;+and a single side whose session ended after the start and before the end of the match: reason abandoned, abandoned =+1; core 0.2.6) and the no-code audit of+direct play,+and writes reward.json = common fields + the sport's own fields (tests/sport_grade.py: evaluate(final) -> numbers).+The task's formats and official configurations come from tests/contract.json (generated from sport.toml).++Hidden official seeds (core 0.2.14, core/seeds.py): once the sport registers a hidden seed set (contract official+hidden_seeds: sha256, counts and commitments per cell = format x level), official_config needs the match seed to be+one of its cell: the commitment the sim recorded (final.json seed_proof; the replay must give the same one) must be in+the registered cell (hidden_seed = 1, hidden_seed_index = its position; else 0 and -1). A hidden seed is never written:+seed = -1 here and in every record. The public [official] seeds then no longer count as official.+Core 0.2.19: this holds over the sport's own official_config too (tests/sport_grade.py may replace the core's value+with a legacy per-format rule): with a registered set, official_config = 1 needs hidden_seed = 1 and the sport's+value 1, so the sport's rule can only lower it and a public-seed match is never official.+Continuous score (core 0.2.14, core/score.py): final.json continuous.by_side (the replay must agree) becomes+<seat>_continuous_score per seat and, for a single-side format, continuous_score; larger is better.++success: duel / team / multi -> the trial is valid (who won is in <seat>_won / <seat>_place);+ single against a scripted opponent -> valid and the seat's side won;+ single without an opponent (solo) -> valid, complete and the score reaches the success line."""+from __future__ import annotations++import importlib.util+import json+import os+import shutil+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+DATA = Path(os.environ.get("RCB_DATA", "/data"))+LOG = Path(os.environ.get("RCB_LOG", "/logs/verifier"))+COMPLETE = ("match_over", "ready_timeout", "clock", "abandoned", "no_show")+++def _load(name):+ p = HERE / f"{name}.py"+ if not p.exists():+ return None+ spec = importlib.util.spec_from_file_location(name, p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++try: # core/seeds.py; in a task, its copy next to this file (tests/seeds.py)+ from . import seeds as seedset+except ImportError:+ seedset = _load("seeds")+++def hidden_index(d, contract) -> int | None:+ """The match seed's position in its cell (format x level) of the sport's registered hidden official seed set+ (core 0.2.14, core/seeds.py): the commitment the sim recorded (final.json seed_proof; the seed and its salt are+ never written) must be in that cell's registered commitments. None if it is not one."""+ reg = (contract.get("official") or {}).get("hidden_seeds")+ proof = d.get("seed_proof") or {}+ if not reg or seedset is None:+ return None+ return seedset.index(contract.get("sport", ""), d.get("format") or "", (d.get("cfg") or {}).get("level"),+ proof.get("commitment"), reg)+++def official(d, contract) -> bool:+ """An official configuration: the seed (a registered hidden seed once the sport has a hidden set, else one of the+ public [official] seeds), the slowdown, the first player and the level."""+ off = contract.get("official", {})+ if ((contract.get("formats") or {}).get(d.get("format") or "") or {}).get("preview"):+ return False # a preview format ([formats.<f>] preview = true; core 0.2.21) is never official+ ok = True+ if off.get("hidden_seeds"):+ ok &= hidden_index(d, contract) is not None+ elif "seeds" in off:+ ok &= int(d.get("seed") or 0) in off["seeds"]+ if "slowdowns" in off:+ ok &= float(d.get("slowdown") or 0) in off["slowdowns"].get(d.get("play", "program"), [])+ if off.get("first_any"):+ ok &= d.get("first") in d["cfg"]["seats"] or d.get("first") in (d.get("sides") or {}).values()+ if "levels" in off and d["cfg"].get("level") is not None:+ ok &= int(d["cfg"]["level"]) in off["levels"]+ return bool(ok)+++def line_ok(score, line: dict) -> bool:+ if "score_at_least" in line:+ return score >= line["score_at_least"]+ if "score_at_most" in line:+ return score <= line["score_at_most"]+ return False+++def grade(d, r, contract, evaluate, audits=None):+ seats = d["cfg"]["seats"]+ side = d.get("sides") or {s: s for s in seats}+ cont = (d.get("continuous") or {}).get("by_side")+ replay = bool(d.get("deterministic") and r.get("state_sha") == d["state_sha"] and r.get("scores") == d["scores"]+ and r.get("winner") == d["match_winner"] and r.get("commands_sha") == d["commands_sha"]+ and r.get("source_sha") == d["source_sha"] and r.get("k") == d["steps"]+ and (cont is None or r.get("continuous") == cont)+ and (not d.get("seed_proof") or r.get("seed_commitment") == d["seed_proof"].get("commitment")))+ solo = bool(d.get("solo"))+ single = len(set(side.values())) == 1+ complete = d.get("reason") in COMPLETE and (single or d.get("match_winner") in side.values())+ errors = bool(d.get("errors") or any(d["meter_error"].values()) or any(d["proxy_error"].values()))+ valid = bool(d.get("valid_trial") and d.get("finalized") and replay and complete and not errors)+ direct = d.get("play") == "direct"+ audits = audits or {}+ bad = {s: bool(direct and d["player_modes"].get(s) == "model" and audits.get(s, (0, []))[1]) for s in seats}+ winner = d["match_winner"]+ if any(bad.values()): # a no-code violation loses the match (all of them: nobody wins)+ rest = sorted({side[s] for s in seats if not bad[s]})+ winner = rest[0] if len(rest) == 1 and not single else None+ fmt = (contract.get("formats") or {}).get(d.get("format") or "", {})+ if solo:+ score = d["scores"].get(side[seats[0]], 0)+ success = valid and d.get("reason") == "match_over" and not any(bad.values()) and \+ line_ok(score, fmt.get("success", {}))+ elif single:+ success = valid and winner == side[seats[0]]+ else:+ success = valid+ out = dict(success=int(success), valid_trial=int(valid), technical_failure=int(not valid), grader_error=0,+ missing_log=0, deterministic=int(replay), match_over=int(d.get("reason") == "match_over"),+ seed=int(d.get("seed") or 0), official_config=int(official(d, contract)),+ video_rendered=int(bool(d.get("video")) or (DATA / "replay.mp4").exists()), direct_play=int(direct),+ lowlevel_actions=int(d.get("action_level") == "low"), solo=int(solo),+ no_show=int(d.get("reason") == "no_show"), abandoned=int(d.get("reason") == "abandoned"))+ hidx = hidden_index(d, contract)+ out.update(hidden_seed=int(hidx is not None), hidden_seed_index=hidx if hidx is not None else -1)+ if cont is not None: # the continuous score (core 0.2.14): larger is better+ worst = float((contract.get("score") or {}).get("forfeit", 0.0))+ for s in seats:+ out[s + "_continuous_score"] = worst if bad[s] else float(cont.get(side[s], worst))+ if single:+ out["continuous_score"] = out[seats[0] + "_continuous_score"]+ ranking = d.get("ranking") or []+ for s in seats:+ out[s + "_won"] = int(valid and winner == side[s] and not bad[s])+ out[s + "_no_show"] = int(d.get("reason") == "no_show" and not (d.get("joined") or {}).get(s, True))+ if len(set(side.values())) > 2:+ out[s + "_place"] = ranking.index(side[s]) + 1 if valid and side[s] in ranking else 0+ out[s + "_transient_api_errors"] = int(d["transient_api_errors"].get(s, 0))+ out[s + "_unrecovered_api_errors"] = int(d["unrecovered_api_errors"].get(s, 0))+ if direct:+ out[s + "_nocode_tool_calls"] = int(audits.get(s, (0, []))[0])+ out[s + "_nocode_violations"] = len(audits.get(s, (0, []))[1])+ out[s + "_nocode_forfeit"] = int(bad[s])+ out.update(evaluate(d))+ if (contract.get("official") or {}).get("hidden_seeds"):+ # core 0.2.19: once the sport registered a hidden seed set (frozen), only a match on a registered hidden seed of+ # its cell is official, whatever the sport's own official_config says (its legacy public-seed rule); the+ # sport's rule (e.g. its slowdowns) can only lower the value+ out["official_config"] = int(out.get("official_config") == 1 and hidx is not None)+ return out+++def main():+ LOG.mkdir(parents=True, exist_ok=True)+ try:+ contract = json.loads((HERE / "contract.json").read_text())+ evaluate = _load("sport_grade").evaluate+ d, r = (json.loads((DATA / f).read_text()) for f in ("final.json", "replay_check.json"))+ audits = None+ if d.get("play") == "direct":+ nmod = _load("nocode_audit") # the players' no-code audit (players/nocode/)+ # calls the gateway blocked never reached the agent, so they are not judged (direct-native/1.1 rule)+ audits = {s: nmod.nocode_audit(DATA / f"think_calls_{s}.jsonl",+ skip_ids=nmod.gate_blocked_ids(DATA / f"direct_gate_{s}.jsonl"))+ for s in d["cfg"]["seats"]}+ (LOG / "nocode_audit.json").write_text(json.dumps({s: dict(tool_calls=a[0], violations=a[1][:50])+ for s, a in audits.items()}, indent=1))+ out = grade(d, r, contract, evaluate, audits)+ hs = (contract.get("official") or {}).get("hidden_seeds") or {}+ (LOG / "versions.json").write_text(json.dumps({+ "versions": d.get("versions"), "renderer": d.get("renderer"),+ "seed_set": {"sha256": hs.get("sha256"), "counts": hs.get("counts"), "index": hidden_index(d, contract)}+ if hs else None,+ "continuous_score": {k: (d.get("continuous") or {}).get(k) for k in ("name", "from", "higher_is_better")}+ if d.get("continuous") else None}))+ for f in ("final.json", "replay_check.json", "episode.jsonl", "replay.mp4"):+ if (DATA / f).exists():+ shutil.copy(DATA / f, LOG / f)+ except Exception as e: # noqa: BLE001+ print(type(e).__name__, str(e))+ out = dict(success=0, valid_trial=0, technical_failure=1, grader_error=1,+ missing_log=int(not (DATA / "final.json").exists()))+ assert all(isinstance(v, (int, float)) for v in out.values())+ (LOG / "reward.json").write_text(json.dumps(out))+ (LOG / "reward.txt").write_text(str(out["success"]) + "\n")+ print(out)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/http.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/http.pynew file mode 100644index 0000000000..1a24ac0309--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/http.py@@ -0,0 +1,199 @@+"""Contract ① (docs/framework_zh.md §4.1), the envelope: the seat-facing HTTP layer shared by both protocols: /<SEAT>/<endpoint>, the caller's address must be that seat's+container (SEAT_HOSTS=A=seat_a,B=seat_b; without it only localhost), at most 4 open requests and 20 per second per+seat, JSON bodies up to 64 KiB. A service maps endpoints to methods returning (status, body).++The budget (core 0.2.16) belongs to the authenticated seat: the seat a request names in its path, once the caller's+address is allowed to be that seat. A request for a seat its address may not be is refused (403) before it spends+anything, so a seat never spends another seat's budget. Before a request is read, an address may hold the budget of+every seat it may be (4 open connections and 20 per second per such seat); an address that may be no seat is refused.+Cores <= 0.2.15 charged a connection to the first seat its address may be: without SEAT_HOSTS every local seat shared+the first seat's budget (a team format's local seats got 429s). Every refusal for the budget is a bare 429 (no body),+which never reached the match: core/client.py retries it."""+from __future__ import annotations++import json+import socket+import sys+import threading+import time+import traceback+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import parse_qsl++from .sport import Refused, check_body++SLOTS, RATE = 4, 20 # per seat: open requests, requests per second+++def seat_allowed(seat, addr, hosts):+ if seat not in hosts:+ return addr in ("127.0.0.1", "::1")+ try:+ return addr in {a[4][0] for a in socket.getaddrinfo(hosts[seat], None)}+ except OSError:+ return False+++def make_server(service, seats, hosts, port=8000):+ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *a):+ pass++ def setup(self):+ super().setup()+ self.connection.settimeout(10)++ def send(self, code, value):+ raw = json.dumps(value, default=float).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True+ try:+ self.wfile.write(raw)+ except (BrokenPipeError, ConnectionResetError):+ pass++ def dispatch(self, post):+ path, _, self.qs = self.path.partition("?") # a GET may carry ?team_since=N (core 0.2.20)+ bits = path.strip("/").split("/")+ if len(bits) != 2 or bits[0] not in seats or not seat_allowed(bits[0], self.client_address[0], hosts):+ return self.send(403, {"error": "seat not authorized"})+ seat, ep = bits+ if not self.server.admit(seat): # the authenticated seat's own budget, never another seat's+ return self.too_many()+ try:+ self.handle_seat(seat, ep, post)+ finally:+ self.server.release(seat)++ def too_many(self):+ try: # read a small body first: closing on unread data may reset the reply+ n = int(self.headers.get("Content-Length", "0"))+ if 0 < n <= 65536:+ self.rfile.read(n)+ except (ValueError, OSError):+ pass+ self.send_response(429)+ self.send_header("Content-Length", "0")+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True++ def handle_seat(self, seat, ep, post):+ try: # the request itself: any problem is the caller's (400), never a failure+ body = {}+ if not post and self.qs: # GET parameters: small integers only (team_since, since)+ for key, val in parse_qsl(self.qs[:256], keep_blank_values=False)[:4]:+ if key in ("team_since", "since"):+ if not val.isdigit() or len(val) > 12:+ raise Refused(f"{key} must be a non-negative integer (a seq)")+ body[key] = int(val)+ if post:+ n = int(self.headers.get("Content-Length", "0"))+ if not 0 <= n <= 65536:+ raise Refused("request too large (at most 64 KiB)")+ body = json.loads(self.rfile.read(n) or b"{}")+ if not isinstance(body, dict):+ raise Refused("JSON object required")+ check_body(body)+ except Refused as exc:+ return self.send(exc.code, {"error": str(exc)})+ except Exception: # noqa: BLE001+ return self.send(400, {"error": "malformed request: a JSON object of at most 64 KiB required"})+ try:+ fn = service.routes(post).get(ep)+ code, out = (404, {"error": "unknown endpoint"}) if fn is None else fn(seat, body)+ except Refused as exc:+ code, out = exc.code, {"error": str(exc)}+ if exc.cause:+ print(f"refused {seat}/{ep}: {exc.cause}", file=sys.stderr, flush=True)+ except (ValueError, TypeError, KeyError, OverflowError) as exc:+ code, out = 400, {"error": "invalid request"}+ print(f"invalid request {seat}/{ep}: {type(exc).__name__}: {str(exc)[:200]}", file=sys.stderr,+ flush=True)+ except BlockingIOError as exc: # core/workers.py: our own text+ code, out = 429, {"error": str(exc)}+ except Exception as exc: # noqa: BLE001+ traceback.print_exc()+ service.failure(ep, exc)+ code, out = 500, {"error": "technical failure"} # the details stay in the logs (G9)+ self.send(code, service.public(out) if hasattr(service, "public") else out) # no hidden seed++ def do_GET(self):+ self.dispatch(False)++ def do_POST(self):+ self.dispatch(True)++ class Bounded(ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, *a, **kw):+ super().__init__(*a, **kw)+ self.lock = threading.Lock()+ self.slots = {s: threading.BoundedSemaphore(SLOTS) for s in seats}+ self.arrivals = {s: [] for s in seats}+ self.open = {} # address -> connections not yet closed+ self.recent = {} # address -> connection times in the last second++ def admit(self, seat):+ """A request of the authenticated seat: its own open requests and rate (in a handler thread)."""+ with self.lock:+ now = time.monotonic()+ self.arrivals[seat] = [t for t in self.arrivals[seat] if now - t < 1]+ if len(self.arrivals[seat]) >= RATE or not self.slots[seat].acquire(False):+ return False+ self.arrivals[seat].append(now)+ return True++ def release(self, seat):+ self.slots[seat].release()++ def process_request(self, request, addr):+ # before the request is read: the address may hold the budget of every seat it may be, no more+ n = sum(1 for s in seats if seat_allowed(s, addr[0], hosts))+ with self.lock:+ now = time.monotonic()+ recent = [t for t in self.recent.get(addr[0], ()) if now - t < 1]+ ok = n > 0 and len(recent) < RATE * n and self.open.get(addr[0], 0) < SLOTS * n+ if ok:+ self.recent[addr[0]] = recent + [now]+ self.open[addr[0]] = self.open.get(addr[0], 0) + 1+ elif recent:+ self.recent[addr[0]] = recent+ else:+ self.recent.pop(addr[0], None)+ if not ok:+ try:+ request.settimeout(.1)+ request.sendall(b"HTTP/1.1 429 Too Many Requests\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")+ except OSError:+ pass+ self.shutdown_request(request)+ return+ try:+ super().process_request(request, addr)+ except Exception:+ self.closed(addr[0])+ raise++ def closed(self, host):+ with self.lock:+ left = self.open.get(host, 0) - 1+ if left > 0:+ self.open[host] = left+ else:+ self.open.pop(host, None)++ def process_request_thread(self, request, addr):+ try:+ super().process_request_thread(request, addr)+ finally:+ self.closed(addr[0])++ return Bounded(("0.0.0.0", port), Handler)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/launch.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/launch.pynew file mode 100644index 0000000000..ff8a35575d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/launch.py@@ -0,0 +1,97 @@+"""Trusted launcher of a task's sim container: one metering proxy per seat (the unchanged think_proxy.py of players/+metering, copied by the generator to metering/think_proxy.py next to core/; seat i on port 18090 + i; model+credentials stay in this container) and the match service (core.serve).++A seat in player mode "unmetered" (PLAYER_MODE_<seat>, core 0.2.29) gets no proxy: its runner meters the model.++Per-seat settings of a seat's proxy (the runner sets them; the compose file passes them through):+ RO_SEAT_SELECT_<seat> = "VAR=SOURCE,..." VAR takes SOURCE's value (e.g. a second account's credential)+ RO_SEAT_ENV_<VAR>_<seat> = value a non-empty value replaces VAR (e.g. the route of OpenAI-style calls)+After the mapping a proxy keeps no RO_SEAT_SELECT_* / RO_SEAT_ENV_* and no other seat's per-seat variable (<VAR>_<other+seat> for every per-seat VAR, PLAYER_MODE_<other seat>): a seat's proxy never holds another seat's credentials. A seat+on route "chatgpt" (THINK_OPENAI_ROUTE: a ChatGPT subscription) keeps only the credentials given to it alone (non-empty+RO_SEAT_ENV_<VAR>_<seat>); every task-wide credential (e.g. the OpenRouter or Azure key) is dropped from its proxy.+A credential is a per-seat VAR that is not a THINK_* setting.+"""+import os+import subprocess+import sys+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SEATS = os.environ.get("RO_SEATS", "A,B").split(",")+DATA = os.environ.get("RCB_DATA", "/data")+PROXY = ROOT.parent / os.environ.get("RO_METER_PROXY", "metering/think_proxy.py")+++def seat_env(seat: str, env: dict, seats=None) -> dict:+ """The environment of `seat`'s metering proxy."""+ seats = seats or SEATS+ env = dict(env)+ env["THINK_CLIENT_HOST"] = "seat_" + seat.lower() if len(seats) > 1 else env.get("THINK_CLIENT_HOST", "player")+ env["THINK_USAGE_FILE"] = f"{DATA}/think_usage_{seat}.json"+ env["THINK_CALLS_FILE"] = f"{DATA}/think_calls_{seat}.jsonl"+ for pair in filter(None, env.get(f"RO_SEAT_SELECT_{seat}", "").split(",")):+ var, _, src = pair.partition("=")+ if var and src in env:+ env[var] = env[src]+ own = set() # the VARs given to this seat alone+ for key in [k for k in env if k.endswith("_" + seat) and k.startswith("RO_SEAT_ENV_")]:+ if env[key]:+ own.add(key[len("RO_SEAT_ENV_"):-len(seat) - 1])+ env[key[len("RO_SEAT_ENV_"):-len(seat) - 1]] = env[key]+ per_seat = {"PLAYER_MODE"} # every VAR set per seat (any seat's RO_SEAT_ENV_<VAR>_<s>)+ for s in seats:+ per_seat |= {k[len("RO_SEAT_ENV_"):-len(s) - 1] for k in env+ if k.startswith("RO_SEAT_ENV_") and k.endswith("_" + s) and len(k) > len("RO_SEAT_ENV_") + len(s) + 1}+ others = [s for s in seats if s != seat]+ for k in list(env):+ if k.startswith(("RO_SEAT_ENV_", "RO_SEAT_SELECT_")) or any(k == f"{v}_{o}" for o in others for v in per_seat):+ del env[k]+ if env.get("THINK_OPENAI_ROUTE", "").strip().lower() == "chatgpt": # a subscription seat: its own credentials only+ for k in per_seat - own:+ if not k.startswith("THINK_") and k != "PLAYER_MODE":+ env.pop(k, None)+ return env+++def seat_mode(seat: str, env=None) -> str:+ """The seat's player mode, as core.seats.Seat reads it."""+ env = os.environ if env is None else env+ return env.get(f"PLAYER_MODE_{seat}", env.get("RCB_PLAYER_MODE", "model"))+++def main():+ if len(sys.argv) > 1: # one seat's proxy+ seat = sys.argv[1]+ env = seat_env(seat, dict(os.environ))+ os.execve(sys.executable, [sys.executable, str(PROXY), str(18090 + SEATS.index(seat))], env)+ Path(DATA).mkdir(exist_ok=True)+ for s in SEATS:+ open(f"{DATA}/think_calls_{s}.jsonl", "a").close()+ procs = []+ try:+ metered = [s for s in SEATS if seat_mode(s) != "unmetered"]+ if PROXY.exists():+ for s in metered: # an unmetered seat (core 0.2.29) gets no proxy+ procs.append(subprocess.Popen([sys.executable, __file__, s]))+ elif metered:+ print(f"no metering proxy at {PROXY}: model seats cannot play", file=sys.stderr, flush=True)+ procs.append(subprocess.Popen([sys.executable, "-m", "core.serve"], cwd=ROOT.parent))+ while all(p.poll() is None for p in procs):+ time.sleep(.5)+ raise RuntimeError("a required service exited")+ finally:+ for p in procs:+ if p.poll() is None:+ p.terminate()+ for p in procs:+ try:+ p.wait(timeout=3)+ except subprocess.TimeoutExpired:+ p.kill()+++if __name__ == "__main__":+ main()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/local.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/local.pynew file mode 100644index 0000000000..76ed991488--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/local.py@@ -0,0 +1,244 @@+"""In-process matches of built-in players (no HTTP, no wall clock): what the checks (tools/check) use for the generic+tests, the fairness check and golden recordings. The players see what they would see over HTTP (core/client.py: the+whitelisted observation with the camera images), the actions go through the same action layer, and the episode is the+same episode.jsonl the live service writes, so `python -m core.episode` replays it in a fresh process.++ play(sport, cfg, players, data=None, render=True) -> {"scores", "winner", "decided_by", "ranking", "k", "digest", ...}+"""+from __future__ import annotations++import base64+import json+from pathlib import Path++from . import PROTOCOLS, VERSION+from . import score as score_mod+from . import spec as spec_mod+from .channel import TeamChannel+from .diaglog import Acts, jsonable, safe, view_steps+from .episode import Episode+from .observe import CameraWorker, filter_fields, players_scene+from .outcome import decide+from .service import own_hook, public_spec+from .sport import FINISHED, UNIT_OVER, Refused, parse_action++MAX_REFUSED = 50 # local play: a player whose actions keep being refused fails the match run++DEFAULT_CLOCK_S = 3600.0+++class Views:+ """The view a player gets: {"state": core fields + the whitelisted observation, "observation": images}."""++ def __init__(self, sport, cfg, m, decl, render: bool, plugin: str | None = None, channel=None):+ self.sport, self.cfg, self.m, self.render, self.plugin = sport, cfg, m, render, plugin+ self.channel = channel # the team channel (core/channel.py), as the live service runs it+ self.allowed = spec_mod.whitelist(decl)+ self.columns = int((decl.get("observation") or {}).get("columns", 2))+ self.cam = None+ self.leaks: list[str] = []+ self.own_images = own_hook(m, "camera_job") or not own_hook(m, "cameras")+ self.log = None # diagnostic rows (core 0.2.25): set by play() with an episode+ self.acts = Acts(cfg.seats)++ def view(self, seat, extra: dict, query=None) -> dict:+ obs, bad = filter_fields(self.m.observe(seat, query), self.allowed)+ self.leaks += bad+ if self.channel is not None and self.channel.enabled: # as Service.observation (core 0.2.21)+ msgs, top = self.channel.messages(seat, self.m.k, self.m.dt or 1.0) # the recent ones, never consumed+ obs["team_messages"], obs["team_seq"] = msgs, top+ if self.log is not None:+ for d in self.channel.deliver(seat, msgs, self.m.k):+ self.log("team_delivered", **d)+ out = {"state": {"seat": seat, **extra, **obs}, "observation": {}}+ job, meta = None, {}+ if self.render and self.own_images:+ job, meta = self.m.camera_job(seat)+ if job is not None:+ img = self.sport.worker_call(None, "render", job)+ out["observation"] = {"image_png_b64": base64.b64encode(img["png"]).decode(), **meta}+ elif self.render:+ cams = self.m.cameras(seat, query)+ if cams:+ if self.cam is None:+ scene = (players_scene(self.sport, self.plugin, self.cfg) if self.plugin else+ self.sport.scene(self.cfg))+ self.cam = CameraWorker(scene, self.cfg.renderer)+ job = cams+ img = self.cam.draw(self.m.render_state(), cams, self.columns)+ out["observation"] = {"image_png_b64": base64.b64encode(img["png"]).decode(), "tiles": img["tiles"]}+ if self.log is not None: # as the service's observe row+ obs_id = self.acts.new_obs(seat)+ self.log("observe", seat=seat, obs_id=obs_id, k=self.m.k, view_steps=view_steps(meta, job, self.m.k),+ query=query)+ return out+++def _header(ep, sport, cfg):+ if ep is not None:+ ep.write("header", cfg=cfg.to_json(), sport=sport.name, revision=sport.revision, protocol=sport.protocol,+ source_sha=None, versions={"core": VERSION, "sport": sport.revision}, local=True)+++def seat_spec(sport, cfg, seat, m=None, plugin=None) -> dict:+ """What GET /spec tells `seat` (without the protocol's timing part)."""+ decl = spec_mod.load(plugin) if plugin else {}+ m = m or sport.build(cfg)+ return {"seat": seat, "side": cfg.side_of(seat), "protocol": PROTOCOLS[sport.protocol], "revision": sport.revision,+ "action_level": cfg.action_level, "play": cfg.play, "format": cfg.format,+ **public_spec(sport, cfg, seat, m, sport.action_layer(cfg.action_level), decl)}+++def make_players(sport, cfg, names: dict, plugin=None, seed=None) -> dict:+ """seat -> built-in player, by name (Sport.players())."""+ table = sport.players()+ return {s: table[n](seat_spec(sport, cfg, s, plugin=plugin), s, cfg.seed if seed is None else seed)+ for s, n in names.items()}+++def play(sport, cfg, players: dict, data: Path | str | None = None, render: bool = True, plugin: str | None = None,+ max_actions: int = 10000, max_steps: int = 10 ** 7, every: int = 5) -> dict:+ """Play one match of built-in players (seat -> player). Turn protocol: the sport's to_move() decides who acts;+ realtime: every `every` control steps each seat may act; reviews end at once. A declared reaction delay D+ (sport.toml [timing] reaction_delay_steps, core 0.2.18; read when `plugin` is given) holds an act until D steps+ after the observation it answers, where it is lowered and applied (core/realtime.py); a seat with an act held+ does not observe."""+ decl = spec_mod.load(plugin) if plugin else {}+ m = sport.build(cfg)+ layer = sport.action_layer(cfg.action_level)+ ep = None+ if data is not None:+ Path(data).mkdir(parents=True, exist_ok=True)+ (Path(data) / "episode.jsonl").unlink(missing_ok=True)+ ep = Episode(Path(data) / "episode.jsonl")+ _header(ep, sport, cfg)+ channel = TeamChannel(cfg, decl.get("team_channel"))+ views = Views(sport, cfg, m, decl, render, plugin, channel)+ clocks = {s: DEFAULT_CLOCK_S for s in cfg.seats}+ refused = {s: 0 for s in cfg.seats}+ log = (lambda ev, **row: ep.write(ev, **row)) if ep is not None else (lambda ev, **row: None)+ dlog = safe(log) # diagnostic rows (core/diaglog.py, core 0.2.25)+ if ep is not None:+ views.log = dlog+ acts = views.acts+ refused: dict = {}+ if sport.protocol == "turn":+ n = 0+ while m.phase().state != FINISHED and n < max_actions:+ seat = m.to_move()+ v = views.view(seat, {"phase": "play", "turn": "you", "your_turn": True, "done": False,+ "clock_left_s": clocks[seat]})+ body = players[seat].act(v)+ try:+ cmd = parse_action(layer, seat, body, m, {"clock_left_s": dict(clocks)})+ except Refused: # an invalid request is refused (HTTP 400 in a real match), not a crash+ refused[seat] = refused.get(seat, 0) + 1+ if refused[seat] > MAX_REFUSED:+ raise RuntimeError(f"seat {seat}: more than {MAX_REFUSED} refused actions in local play")+ continue+ low, _info = layer.lower(seat, cmd, None, m)+ act_id = acts.new(seat)+ dlog("act_received", seat=seat, k=m.k, act_id=act_id, obs_id_last=acts.last_obs.get(seat), decision=cmd)+ log("cmd", k=m.k, seat=seat, cmd=low)+ k_cmd = m.k+ applied = m.apply(seat, low) or {}+ dlog("effect", seat=seat, act_id=act_id, k=k_cmd, info=jsonable(applied),+ **({"rejected": True} if "rejected" in applied else {}))+ n += 1+ else:+ plan = {s: sport.worker_init("plan", s, cfg) for s in cfg.seats} if getattr(layer, "worker", None) else {}+ delay = int(getattr(layer, "delay_steps", 0) or 0)+ react = spec_mod.reaction_delay(decl)+ scheduled: list = []+ held: dict = {} # seat -> (effect step, cmd): the declared reaction delay++ def effect(seat, cmd, act_id=None):+ job = layer.snapshot(seat, cmd, m, m.k)+ prepared = None+ if job is not None:+ prepared = (sport.worker_call(plan[seat], "plan", job) if plan else layer.prepare(job))+ low, info = layer.lower(seat, cmd, prepared, m)+ if delay:+ scheduled.append((m.k + delay, seat, low, act_id))+ else:+ apply(seat, low, act_id)++ def apply(seat, low, act_id, count=True):+ log("cmd", k=m.k, seat=seat, cmd=low)+ rej = "rejected" in (m.apply(seat, low) or {})+ if rej and count:+ refused[seat] = refused.get(seat, 0) + 1+ if act_id is not None:+ dlog("effect", seat=seat, act_id=act_id, k=m.k, **({"rejected": True} if rej else {}))++ def say(seat, v):+ """a built-in player's team-channel message (optional message(view) -> text | None; core 0.2.21), sent+ under the channel's limits as POST /<seat>/say would be (a refused message is dropped)"""+ f = getattr(players[seat], "message", None)+ text = f(v) if f is not None and channel.enabled else None+ if text and channel.say(seat, text, m.k, m.dt or 1.0)[0] == 200:+ log("team", seat=seat, k=m.k, seq=channel.seq.get(cfg.side_of(seat)), text=text)++ while m.phase().state != FINISHED and m.k < max_steps:+ if m.phase().state == UNIT_OVER:+ for x in scheduled:+ dlog("act_dropped", seat=x[1], act_id=x[3], k=m.k, why="unit_over")+ for seat, x in held.items():+ dlog("act_dropped", seat=seat, act_id=x[2], k=m.k, why="unit_over")+ scheduled.clear()+ held.clear()+ log("resume", k=m.k)+ m.resume()+ tick = getattr(layer, "tick", None) # a layer's per-step command (core/realtime.py apply_pending)+ if tick is not None:+ for seat in cfg.seats:+ low = tick(seat, m)+ if low is not None:+ log("cmd", k=m.k, seat=seat, cmd=low)+ if "rejected" in (m.apply(seat, low) or {}):+ refused[seat] = refused.get(seat, 0) + 1+ for item in [x for x in scheduled if x[0] <= m.k]:+ scheduled.remove(item)+ apply(item[1], item[2], item[3], count=False)+ for seat in [s for s in cfg.seats if s in held and held[s][0] <= m.k]:+ _k, cmd, act_id = held.pop(seat)+ effect(seat, cmd, act_id)+ if m.k % every == 0:+ for seat in cfg.seats:+ if seat in held: # one act in flight+ continue+ v = views.view(seat, {"phase": "running", "world": "running", "step": m.k,+ "t_sim": m.k * m.dt, "done": False})+ body = players[seat].act(v)+ say(seat, v)+ if body is None:+ continue+ try:+ cmd = parse_action(layer, seat, body, m, {})+ except Refused: # refused as in a real match (HTTP 400): the world goes on+ refused[seat] = refused.get(seat, 0) + 1+ continue+ act_id = acts.new(seat)+ dlog("act_received", seat=seat, k=m.k, act_id=act_id, obs_id_last=acts.last_obs.get(seat),+ seen=m.k, entity=(cmd.get("entity") if isinstance(cmd, dict) else None), decision=cmd)+ if react:+ held[seat] = (m.k + react, cmd, act_id)+ else:+ effect(seat, cmd, act_id)+ events = m.step()+ if events:+ dlog("event", k=m.k, events=jsonable(events))+ for x in scheduled: # never took effect: the match ended first+ dlog("act_dropped", seat=x[1], act_id=x[3], k=m.k, why="match_over")+ for seat, x in held.items():+ dlog("act_dropped", seat=seat, act_id=x[2], k=m.k, why="match_over")+ finished = m.phase().state == FINISHED+ log("end", k=m.k, reason="match_over" if finished else "unfinished")+ out = decide(m, None, None, cfg.side_list(), cfg.side_of)+ res = {"scores": m.scores(), "winner": out.winner, "decided_by": out.decided_by, "ranking": out.ranking,+ "solo": out.solo, "k": m.k, "digest": m.state_digest(), "finished": finished,+ "observation_leaks": sorted(set(views.leaks)), "rejected": refused, "final_fields": m.final_fields(),+ "continuous": score_mod.compute(m, decl, cfg.side_list())}+ if data is not None:+ (Path(data) / "local_result.json").write_text(json.dumps(res, default=float))+ return resdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/api_errors.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/api_errors.pynew file mode 100644index 0000000000..e9bd733ddc--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/api_errors.py@@ -0,0 +1,132 @@+"""Model-API errors of one seat, classified for the trial's validity (docs/EAI_STANDARD_REALTIME_1_0.md, "Validity").++The metering proxy (think_proxy.py) logs every request of a seat to its think_calls file (think_calls.jsonl, or+think_calls_<seat>.jsonl in a duel) and counts failed model calls and in-proxy 429 retries in the usage file. A model-API+error is a model call that did not complete successfully (an HTTP error such as 429 or 5xx, a stream error, a broken+connection) or one 429 retry inside the proxy. Each error is+ * transient when a later model call of the same seat completed successfully (the harness retried and got past it);+ * unrecovered when no model call of that seat completed successfully after it (the agent stopped, or the session+ ended, because of the model API, e.g. an account rate limit it could not get past).+A seat's model API failed the trial (`api_failure`, the trial's proxy_error) only if it had an unrecovered error or more+than MAX_TRANSIENT_API_ERRORS transient errors in the match. Transient errors below the limit are only counted and+reported. Azure deployment switches (azure_failovers) are not errors: the request completed on another replica.++The same file is copied into every Olympiad task's sim (scripts/olympiad/generate.py) and used by+scripts/olympiad/regrade_transient.py. Standard library only.+"""+from __future__ import annotations++import json+import os+import threading++MAX_TRANSIENT_API_ERRORS = 5+++def calls_file_for(usage_file: str) -> str:+ """The think_calls file the proxy writes next to `usage_file` (think_proxy.py's own rule)."""+ base = os.path.basename(usage_file)+ if "think_usage" in base:+ return usage_file.replace("think_usage", "think_calls").rsplit(".json", 1)[0] + ".jsonl"+ return os.path.join(os.path.dirname(usage_file) or ".", "think_calls.jsonl")+++class SeatApiErrors:+ """Incremental classifier of one seat's think_calls records (reads only the lines added since the last call)."""++ def __init__(self, calls_file: str | None = None):+ self.calls_file = calls_file+ self.lock = threading.Lock()+ self.reset()++ def reset(self) -> None:+ self.offset = 0+ self.error_times: list[float] = [] # when each error happened (a failed call's end, a retry's time)+ self.last_ok = None # end time of the latest successfully completed model call+ self.logged_failed = 0 # failed model calls in the log+ self.logged_retries = 0 # in-proxy 429 retries in the log+ self.model_calls = 0++ def add(self, rec) -> None:+ if not isinstance(rec, dict) or not rec.get("model_call"):+ return+ self.model_calls += 1+ end = _num(rec.get("t1"), _num(rec.get("t0"), 0.0))+ retries = rec.get("retries") if isinstance(rec.get("retries"), list) else []+ for r in retries:+ self.error_times.append(_num(r.get("at") if isinstance(r, dict) else None, end))+ self.logged_retries += len(retries)+ if rec.get("status") == 200 and rec.get("completed") is True:+ self.last_ok = end if self.last_ok is None else max(self.last_ok, end)+ else:+ self.logged_failed += 1+ self.error_times.append(end)++ def read(self) -> None:+ if not self.calls_file:+ return+ try:+ with open(self.calls_file, "rb") as f:+ f.seek(0, os.SEEK_END)+ if f.tell() < self.offset: # the file was replaced: start again+ self.reset()+ f.seek(self.offset)+ data = f.read()+ except OSError:+ return+ end = data.rfind(b"\n")+ if end < 0:+ return+ self.offset += end + 1 # only complete lines; a line being written waits+ for line in data[:end].splitlines():+ if line.strip():+ try:+ self.add(json.loads(line))+ except ValueError:+ pass # not a record (think_proxy.py writes whole lines)++ def summary(self, usage: dict | None = None) -> dict:+ transient = sum(1 for t in self.error_times if self.last_ok is not None and self.last_ok > t)+ unrecovered = len(self.error_times) - transient+ missing = 0+ if isinstance(usage, dict): # counted by the proxy but not (yet) in the log: not recovered+ missing = (max(0, int(usage.get("failed_model_calls", 0) or 0) - self.logged_failed)+ + max(0, int(usage.get("rate_limit_retries", 0) or 0) - self.logged_retries))+ unrecovered += missing+ return {"transient_api_errors": transient, "unrecovered_api_errors": unrecovered,+ "api_failure": bool(unrecovered > 0 or transient > MAX_TRANSIENT_API_ERRORS),+ "model_calls_logged": self.model_calls, "unlogged_api_errors": missing}+++def _num(v, default):+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else default+++def classify_calls(records, usage: dict | None = None) -> dict:+ """Classify a list of think_calls records (dicts). Returns transient_api_errors, unrecovered_api_errors and+ api_failure (unrecovered > 0 or transient > MAX_TRANSIENT_API_ERRORS)."""+ s = SeatApiErrors()+ for rec in records:+ s.add(rec)+ return s.summary(usage)+++def classify_file(calls_file: str, usage: dict | None = None) -> dict:+ s = SeatApiErrors(calls_file)+ s.read()+ return s.summary(usage)+++_SEATS: dict[str, SeatApiErrors] = {}+_SEATS_LOCK = threading.Lock()+++def seat_api_errors(usage_file: str, usage: dict | None = None) -> dict:+ """The classification of the seat metered in `usage_file` (its think_calls file read incrementally), for a server's+ final record. `usage`: that seat's usage counters, already read."""+ path = calls_file_for(usage_file)+ with _SEATS_LOCK:+ s = _SEATS.setdefault(path, SeatApiErrors(path))+ with s.lock:+ s.read()+ return s.summary(usage)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/think_clock.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/think_clock.pynew file mode 100644index 0000000000..a80909054a--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/metering/think_clock.py@@ -0,0 +1,114 @@+"""Wallclock model-turn gate. Oracle exemption must be explicitly enabled by the runner."""+from __future__ import annotations+import json+import os+import threading+import time++USAGE_FILE = os.environ.get("THINK_USAGE_FILE", "/data/think_usage.json")+++class MeterError(RuntimeError):+ pass+++def read_usage(path=USAGE_FILE):+ try:+ with open(path) as f:+ value = json.load(f)+ return value if isinstance(value, dict) else {}+ except (OSError, ValueError):+ return {}+++class ThinkClock:+ def __init__(self, seconds_per_ktok=0.0, usage_file=USAGE_FILE, **kwargs):+ self.usage_file = usage_file+ self.mode = kwargs.get("mode") or os.environ.get("RCB_PLAYER_MODE", "model")+ self.min_started_at = 0.0+ if self.mode not in ("model", "oracle"):+ raise ValueError("RCB_PLAYER_MODE must be model or oracle")+ act_rule = os.environ.get("RCB_ACT_RULE", "per_response")+ if act_rule not in ("per_response", "program"):+ raise ValueError("RCB_ACT_RULE must be per_response or program")+ self.rule = "explicit_oracle" if self.mode == "oracle" else (+ "program" if act_rule == "program" else "completed_act_calls")+ self._calls_at_decision = 0+ self._epoch = None+ self._last = {}+ self.lock = threading.Lock()++ def check_ready(self):+ if self.mode == "oracle":+ return {}+ u = read_usage(self.usage_file)+ counters = ("model_calls_completed", "act_calls_completed", "requests", "in_flight")+ if (not isinstance(u.get("epoch"), str) or not u["epoch"]+ or any(type(u.get(k)) is not int or u[k] < 0 for k in counters)+ or u["requests"] < 1 or u["act_calls_completed"] > u["model_calls_completed"]+ or u["model_calls_completed"] > u["requests"]):+ raise MeterError("model meter is missing, invalid, or has not received a model request")+ if self._epoch is not None and u["epoch"] != self._epoch:+ raise MeterError("model meter restarted during this match")+ self._epoch = u["epoch"]+ if u["act_calls_completed"] < self._calls_at_decision:+ raise MeterError("model meter counters moved backwards during this match")+ return u++ def settle(self, max_wait_s=2.0):+ """Drain the response carrying start/ready before discarding its act credits."""+ if self.mode == "oracle" or self.rule == "program":+ return # program play: no per-response act credits to discard+ deadline = time.monotonic() + max_wait_s+ while self.check_ready()["in_flight"]:+ if time.monotonic() >= deadline:+ raise MeterError("model response did not settle before the match resumed")+ time.sleep(.01)++ def rebase(self):+ """Discard all pre-start/review act credits. Caller first settles model traffic."""+ with self.lock:+ if self.mode == "oracle":+ return+ u = self.check_ready()+ if u["in_flight"]:+ raise MeterError("cannot rebase the model meter while responses are in flight")+ self._calls_at_decision = u["act_calls_completed"]+ self._last = {}++ def last_call(self):+ return dict(self._last)++ def decided_by_model(self):+ with self.lock:+ if self.mode == "oracle":+ self._last = {"oracle": True}+ return True+ if self.rule == "program":+ # Program play: the agent's own program may act; a live, metered model session is still required.+ u = self.check_ready()+ self._last = {"program": True, "act_calls_completed": u["act_calls_completed"],+ "model_calls_completed": u["model_calls_completed"], "epoch": u["epoch"]}+ return True+ deadline = time.monotonic() + float(os.environ.get("WALLCLOCK_RULE_WAIT_S", "1"))+ while True:+ u = self.check_ready()+ done = u["act_calls_completed"]+ if done > self._calls_at_decision and u.get("last_act_started_at", 0) >= self.min_started_at:+ self._calls_at_decision = done+ self._last = {"act_calls_completed": done, "model_calls_completed": u["model_calls_completed"],+ "response_seq": u.get("last_act_response_seq"),+ "epoch": u["epoch"], "last_completed_at": u.get("last_act_call_at"),+ "request_started_at": u.get("last_act_started_at")}+ return True+ if not u["in_flight"] or time.monotonic() >= deadline:+ return False+ time.sleep(.01)++ def begin_segment(self, started_at):+ """Discard frozen requests, including responses still in flight at the barrier."""+ with self.lock:+ self.min_started_at = started_at+ if self.mode != "oracle":+ self._calls_at_decision = self.check_ready()["act_calls_completed"]+ self._last = {}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/observe.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/observe.pynew file mode 100644index 0000000000..94b46fc9b3--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/observe.py@@ -0,0 +1,154 @@+"""Observations (sport rule 1, docs/framework_zh.md §9): what a seat gets is the camera images, its own body and the+referee's information, and nothing else. The sport declares the fields of Match.observe() in sport.toml+([observation] fields); a field outside that whitelist is never delivered and is a technical error of the match.++The camera images: Match.cameras(seat, query) returns camera definitions, the task's renderer (renderers/, chosen by+the task parameter `renderer`) draws them from the sport's scene and Match.render_state(), and the core lays the+images out as tiles of one PNG (left to right, `columns` per row), described in the reply (`tiles`).++Reply images (core 0.2.8): Match.reply_views(seat, cmd, info) right after an action -> reply_job() snapshots the+frames under the lock -> CameraWorker.draw_job() draws them off the lock (the same renderer, scene and worker as the+observation) -> one PNG of tiles, each tile also naming its frame (`frame`, `label`) when there are several.++The scene of the players' images (core 0.2.9, renderer rule 6): Sport.scene(cfg), or the presentation scene the sport+declares for its players (sports/<sport>/presentation/presentation.toml `players`, bundled into the simulator by the+generator; renderers/presentation.players_scene): the same kinematics, finer visual meshes. Any other presentation+scene is refused (spectators only)."""+from __future__ import annotations++import copy+import struct+import zlib+from pathlib import Path++import numpy as np+++class WhitelistError(Exception):+ pass+++def filter_fields(obs: dict, allowed: set[str] | None) -> tuple[dict, list[str]]:+ """(the whitelisted part of obs, the names that were not allowed)."""+ if allowed is None:+ return obs, []+ bad = sorted(k for k in obs if k not in allowed)+ return {k: v for k, v in obs.items() if k in allowed}, bad+++def png(img: np.ndarray) -> bytes:+ """A minimal RGB8 PNG encoder (no imaging library needed in the sim)."""+ img = np.ascontiguousarray(img, dtype=np.uint8)+ h, w = img.shape[:2]+ raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))++ def chunk(tag, data):+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)++ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))+ + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))+++def reply_job(m, spec: dict | None, columns: int) -> dict | None:+ """Under the lock: Match.reply_views()'s answer -> a self-contained draw job (deep copies: the match may move on+ while the job is drawn off the lock). A frame without a state gets render_state() now."""+ if not spec or not spec.get("frames"):+ return None+ order = spec.get("order", "frame")+ if order not in ("frame", "camera"):+ raise ValueError(f"reply_views: order must be 'frame' or 'camera', not {order!r}")+ now = None+ frames = []+ for f in spec["frames"]:+ st = f.get("state")+ if st is None:+ now = m.render_state() if now is None else now+ st = now+ cams = list(f.get("cameras") or [])+ if not cams:+ raise ValueError("reply_views: every frame needs at least one camera")+ frames.append({"state": st, "cams": cams, "label": f.get("label")})+ return copy.deepcopy({"frames": frames, "order": order, "columns": int(spec.get("columns") or columns),+ "note": spec.get("note")})+++def compose(images: list[np.ndarray], names: list[str], columns: int = 2) -> tuple[np.ndarray, list[dict]]:+ """Tiles left to right, `columns` per row, each at its own size; -> (sheet, [{camera, x, y, width, height}])."""+ rows = [list(range(i, min(i + columns, len(images)))) for i in range(0, len(images), columns)]+ widths = [sum(images[j].shape[1] for j in r) for r in rows]+ heights = [max(images[j].shape[0] for j in r) for r in rows]+ sheet = np.zeros((sum(heights), max(widths), 3), np.uint8)+ tiles, y = [], 0+ for r, hgt in zip(rows, heights):+ x = 0+ for j in r:+ h, w = images[j].shape[:2]+ sheet[y:y + h, x:x + w] = images[j][..., :3]+ tiles.append({"camera": names[j], "x": x, "y": y, "width": w, "height": h})+ x += w+ y += hgt+ return sheet, tiles+++def players_scene(sport, plugin: str, cfg):+ """The scene of the players' images: the sport's presentation scene when it declares `players`, else+ Sport.scene(cfg)."""+ scene = sport.scene(cfg)+ d = Path(plugin).resolve().parent+ if not (d / "presentation" / "presentation.toml").is_file():+ return scene+ from renderers import presentation+ return presentation.players_scene(d, scene)+++class CameraWorker:+ """Draws a seat's camera definitions with the task's renderer (in-process or inside a render worker process)."""++ def __init__(self, scene, renderer_name: str | None):+ import renderers+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):+ raise ValueError("the players' images are drawn from the match scene (Sport.scene) or the presentation "+ "scene the sport declares for them; any other presentation scene is for spectators only "+ "(renderer rule 6)")+ self.name = renderer_name or renderers.DEFAULT+ self.renderer = renderers.load(self.name)(scene)++ def draw(self, state: dict, cams: list[dict], columns: int = 2) -> dict:+ from renderers.base import CameraDef+ defs = [CameraDef.from_dict(c) for c in cams]+ images = self.renderer.render(state, defs)+ sheet, tiles = compose(images, [c.name for c in defs], columns)+ return {"png": png(sheet), "tiles": tiles, "renderer": self.name}++ def draw_frames(self, job: dict) -> dict:+ """A reply job (reply_job()): every frame's cameras drawn from that frame's state, laid out frame after+ frame or camera after camera; a tile names its camera, and its frame (index, label) when there are several."""+ from renderers.base import CameraDef+ frames = job["frames"]+ drawn = [] # per frame: [(name, image)]+ for f in frames:+ defs = [CameraDef.from_dict(c) for c in f["cams"]]+ drawn.append(list(zip([c.name for c in defs], self.renderer.render(f["state"], defs))))+ cells = [] # (frame index, camera name, image)+ if job.get("order") == "camera":+ for j in range(max(len(d) for d in drawn)):+ cells += [(i, d[j][0], d[j][1]) for i, d in enumerate(drawn) if j < len(d)]+ else:+ cells = [(i, name, img) for i, d in enumerate(drawn) for name, img in d]+ sheet, tiles = compose([c[2] for c in cells], [c[1] for c in cells], int(job.get("columns", 2)))+ many = len(frames) > 1+ for t, (i, _, _) in zip(tiles, cells):+ if many:+ t["frame"] = i+ if frames[i].get("label"):+ t["label"] = frames[i]["label"]+ out = {"png": png(sheet), "tiles": tiles, "renderer": self.name}+ if job.get("note"):+ out["note"] = job["note"]+ return out++ def draw_job(self, job: dict) -> dict:+ """Any job of the core's camera worker: a reply job (frames) or an observation (state + cameras)."""+ if "frames" in job:+ return self.draw_frames(job)+ return self.draw(job["state"], job["cams"], job.get("columns", 2))diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/outcome.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/outcome.pynew file mode 100644index 0000000000..11916961f2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/outcome.py@@ -0,0 +1,50 @@+"""The no-draw decision chain (docs/framework_zh.md §5): a forfeit (a core decision: review or clock time, abandonment,+or a side that never started, "no_show"; sides that retired before it rank last, the last to retire first), then the+sport's tiebreaks in order (rulebook result -> rulebook tiebreak -> capped extra play -> last resort; the last one must+decide). A match with more than two sides is decided by the sport's classification (Match.ranking, best first). A solo+match (single format without an opponent: tiebreaks() == []) has no winner; its result is the score against the+success line. A match that did not finish has no winner."""+from __future__ import annotations++from dataclasses import dataclass, field++from .sport import FINISHED+++@dataclass+class Outcome:+ winner: str | None+ decided_by: str+ scores: dict+ ranking: list = field(default_factory=list)+ solo: bool = False+++def decide(match, forfeit_seat: str | None = None, why: str | None = None, sides=("A", "B"),+ side_of=lambda s: s, retired=()) -> Outcome:+ scores = match.scores()+ sides = list(sides)+ rules = match.tiebreaks()+ solo = len(sides) == 1 and not rules+ if forfeit_seat is not None:+ lost = side_of(forfeit_seat)+ others = [s for s in sides if s != lost and s not in retired]+ if len(others) == 1:+ return Outcome(others[0], f"forfeit:{why}", scores, others + [lost] + list(reversed(retired)))+ if not others and len(sides) == 1: # a single player who forfeits loses (to the line or the opponent)+ return Outcome(None, f"forfeit:{why}", scores, [], solo)+ if match.phase().state != FINISHED:+ return Outcome(None, "unfinished", scores, [], solo)+ if solo:+ return Outcome(None, "score", scores, list(sides), True)+ if len(sides) > 2:+ ranking = list(match.ranking() or [])+ if sorted(ranking) != sorted(sides):+ raise RuntimeError("a match of more than two sides must rank every side (Match.ranking)")+ return Outcome(ranking[0], "ranking", scores, ranking)+ for name, rule in rules:+ w = rule(match)+ if w is not None:+ rest = [s for s in sides if s != w]+ return Outcome(w, name, scores, [w] + rest)+ raise RuntimeError("a finished match must be decided by its last tiebreak (no draws)")diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/realtime.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/realtime.pynew file mode 100644index 0000000000..af44b36845--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/realtime.py@@ -0,0 +1,462 @@+"""Protocol eai-standard-realtime/1.0: a continuous world paced at slowdown S (one control step every dt x S wall+seconds), frozen at every unit end for the reviews of the seats the referee names (Phase.review).++Phases: prepare (until every seat sent start/ready; after the first, START_TIMEOUT_S: a side that has not started by+then loses, "no_show"; if none started, the match does not count; a single side has START_TIMEOUT_S from the service+start, else it loses) -> running -> review (each seat+in Phase.review sends ready WHY PLAN within READY_TIMEOUT_S, else its side loses, or with more than two sides retires+while the others go on) -> running ... -> over. The collect (every player session has ended) before the end: before+the start a side that has not started loses at once ("no_show", core 0.2.7; if no side started, "collected"); a single+side whose match has started loses ("abandoned", a valid loss, core 0.2.6); otherwise the match ends "collected"+(unfinished, not a valid trial).+Acts: one per (seat, entity) in flight (429); program play needs a live metered session, per-response play a fresh+completed model response (think_clock.py); the high action layer prepares off the world lock (in the seat's plan+worker) and is lowered at the next control-step boundary, where the whole batch of ready acts takes effect together,+or `delay_steps` later (the effect step is what the episode logs). Declared reaction delay (core 0.2.18): a sport+may declare D = sport.toml [timing] reaction_delay_steps; an act then takes effect (and is lowered) at step+max(the next control-step boundary, s + D), s = the step of the latest world state the service sent to the seat before+the act arrived (the `now` of any reply: observe, act, wait, status, ready), the same D for every seat, so that a+program that answers within D steps always gets exactly D, whatever the machine's load; a slower one gets its own+latency as before. Not declared: D = 0, the rule above unchanged. Observations may carry a query (observation+parameters, e.g. which camera) that the sport validates. Reply images (core 0.2.8): an act that takes effect at once+gets the images of its result (Match.reply_views), snapshotted at the effect step under the lock and drawn off the+lock after the act's timing is taken (`wall_s_after_request` excludes it; `render_wall_s` reports it), like an+observation; the world runs on meanwhile.+"""+from __future__ import annotations++import base64+import json+import math+import os+import time++import numpy as np++from . import spec as spec_mod+from .diaglog import jsonable, view_steps+from .episode import reaction_report+from .service import Service+from .sport import FINISHED, UNIT_OVER, Refused, parse_action+++def query_of(body) -> dict | None:+ q = (body or {}).get("query")+ if q is None:+ return None+ if not isinstance(q, dict) or len(json.dumps(q)) > 4096:+ raise Refused("query must be a JSON object of at most 4 KiB")+ return q+++class RealtimeService(Service):+ protocol = "realtime"+ protocol_id = "eai-standard-realtime/1.0"++ def __init__(self, *a, **kw):+ super().__init__(*a, **kw)+ self.slowdown = float(self.cfg.slowdown or 20)+ if not np.isfinite(self.slowdown) or self.slowdown <= 0:+ raise ValueError("invalid slowdown")+ self.period = self.m.dt * self.slowdown+ self.ready_deadline = self.resume_at = self.anchor = self.segment_start = None+ if len(self.cfg.side_list()) == 1: # nobody to wait for: the start window opens now+ self.ready_deadline = time.monotonic() + self.start_window()+ self.pending: dict = {} # (seat, entity) -> act waiting for the next boundary+ self.scheduled: list = [] # [effect_k, seat, low] lowered acts with a delayed effect+ self.delay = int(getattr(self.layer, "delay_steps", 0) or 0)+ self.react = spec_mod.reaction_delay(self.decl) # declared reaction delay D (core 0.2.18), 0 = none+ self.seen: dict = {} # seat -> step of the latest world state sent to it+ self.lates, self.run_steps, self.run_wall = [], 0, 0.0+ for st in self.seats.values():+ st.stats.update(attempts=0, applied=0, refused=0, refused_invalid=0, dropped=0, observations=0, plan_s=[],+ act_s=[], obs_age_s=[])++ def routes(self, post):+ if post:+ return {"start": self.ready, "ready": self.ready, "act": self.act, "wait": self.wait,+ "observe": self.observe, "say": self.say, "team": self.team}+ return {"spec": self.spec, "status": self.status, "observe": self.observe, "team": self.team}++ def spec_core(self):+ return {"timing": {"slowdown": self.slowdown, "control_dt": self.m.dt, "period_s": self.period,+ "policy": "report_only", "effect_delay_steps": self.delay,+ "reaction_delay_steps": self.react},+ "start": self.start_rule(),+ "decision_rule": ("program play: your own program may observe and act without a new model response; "+ "one act per seat in flight" if os.environ.get("RCB_ACT_RULE") == "program" else+ "one fresh completed model response per act, after both players resume")}++ def start_window(self) -> float:+ return float(os.environ.get("START_TIMEOUT_S") or os.environ.get("READY_TIMEOUT_S", "60"))++ # ------------------------------------------------------------------ replies+ def state(self, seat, query=None, since=None):+ core = {"phase": self.phase, "done": self.phase == "over", "reason": self.reason,+ "ready": {s: st.ready for s, st in self.seats.items()},+ "world": "running" if self.phase == "running" else "frozen", "step": self.m.k,+ "t_sim": self.m.k * self.m.dt}+ self.seen[seat] = self.m.k # every reply's `now` is a world state the seat has seen+ if self.retired:+ core["retired"] = list(self.retired)+ return {**core, **self.observation(seat, query, since)}++ def status(self, seat, body=None):+ since = self.team_since(body)+ with self.cond:+ return 200, self.state(seat, since=since)++ def ready(self, seat, body):+ st = self.seats[seat]+ st.meter.settle() # never under the world lock (may wait for a stream)+ with self.cond:+ if self.phase not in ("prepare", "review"):+ return 409, {"error": "not awaiting ready", "now": self.state(seat)}+ if st.retired:+ return 409, {"error": "your side has retired"}+ if self.phase == "review" and seat not in self.due():+ return 409, {"error": "no review is due from you now"}+ unit = self.m.unit()+ if st.ready:+ return 409, {"error": "ready already submitted"}+ why, plan = body.get("why", ""), body.get("plan", "")+ if not isinstance(why, str) or not isinstance(plan, str) or len(why) > 2000 or len(plan) > 2000:+ return 400, {"error": "why and plan must be strings of at most 2000 characters"}+ if self.phase == "review" and (not why.strip() or not plan.strip()):+ return 400, {"error": "both review fields required"}+ st.joined = st.ready = True+ if self.ready_deadline is None:+ self.ready_deadline = time.monotonic() + (self.start_window() if self.phase == "prepare" else+ float(os.environ.get("READY_TIMEOUT_S", "60")))+ if self.phase == "review":+ self.reviews.append({"seat": seat, "after_unit": unit, "why": why, "plan": plan})+ self.ep.write("ready", seat=seat, unit=unit, why=why, plan=plan)+ self.barrier()+ self.cond.notify_all()+ while self.phase in ("prepare", "review") and self.m.unit() == unit: # one start event releases all+ self.cond.wait(.5)+ return 200, {"accepted": "ready", "now": self.state(seat)}++ def barrier(self):+ if all(self.seats[s].ready for s in self.due()):+ self.resume_at = time.monotonic() + float(os.environ.get("BARRIER_LEAD_S", ".2"))++ def due(self):+ seats = self.cfg.seats if self.phase == "prepare" else self.m.phase().review+ return [s for s in seats if not self.seats[s].retired]++ def act(self, seat, body):+ st = self.seats[seat]+ try:+ cmd = parse_action(self.layer, seat, body, self.m, {})+ except Refused as exc: # a malformed action: the player's own error, never a failure+ with self.cond:+ self.refused_invalid(seat, exc)+ raise+ entity = str(cmd.get("entity", "")) if isinstance(cmd, dict) else ""+ arrived = time.monotonic()+ lock = st.act_lock(entity)+ if not lock.acquire(False):+ return 429, {"error": "one act request per seat" + (" and entity" if entity else "") + " may be in flight"}+ try:+ with self.cond:+ st.count("attempts")+ if self.phase != "running":+ return 409, {"error": "the match is over" if self.phase == "over" else "world is not running",+ "now": self.state(seat)}+ if st.retired:+ return 409, {"error": "your side has retired"}+ unit = self.m.unit()+ seen = self.seen.get(seat) # the world state this act answers (reaction delay)+ if not st.meter.decided_by_model():+ with self.cond:+ st.count("refused")+ self.ep.write("refused_not_model", seat=seat, unit=unit)+ return 429, {"error": "act needs a fresh completed response started after resume, one act per response"}+ receipt = st.meter.last_call()+ with self.cond:+ if self.phase != "running" or self.m.unit() != unit:+ return 409, {"error": "unit ended during response confirmation"}+ job = self.layer.snapshot(seat, cmd, self.m, st.stats["attempts"])+ act_id = self.acts.new(seat) # diagnostics (core 0.2.25): act -> observation -> effect+ self.ep.write("act_received", seat=seat, unit=unit, decision=cmd, model_call=receipt, k=self.m.k,+ act_id=act_id, obs_id_last=self.acts.last_obs.get(seat), seen=seen,+ entity=entity or None)+ prepared = None+ if job is not None:+ prepared = (self.workers["plan", seat].call(job) if self.layer.worker else self.layer.prepare(job))+ with self.cond:+ if isinstance(prepared, dict) and "worker_s" in prepared:+ st.sample("plan_s", prepared["worker_s"])+ if self.phase != "running" or self.m.unit() != unit:+ st.count("dropped")+ self.dropped({"act_id": act_id}, seat, "unit_over_planning" if self.phase != "over" else "match_over")+ return 409, {"error": "unit ended during planning", "now": self.state(seat)}+ item = {"unit": unit, "cmd": cmd, "prepared": prepared, "arrived": arrived, "result": None,+ "act_id": act_id, "entity": entity}+ if seen is not None:+ item["seen"] = seen # the reaction report (core 0.2.23), any D+ if self.react:+ item["earliest"] = seen + self.react+ self.pending[seat, entity] = item+ while item["result"] is None and self.phase == "running" and self.m.unit() == unit:+ self.cond.wait(.5)+ if item["result"] is None:+ return 409, {"error": "unit ended before effect", "now": self.state(seat)}+ out = {"call": "act", "took_effect": item["result"], "now": self.state(seat)}+ if item.get("images") is not None: # drawn off the lock: the world runs on+ try:+ out["observation"] = self.reply_images(seat, item["images"])+ except Exception as exc: # noqa: BLE001+ self.failure("act_images", exc)+ return 500, {**out, "error": "technical failure"}+ return 200, out+ finally:+ lock.release()++ def apply_now(self, seat, low, act=None):+ """Log and apply one low-level command. An act's row (act = its pending item) also carries `seen`, the step of+ the world state the act answered (None if the seat had been sent none): the reaction report (core 0.2.23)."""+ self.ep.write("cmd", k=self.m.k, seat=seat, cmd=low, **({"seen": act.get("seen")} if act is not None else {}))+ info = self.m.apply(seat, low) or {}+ if act is not None and act.get("act_id") is not None: # diagnostics (core 0.2.25): not in the cmd row+ self.diag("effect", seat=seat, act_id=act["act_id"], k=self.m.k, entity=act.get("entity") or None,+ **({"rejected": True} if "rejected" in info else {}))+ return info++ def dropped(self, item, seat, why):+ """An accepted act that will never take effect (diagnostics, core 0.2.25)."""+ if item.get("act_id") is not None:+ self.diag("act_dropped", seat=seat, act_id=item["act_id"], k=self.m.k, why=why)++ def apply_pending(self):+ tick = getattr(self.layer, "tick", None) # a layer's per-step command (the skill in the loop's step(),+ if tick is not None: # skilleval/inloop.py): applied and logged like any other+ for seat in self.cfg.seats:+ if self.seats[seat].retired:+ continue+ low = tick(seat, self.m)+ if low is not None and "rejected" in self.apply_now(seat, low):+ self.seats[seat].count("rejected")+ due = [x for x in self.scheduled if x[0] <= self.m.k]+ self.scheduled = [x for x in self.scheduled if x[0] > self.m.k]+ for _, seat, low, act in due:+ info = self.apply_now(seat, low, act)+ if "rejected" in info:+ self.seats[seat].count("rejected")+ batch, self.pending = self.pending, {}+ for (seat, _entity), item in batch.items():+ st = self.seats[seat]+ if item["unit"] != self.m.unit():+ st.count("dropped")+ self.dropped(item, seat, "unit_changed")+ continue+ if item.get("earliest", 0) > self.m.k: # held until its reaction delay has passed (core 0.2.18)+ self.pending[seat, _entity] = item+ continue+ low, info = self.layer.lower(seat, item["cmd"], item["prepared"], self.m)+ if self.delay:+ self.scheduled.append([self.m.k + self.delay, seat, low, {"seen": item.get("seen"),+ "act_id": item["act_id"],+ "entity": item["entity"]}])+ info = {"effect_step": self.m.k + self.delay, **info}+ else:+ applied = self.apply_now(seat, low, item)+ item["images"] = self.reply_job(seat, low, applied)+ info = {**applied, **info}+ if "rejected" in info:+ st.count("rejected")+ elapsed = time.monotonic() - item["arrived"]+ item["result"] = {"step": self.m.k, "t_sim": self.m.k * self.m.dt, "wall_s_after_request": elapsed,+ **({"seen_step": item["seen"], "reaction_delay_steps": self.react}+ if self.react and "seen" in item else {}),+ **self.layer.reply(seat, item["cmd"], info, self.m)}+ st.count("applied")+ st.sample("act_s", elapsed)++ def observe(self, seat, body=None):+ st = self.seats[seat]+ query = query_of(body)+ since = self.team_since(body)+ if not st.view_lock.acquire(False):+ return 429, {"error": "one observation per seat may be in flight"}+ try:+ with self.cond:+ if self.phase == "over": # core 0.2.26: no images after the end, the final state only+ return 409, {"error": "the match is over", "now": self.state(seat, since=since)}+ now, (job, meta) = self.query_guard(seat, query, lambda: (self.state(seat, query, since),+ self.camera_job(seat, query)))+ st.count("observations")+ obs_id = st.stats["observations"]+ k_obs = self.m.k+ meta = dict(meta)+ steps = view_steps(meta, job, k_obs)+ out = self.draw(seat, job) or {}+ age = max(0.0, time.monotonic() - meta.pop("wall_mono", time.monotonic()))+ with self.cond:+ st.sample("obs_age_s", age)+ self.ep.write("observe", seat=seat, obs_id=obs_id, age_s=age, query=query, k=k_obs, view_steps=steps)+ self.acts.observed(seat, obs_id) # what the seat's next act answers (act_received)+ obs = {"obs_id": obs_id, **meta, "obs_age_wall_s": age, "render_wall_s": out.get("worker_s", 0.0)}+ if out.get("png"):+ obs["image_png_b64"] = base64.b64encode(out["png"]).decode()+ if out.get("tiles"):+ obs["tiles"] = out["tiles"]+ return 200, {"call": "observe", "now": now, "observation": obs}+ finally:+ st.view_lock.release()++ def wait(self, seat, body):+ try:+ d = float(body.get("dt", 0))+ except (TypeError, ValueError, OverflowError):+ d = math.nan+ if not np.isfinite(d) or not 0 < d <= 1:+ return 400, {"error": "dt must be 0..1 game seconds"}+ since = self.team_since(body)+ with self.cond:+ target, unit = self.m.k + int(np.ceil(d / self.m.dt)), self.m.unit()+ while self.phase == "running" and self.m.unit() == unit and self.m.k < target:+ self.cond.wait(.5)+ return 200, {"now": self.state(seat, since=since)}++ # ------------------------------------------------------------------ the world loop+ def on_end(self):+ if self.segment_start is not None:+ self.run_wall += time.monotonic() - self.segment_start+ self.segment_start = None+ self.drop_all("match_over")++ def drop_all(self, why):+ """The acts waiting for their effect step will never take effect: act_dropped rows, queues cleared."""+ for (s, _e), item in self.pending.items():+ self.dropped(item, s, why)+ for _k, s, _low, act in self.scheduled:+ self.dropped(act, s, why)+ self.pending.clear()+ self.scheduled.clear()++ def timeout(self):+ """The ready window ran out. In prepare (the start window): a side that never started loses ("no_show", see+ Service.close_start_window); in a review: a late side loses (or retires)."""+ if self.phase == "prepare":+ self.ready_deadline = None+ if self.close_start_window():+ self.barrier() # the present seats have all started: run after the lead time+ return+ missing = [s for s in self.due() if not self.seats[s].ready]+ sides = []+ for s in missing:+ if self.cfg.side_of(s) not in sides:+ sides.append(self.cfg.side_of(s))+ if len(sides) == 1 or (len(self.active_sides()) > 2 and len(sides) < len(self.active_sides())):+ for side in sides:+ seat = next(s for s in missing if self.cfg.side_of(s) == side)+ if not self.lose(seat, "ready_timeout"):+ return+ self.ready_deadline = time.monotonic() + float(os.environ.get("READY_TIMEOUT_S", "60"))+ self.barrier()+ return+ self.end("incomplete")++ def loop(self):+ try:+ while True:+ with self.cond:+ if self.phase == "over":+ return+ now = time.monotonic()+ if self.phase in ("prepare", "review"):+ if self.resume_at is not None and now >= self.resume_at:+ if self.m.phase().state == UNIT_OVER:+ self.ep.write("resume", k=self.m.k)+ self.m.resume()+ now, epoch = time.monotonic(), time.time() # the run starts when resume() returns+ for st in self.seats.values():+ st.meter.begin_segment(epoch)+ st.ready = False+ self.phase, self.anchor, self.segment_start = "running", (now, self.m.k), now+ self.resume_at = self.ready_deadline = None+ self.ep.write("run", k=self.m.k, started_epoch=epoch)+ self.bc.event("run")+ self.cond.notify_all()+ elif self.ready_deadline and now > self.ready_deadline:+ self.timeout()+ continue+ else:+ self.cond.wait(.01)+ continue+ a, k = self.anchor+ due = a + (self.m.k - k + 1) * self.period+ delay = due - time.monotonic()+ if delay > 0:+ time.sleep(min(delay, .02))+ continue+ with self.cond:+ if self.phase != "running":+ continue+ self.apply_pending()+ events = self.m.step()+ if events: # diagnostics (core 0.2.25): what the step returned+ self.diag("event", k=self.m.k, events=jsonable(events))+ self.bc.frame(force=self.m.phase().state != "playing")+ self.run_steps += 1+ self.lates.append(max(0.0, time.monotonic() - due))+ ph = self.m.phase()+ if ph.state != "playing":+ for s, _e in self.pending:+ self.seats[s].count("dropped")+ self.drop_all("unit_over")+ self.ep.write("unit_over", k=self.m.k, unit=self.m.unit(), reason=ph.reason)+ self.bc.event("unit_over", unit=self.m.unit(), reason=ph.reason, scores=self.m.scores())+ if ph.state == FINISHED:+ self.end("match_over")+ else:+ self.phase = "review"+ self.run_wall += time.monotonic() - self.segment_start+ self.segment_start = None+ self.ready_deadline = time.monotonic() + float(os.environ.get("READY_TIMEOUT_S", "60"))+ if not self.due(): # nobody reviews: go on after the lead time+ self.barrier()+ self.cond.notify_all()+ if self.m.k % 50 == 0 or self.phase != "running":+ self.write_final()+ except Exception as exc: # noqa: BLE001+ self.failure("world", exc)++ def header_extra(self) -> dict:+ """The episode header's timing (core 0.2.23): what the reaction report of a replay needs."""+ return {"timing": {"reaction_delay_steps": spec_mod.reaction_delay(self.decl),+ "effect_delay_steps": int(getattr(self.layer, "delay_steps", 0) or 0)}}++ def reaction_final(self) -> dict:+ """final.json `reaction` (core 0.2.23, report only: no effect on validity or grading): per seat, how many acts+ took effect within the declared reaction delay D, and the distribution of the actual delay, from the episode's+ command rows (core/episode.reaction_report); `replayed`: the fresh-process replay's report is the same."""+ with self.ep.lock:+ rows = list(self.ep.commands)+ out = reaction_report(rows, self.cfg.seats, self.react, self.delay)+ rr = (self.replay or {}).get("reaction")+ out["replayed"] = None if not self.replay else bool(rr and rr.get("by_seat") == out["by_seat"])+ return out++ def extra_final(self):+ L = self.lates+ return {"reaction": self.reaction_final(), "slowdown": self.slowdown, "timing_policy": "report_only", "timing_invalid": False,+ "sim_lag": {"late_max_s": max(L, default=0), "late_p99_s": float(np.percentile(L, 99)) if L else 0,+ "run_steps": self.run_steps, "run_sim_s": self.run_steps * self.m.dt,+ "run_wall_s": self.run_wall, "period_s": self.period}}++ def collect(self):+ """Every player session has ended. Before the start every side that has not started loses ("no_show", a valid+ loss; Service.no_show_at_collect, core 0.2.7); a single side whose match has started loses ("abandoned", a+ valid loss; Service.abandon_single, core 0.2.6). Otherwise (two or more sides after the start, or no side+ started) the match ends "collected": unfinished, no winner, not a valid trial."""+ with self.cond:+ if self.no_show_at_collect():+ self.ready_deadline = None+ elif not self.abandon_single():+ self.end("collected")+++__all__ = ["RealtimeService", "Refused"]diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/rng.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/rng.pynew file mode 100644index 0000000000..37efff2c79--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/rng.py@@ -0,0 +1,15 @@+"""Random numbers by name (docs/framework_zh.md §5, rule 4 of the sport rules): every random draw of a sport comes from+a stream named by the sport, seeded from the match seed and the name only, so a stream never depends on how many+draws another stream made, and a replay in a fresh process draws the same numbers."""+from __future__ import annotations++import hashlib++import numpy as np+++def stream(cfg_or_seed, name: str) -> np.random.Generator:+ seed = getattr(cfg_or_seed, "seed", cfg_or_seed)+ sport = getattr(cfg_or_seed, "sport", "")+ h = hashlib.sha256(f"{sport}|{int(seed)}|{name}".encode()).digest()+ return np.random.Generator(np.random.PCG64(int.from_bytes(h[:16], "little")))diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/score.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/score.pynew file mode 100644index 0000000000..d37235fa44--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/score.py@@ -0,0 +1,89 @@+"""The continuous score (core 0.2.14, docs/framework_zh.md §4.3): one number per side, LARGER IS BETTER, that the+leaderboards and statistics read next to the win (final.json `continuous`, reward.json `<seat>_continuous_score` and,+for a single-side format, `continuous_score`). The sport defines it in sport.toml [score]:++ name an id ([a-z][a-z0-9_]*), e.g. point_share, mean_per_throw, goal_difference+ text the definition in one sentence (README, site)+ from share own score / the sum of every side's score in Match.scores() (0.5 when nothing was scored)+ margin own score - the best other score in Match.scores()+ own own score (a single format scored against a line)+ hook Match.continuous_score() -> {side: number} (anything else, e.g. a mean per throw)+ forfeit the value of a side that forfeited (no_show, abandoned, clock, review time) or retired: a side cannot+ keep a good number by walking away; it should be the worst value the definition allows+ range optional [lo, hi]: the values the definition can take (core.testkit checks them)++A sport without [score] has no continuous score (the fields are absent); tools/check warns, and fails once the sport+has registered hidden official seeds (it is frozen for a season)."""+from __future__ import annotations++import math+import re++KINDS = ("share", "margin", "own", "hook")+NAME = re.compile(r"^[a-z][a-z0-9_]*$")+++def declaration(decl: dict) -> dict | None:+ return decl.get("score") or None+++def problems(decl: dict, has_hook: bool) -> list[str]:+ """What is wrong with sport.toml [score] (empty: fine, or not declared)."""+ d = declaration(decl)+ if d is None:+ return []+ out = []+ if not NAME.match(str(d.get("name", ""))):+ out.append("name: an id [a-z][a-z0-9_]*")+ if not str(d.get("text", "")).strip():+ out.append("text: the definition in one sentence")+ if d.get("from") not in KINDS:+ out.append(f"from: one of {', '.join(KINDS)}")+ if (d.get("from") == "hook") != has_hook:+ out.append("from = \"hook\" iff the plugin defines continuous_score()")+ if not isinstance(d.get("forfeit"), (int, float)) or isinstance(d.get("forfeit"), bool):+ out.append("forfeit: a number (the value of a side that forfeits)")+ r = d.get("range")+ if r is not None and not (isinstance(r, list) and len(r) == 2 and all(isinstance(x, (int, float)) for x in r)+ and r[0] < r[1]):+ out.append("range: [lo, hi] with lo < hi")+ if d.get("from") in ("share", "margin") and not any(+ len(set((f.get("sides") or {s: s for s in f.get("seats", [])}).values())) > 1 or f.get("opponent")+ for f in (decl.get("formats") or {}).values()):+ out.append(f"from = \"{d.get('from')}\" needs a format with an opponent")+ return out+++def compute(match, decl: dict, sides, forfeited=()) -> dict | None:+ """{"name", "from", "higher_is_better": True, "by_side": {side: float}, "forfeited": [sides]} for the player+ sides at the end of a match, None without a declaration. Raises on a non-finite value (a sport bug)."""+ d = declaration(decl)+ if d is None:+ return None+ kind = d["from"]+ if kind == "hook":+ raw = match.continuous_score()+ if raw is None:+ raise RuntimeError("[score] from = \"hook\" but Match.continuous_score() returned None")+ vals = {s: raw.get(s) for s in sides}+ else:+ sc = {str(k): float(v) for k, v in (match.scores() or {}).items()}+ vals = {}+ for s in sides:+ own = sc.get(s, 0.0)+ others = [v for k, v in sc.items() if k != s]+ if kind == "share":+ tot = own + sum(others)+ vals[s] = own / tot if tot > 0 else 0.5+ elif kind == "margin":+ vals[s] = own - max(others) if others else own+ else:+ vals[s] = own+ by = {}+ for s in sides:+ v = float(d["forfeit"]) if s in forfeited else vals.get(s)+ if v is None or isinstance(v, bool) or not math.isfinite(float(v)):+ raise RuntimeError(f"continuous score of side {s}: {v!r} is not a finite number")+ by[s] = round(float(v), 6)+ return {"name": d["name"], "from": kind, "higher_is_better": True, "by_side": by,+ "forfeited": [s for s in sides if s in forfeited]}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/seats.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/seats.pynew file mode 100644index 0000000000..94cb549406--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/seats.py@@ -0,0 +1,87 @@+"""Seats: metering (the unchanged think_clock.py / api_errors.py), per-seat counters, one-request-in-flight locks (per+entity for acts), the chess clock of the turn protocol, and the validity fields every final.json carries."""+from __future__ import annotations++import os+import threading+import time+from pathlib import Path++from .metering.api_errors import seat_api_errors+from .metering.think_clock import ThinkClock, read_usage++UNMETERED_MODES = ("oracle", "unmetered") # player modes whose model the sim does not meter+++class Seat:+ def __init__(self, name: str, data: Path, clock_s: float | None = None, side: str | None = None):+ self.name, self.side = name, side or name+ self.mode = os.environ.get(f"PLAYER_MODE_{name}", os.environ.get("RCB_PLAYER_MODE", "model"))+ if self.mode not in UNMETERED_MODES + ("model",):+ raise ValueError(f"PLAYER_MODE_{name} must be model, oracle or unmetered")+ # "unmetered" (core 0.2.29): the runner meters the seat's model itself (a single-seat task run by a plain+ # Harbor with its native agents, e.g. the export to the upstream benchmark): no metering proxy, so the meter+ # takes the gate's exemption (ThinkClock's oracle rule; think_clock.py stays unchanged) and no meter is+ # required for validity (Service.need_meter); final.json records the mode as it is.+ self.meter = ThinkClock(usage_file=str(Path(data) / f"think_usage_{name}.json"),+ mode="oracle" if self.mode in UNMETERED_MODES else self.mode)+ self.act_locks: dict[str, threading.Lock] = {}+ self.view_lock = threading.Lock()+ self.joined = self.ready = self.retired = False+ self.stats: dict = {}+ self.clock_s, self.used, self.turn_t0, self.turn_busy = clock_s, 0.0, None, 0.0+ self.frozen, self.frozen_at = 0, None # off-lock service in progress (images being drawn): no clock++ def act_lock(self, entity: str = "") -> threading.Lock:+ return self.act_locks.setdefault(entity, threading.Lock())++ def count(self, key: str, n: int = 1):+ self.stats[key] = self.stats.get(key, 0) + n++ def sample(self, key: str, v: float):+ self.stats.setdefault(key, []).append(v)++ # chess clock (turn protocol): runs on this seat's turn only; service time inside the turn does not count+ def clock_used(self, now=None) -> float:+ if self.turn_t0 is None:+ return self.used+ now = now or time.time()+ if self.frozen: # the clock stands still while the service draws this seat's images+ now = max(self.turn_t0, min(now, self.frozen_at))+ return self.used + max(0.0, now - self.turn_t0 - self.turn_busy)++ def freeze(self, now):+ """Service work for this seat continues off the lock (drawing its images, core 0.2.8): stop the clock."""+ if self.frozen == 0:+ self.frozen_at = now+ self.frozen += 1++ def thaw(self, now):+ self.frozen -= 1+ if self.frozen == 0:+ if self.turn_t0 is not None:+ self.turn_busy += max(0.0, now - max(self.frozen_at, self.turn_t0))+ self.frozen_at = None++ def clock_left(self) -> float:+ return (self.clock_s or 0.0) - self.clock_used()++ def start_turn(self, now):+ self.turn_t0, self.turn_busy = now, 0.0++ def stop_turn(self, now):+ if self.turn_t0 is not None:+ self.used = self.clock_used(now)+ self.turn_t0 = None+++def validity_fields(seats: dict[str, Seat], need_meter) -> dict:+ """Metering and model-API validity of every seat (the one rule of api_errors.py)."""+ usage = {s: read_usage(st.meter.usage_file) for s, st in seats.items()}+ meter = {s: bool(need_meter(seats[s]) and (not usage[s].get("epoch") or not usage[s].get("requests")))+ for s in seats}+ apis = {s: seat_api_errors(seats[s].meter.usage_file, usage[s]) for s in seats}+ return {"meter_error": meter, "proxy_error": {s: a["api_failure"] for s, a in apis.items()},+ "transient_api_errors": {s: a["transient_api_errors"] for s, a in apis.items()},+ "unrecovered_api_errors": {s: a["unrecovered_api_errors"] for s, a in apis.items()},+ "player_modes": {s: st.mode for s, st in seats.items()}}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/seeds.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/seeds.pynew file mode 100644index 0000000000..c6a2ae4c83--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/seeds.py@@ -0,0 +1,178 @@+"""Hidden official seeds (core 0.2.14, docs/framework_zh.md §6.4): a sport frozen for a season plays its official+matches on a seed set that only the organisers hold. The repository has its commitments, never the seeds.++ cells the set is partitioned by format x level: one cell per format ("duel") or per format and level of a+ format with levels ("match/L1", "match/L2", ...; cell_of); every cell has its own seeds, none shared+ private set {"schema": PRIVATE, "sport", "created", "cells": {cell: [{"seed": int, "salt": 32 hex}, ...]}}: outside+ git, on the official run host only (tools/seeds.py: $RO_SEEDS_DIR/<sport>.hidden_seeds.json, 0600)+ commitments one per seed, in cell order: sha256("ro-hidden-seeds/1|<sport>|<seed>|<salt>"); the salt (128 random+ bits) makes a commitment say nothing about its seed+ registration set_sha256 (the sport and every cell's commitments) and the count per cell: sport.toml+ [official.hidden_seeds] sha256, counts; the commitments are public (sports/<sport>/seed_commitments.json)++At run time the runner hands one seed, its salt and its index to the sim service only (RO_SEED, RO_SEED_SALT,+RO_SEED_INDEX); the players' containers never see them. In such a match the core writes the seed nowhere: the+episode header, final.json, replay_check.json and the broadcast log carry seed -1 and the commitment only+(final.json seed_proof), the sport's own fields and the players' observations and /spec are scrubbed (scrub()), and+the fresh-process replay takes the seed from the same environment and checks it against the commitment. The salt is+never written either (with it, a six-digit seed would follow from its commitment by brute force). The verifier finds+the commitment in the cell of the match's format and level (index()): hidden_seed, hidden_seed_index. The private set+plus the index is the only record of the seed; after the season the set may be published and anyone can recompute+set_sha256 from it.++Standard library only: the generator copies this file next to the verifier (tests/seeds.py)."""+from __future__ import annotations++import hashlib+import re+import secrets++SCHEMA = "ro-hidden-seeds/1" # the commitment of one seed+SET_SCHEMA = "ro-hidden-seeds/2" # the registered digest of a partitioned set+PRIVATE = "ro-hidden-seeds-private/2"+PUBLIC = "ro-hidden-seeds-public/2"+SEED_RANGE = (100000, 999999) # six digits: an int32 for any simulator+HIDDEN = -1 # the seed as written in the records of a hidden-seed match+HEX = re.compile(r"^[0-9a-f]{64}$")+CELL = re.compile(r"^[a-z0-9][a-z0-9_-]*(/L\d+)?$") # a format name of sport.toml, "/L<level>"+KEEP = {"step", "k", "steps", "t_sim"}+COMMITMENTS = "seed_commitments.json" # sports/<sport>/<this>: the public part (public())+++def commitment(sport: str, seed: int, salt: str) -> str:+ return hashlib.sha256(f"{SCHEMA}|{sport}|{int(seed)}|{salt}".encode()).hexdigest()+++def set_sha256(sport: str, cells: dict) -> str:+ """The registered digest of a seed set: its sport and every cell's commitments, cells in sorted order."""+ text = SET_SCHEMA + "\n" + sport + "\n"+ for c in sorted(cells):+ text += f"[{c}]\n" + "".join(x + "\n" for x in cells[c])+ return hashlib.sha256(text.encode()).hexdigest()+++def cell_of(fmt: str, level, cells) -> str | None:+ """The cell of a match: "<format>/L<level>" when the set has it, else "<format>" when it has that, else None."""+ if level is not None and f"{fmt}/L{int(level)}" in cells:+ return f"{fmt}/L{int(level)}"+ return fmt if fmt in cells else None+++def new(sport: str, counts: dict, avoid=(), created: str = "") -> dict:+ """A fresh private set: counts = {cell: n}; every seed distinct across cells and none of `avoid`."""+ if not counts or any(int(n) < 1 or not CELL.match(c) for c, n in counts.items()):+ raise ValueError("cells: {\"<format>\" or \"<format>/L<level>\": count >= 1}")+ lo, hi = SEED_RANGE+ used, cells = {int(x) for x in avoid}, {}+ for c in sorted(counts):+ cells[c] = []+ while len(cells[c]) < int(counts[c]):+ s = lo + secrets.randbelow(hi - lo + 1)+ if s not in used:+ used.add(s)+ cells[c].append({"seed": s, "salt": secrets.token_hex(16)})+ return {"schema": PRIVATE, "sport": sport, "created": created, "cells": cells}+++def from_seeds(sport: str, cells: dict, created: str = "") -> dict:+ """A private set of given seeds ({cell: [int, ...]}) with fresh salts."""+ out = {c: [{"seed": int(s), "salt": secrets.token_hex(16)} for s in v] for c, v in cells.items()}+ p = {"schema": PRIVATE, "sport": sport, "created": created, "cells": out}+ check_private(p)+ return p+++def check_private(p: dict) -> None:+ if p.get("schema") != PRIVATE or not p.get("sport") or not p.get("cells"):+ raise ValueError(f"not a private seed set (schema {PRIVATE}, sport, cells)")+ seen = set()+ for c, entries in p["cells"].items():+ if not CELL.match(c) or not entries:+ raise ValueError(f"bad cell {c!r}")+ for e in entries:+ if not isinstance(e.get("seed"), int) or not re.fullmatch(r"[0-9a-f]{32}", str(e.get("salt", ""))):+ raise ValueError(f"bad entry in {c}: seed int, salt 32 hex")+ if e["seed"] in seen:+ raise ValueError(f"seed {e['seed']} twice (cells never share a seed)")+ seen.add(e["seed"])+++def public(p: dict) -> dict:+ """The public part of a private set: what goes into the repository."""+ check_private(p)+ cells = {c: [commitment(p["sport"], e["seed"], e["salt"]) for e in v] for c, v in sorted(p["cells"].items())}+ return {"schema": PUBLIC, "sport": p["sport"], "counts": {c: len(v) for c, v in cells.items()},+ "sha256": set_sha256(p["sport"], cells), "cells": cells}+++def registered(sport: str, reg: dict) -> dict:+ """The cells of a registration {sha256, counts, cells}, after checking that they are the registered ones (their+ digest and counts); ValueError otherwise."""+ cells = reg.get("cells") or {}+ counts = reg.get("counts") or {}+ if set(cells) != set(counts) or not cells:+ raise ValueError("hidden seeds: the cells of the commitments and of the counts differ")+ flat = [x for v in cells.values() for x in v]+ if not all(isinstance(x, str) and HEX.match(x) for x in flat) or len(set(flat)) != len(flat):+ raise ValueError("hidden seeds: commitments must be distinct sha256 hex digests")+ for c, v in cells.items():+ if len(v) != int(counts[c]):+ raise ValueError(f"hidden seeds: cell {c} has {len(v)} commitments, count {counts[c]}")+ if set_sha256(sport, cells) != reg.get("sha256"):+ raise ValueError("hidden seeds: the commitments do not hash to the registered sha256")+ return cells+++def index(sport: str, fmt: str, level, commit: str | None, reg: dict) -> int | None:+ """The position of a match's commitment in the cell of its format and level, None if it is not there (or the+ registration is inconsistent: then nothing is a member)."""+ if not commit:+ return None+ try:+ cells = registered(sport, reg)+ except (ValueError, TypeError):+ return None+ cell = cell_of(fmt, level, cells)+ if cell is None or commit not in cells[cell]:+ return None+ return cells[cell].index(commit)+++def resolve(p: dict, cell: str, i: int, reg: dict | None = None) -> tuple[int, str]:+ """(seed, salt) of entry i of a cell of a private set; with a registration, also checks that the set is the+ registered one."""+ check_private(p)+ if cell not in p["cells"]:+ raise KeyError(f"no cell {cell!r} (cells: {', '.join(sorted(p['cells']))})")+ if not 0 <= i < len(p["cells"][cell]):+ raise IndexError(f"cell {cell} has {len(p['cells'][cell])} seeds (0..{len(p['cells'][cell]) - 1}); asked {i}")+ if reg is not None and public(p)["sha256"] != reg.get("sha256"):+ raise ValueError("this private seed set is not the registered one (sha256 differs)")+ e = p["cells"][cell][i]+ return int(e["seed"]), str(e["salt"])+++def scrub(obj, seed: int, salt: str = ""):+ """A copy of obj (JSON-like) without the seed: values under a key named "seed" or "*_seed" become HIDDEN, and so+ does any integer equal to the seed or any string equal to it or to the salt. For a hidden-seed match."""+ seed = int(seed)++ def go(x, key=""):+ if (key == "seed" or key.endswith("_seed")) and not isinstance(x, (dict, list, tuple)):+ return HIDDEN+ if key in KEEP: # the core's step counters: never the seed, may reach six digits+ return x+ if isinstance(x, dict):+ return {k: go(v, str(k)) for k, v in x.items()}+ if isinstance(x, (list, tuple)):+ return [go(v) for v in x]+ if isinstance(x, bool):+ return x+ if isinstance(x, int) and x == seed:+ return HIDDEN+ if isinstance(x, float) and x == seed:+ return float(HIDDEN)+ if isinstance(x, str) and (x == str(seed) or (salt and x == salt)):+ return str(HIDDEN)+ return x+ return go(obj)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/serve.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/serve.pynew file mode 100644index 0000000000..55d60c8b95--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/serve.py@@ -0,0 +1,54 @@+"""Entry point of a generated task's sim service: python3 -m core.serve (cwd = the directory holding core/).++Environment: RO_PLUGIN (path of the sport's plugin.py), RO_SPORT, RO_FORMAT, RO_SEATS (e.g. "A,B"), RO_SIDES (e.g.+"A=home,B=home,C=away,D=away"; default: every seat its own side), RO_SEED, RO_SEED_SALT+(a hidden official seed's salt, core 0.2.14: recorded in final.json seed_proof for the verifier), RO_FIRST, RO_SLOWDOWN (realtime), RO_LEVEL+(single), RO_PARAMS (JSON), RO_RENDERER (the players' image renderer), RCB_ACTION_LEVEL, RCB_PLAY, RCB_DATA,+SEAT_HOSTS. The runner's own names (DUEL_SEED, FIRST_PLAYER, ...) are mapped onto these by the task's compose file.+"""+from __future__ import annotations++import json+import os+import signal+import threading+from pathlib import Path++from .episode import load_plugin+from .http import make_server+from .realtime import RealtimeService+from .sport import MatchConfig+from .turn import TurnService+++def config_from_env() -> MatchConfig:+ e = os.environ.get+ level, slow = e("RO_LEVEL"), e("RO_SLOWDOWN")+ sides = dict(x.split("=", 1) for x in e("RO_SIDES", "").split(",") if "=" in x) or None+ return MatchConfig(sport=e("RO_SPORT", ""), format=e("RO_FORMAT", "duel"),+ seats=tuple(e("RO_SEATS", "A,B").split(",")), seed=int(e("RO_SEED", "1")),+ first=e("RO_FIRST") or None, slowdown=float(slow) if slow else None,+ level=int(level) if level else None, action_level=e("RCB_ACTION_LEVEL", "high"),+ play=e("RCB_PLAY", "program"), params=json.loads(e("RO_PARAMS", "{}")), sides=sides,+ renderer=e("RO_RENDERER") or None)+++def main():+ plugin = os.path.abspath(os.environ["RO_PLUGIN"])+ sport = load_plugin(plugin)+ cfg = config_from_env()+ if cfg.action_level not in ("high", "low") or cfg.play not in ("program", "direct"):+ raise ValueError("RCB_ACTION_LEVEL must be high or low, RCB_PLAY program or direct")+ data = Path(os.environ.get("RCB_DATA", "/data"))+ svc = (RealtimeService if sport.protocol == "realtime" else TurnService)(sport, plugin, cfg, data)+ hosts = dict(x.split("=", 1) for x in os.environ.get("SEAT_HOSTS", "").split(",") if "=" in x)+ signal.signal(signal.SIGUSR1, lambda *a: threading.Thread(target=svc.collect, daemon=True).start())+ svc.write_final()+ (data / "server.pid").write_text(str(os.getpid()))+ threading.Thread(target=svc.loop, daemon=True).start()+ print(f"{sport.name} {cfg.format} service ready ({svc.protocol_id})", flush=True)+ make_server(svc, cfg.seats, hosts, int(os.environ.get("RCB_PORT", "8000"))).serve_forever()+++if __name__ == "__main__":+ main()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/service.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/service.pynew file mode 100644index 0000000000..3befc74ecc--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/service.py@@ -0,0 +1,527 @@+"""What both protocols share: the match, seats and sides, the episode, worker processes, observations (whitelist,+cameras through the task's renderer, the team channel), the end of a match (fresh-process replay and its comparison)+and final.json (common validity fields + the sport's own fields)."""+from __future__ import annotations++import base64+import json+import os+import subprocess+import sys+import threading+import time+from pathlib import Path++from . import VERSION+from . import score as score_mod+from . import seeds as seeds_mod+from . import spec as spec_mod+from .channel import TeamChannel+from .diaglog import Acts, safe+from .episode import Episode, source_sha+from .observe import CameraWorker, filter_fields, players_scene, reply_job+from .outcome import decide+from .sport import Refused+from .seats import Seat, validity_fields+from .spectator import Broadcast+from .sport import MatchBase+from .workers import ProcessWorker++ROOT = Path(__file__).resolve().parent+FORFEIT_REASONS = ("ready_timeout", "clock", "abandoned", "no_show")+CAMERA_KIND = "camera" # the core's own render worker: the sport's cameras drawn by the task's renderer+# final.json compatibility (the readers of Season 1: live_board, the site extractors, regrade_transient, broadcast):+# every sport field (Match.final_fields(), also kept under "sport_fields") is lifted to the top level unless a core+# field has that name, and "score" is the by-side score unless the sport sets its own. A migrating sport keeps its+# legacy field names in final_fields(); a reader that needs a sport field whose name a core field took (e.g. a+# legacy "scores" table) reads sport_fields first (live_board does).+COMPAT = "v0.1-toplevel-aliases"+++def own_hook(obj, name) -> bool:+ """Does the sport's Match override MatchBase's default of `name`?"""+ f = getattr(type(obj), name, None)+ return f is not None and f is not getattr(MatchBase, name, None)+++def public_spec(sport, cfg, seat, m, layer, decl) -> dict:+ """The sport's part of /spec: the action layer's commands, the camera definitions with their intrinsics, the+ rule constants of sport.toml [spec] and the tiebreak text, plus anything Sport.spec() adds."""+ out = {}+ schema = layer.schema(m, seat) if hasattr(layer, "schema") else {}+ if schema:+ out["actions"] = schema+ cams = m.cameras(seat) if own_hook(m, "cameras") else []+ if cams:+ from renderers.base import CameraDef+ out["cameras"] = [dict(c, **CameraDef.from_dict(c).intrinsics()) for c in cams]+ out.update(decl.get("spec") or {})+ if (decl.get("tiebreaks") or {}).get("text"):+ out["tiebreaks"] = decl["tiebreaks"]["text"]+ f = getattr(sport, "spec", None)+ if f is not None:+ out.update(f(cfg, seat, m))+ return out+++class Service:+ protocol = ""++ def __init__(self, sport, plugin: str, cfg, data: Path, clock_s: float | None = None):+ self.sport, self.plugin, self.cfg, self.data = sport, plugin, cfg, Path(data)+ self.data.mkdir(parents=True, exist_ok=True)+ self.decl = spec_mod.load(plugin)+ self.allowed = spec_mod.whitelist(self.decl)+ self.m = sport.build(cfg)+ self.layer = sport.action_layer(cfg.action_level)+ self.seats = {s: Seat(s, self.data, clock_s, cfg.side_of(s)) for s in cfg.seats}+ self.cond = threading.Condition(threading.RLock())+ self.t0 = time.monotonic()+ self.phase, self.reason, self.forfeiting = "prepare", None, None+ self.retired: list[str] = []+ self.errors, self.reviews, self.replay = [], [], {}+ self.finalizing = self.finalized = False+ self.channel = TeamChannel(cfg, self.decl.get("team_channel"))+ self.columns = int((self.decl.get("observation") or {}).get("columns", 2))+ self.source_sha = source_sha(ROOT, *sport.source_dirs, *self.extra_source_dirs())+ self.versions = {"protocol": self.protocol_id, "core": VERSION, "sport": sport.revision,+ "players": {s: os.environ.get(f"RO_PLAYER_CONFIG_{s}", "") for s in cfg.seats}}+ salt = os.environ.get("RO_SEED_SALT", "") # a hidden official seed (core/seeds.py, core 0.2.14)+ self.hidden = ({"seed": int(cfg.seed), "salt": salt,+ "commitment": seeds_mod.commitment(sport.name, cfg.seed, salt)} if salt else None)+ self.ep = Episode(self.data / "episode.jsonl")+ self.diag = safe(self.ep.write) # diagnostic rows (core/diaglog.py, core 0.2.25): never replayed+ self.acts = Acts(cfg.seats)+ self.ep.write("header", cfg=self.cfg_json(), sport=sport.name, revision=sport.revision, protocol=self.protocol,+ source_sha=self.source_sha, versions=self.versions,+ player_modes={s: st.mode for s, st in self.seats.items()},+ **({"seed_hidden": {"commitment": self.hidden["commitment"]}} if self.hidden else {}),+ **self.header_extra())+ self.workers = {}+ self.cameras = own_hook(self.m, "cameras") and not own_hook(self.m, "camera_job")+ self.renderer_name = cfg.renderer+ self.camera = None # in-process CameraWorker (turn protocol, or no render worker)+ self.render_lock = threading.Lock() # in-process drawing: one at a time (it runs off the world lock)+ self.replies = own_hook(self.m, "reply_views") and self.cameras # reply images (core 0.2.8)+ for kind in getattr(sport, "workers", ()):+ for s in cfg.seats:+ k = CAMERA_KIND if (kind == "render" and self.cameras) else kind+ self.workers[kind, s] = ProcessWorker(plugin, k, s, cfg.to_json())+ self.video_info: dict = {}+ self.bc = Broadcast(sport, cfg, self.m, self.decl, slowdown=cfg.slowdown) # spectators only+ self.bc.clean = self.public++ def cfg_json(self) -> dict:+ """The match configuration as the records show it: a hidden seed is written as -1 (core/seeds.py)."""+ d = self.cfg.to_json()+ if self.hidden:+ d["seed"] = seeds_mod.HIDDEN+ return d++ def public(self, obj):+ """What leaves the sim service (replies, final.json, the broadcast log): without a hidden seed or its salt+ (core/seeds.py scrub; core 0.2.14). Unchanged otherwise."""+ if not self.hidden:+ return obj+ return seeds_mod.scrub(obj, self.hidden["seed"], self.hidden["salt"])++ def extra_source_dirs(self):+ """The renderer code is part of the match only when it draws the players' images."""+ return []++ # ------------------------------------------------------------------ helpers+ def camera_job(self, seat, query=None):+ """Under the lock: the job that draws `seat`'s images, and the metadata for the reply."""+ if not self.cameras:+ return self.m.camera_job(seat)+ cams = self.m.cameras(seat, query)+ if not cams:+ return None, {}+ return {"state": self.m.render_state(), "cams": cams, "columns": self.columns}, {}++ def draw(self, seat, job):+ """Off the lock: render a camera job, an observation or reply images (in the seat's render worker if the+ sport has one, where a second job of the seat queues; in-process jobs are drawn one at a time)."""+ if job is None or self.finalized: # core 0.2.26: after finalization the render workers are closed+ return None+ if ("render", seat) in self.workers:+ try:+ return self.workers["render", seat].call(job, wait=True)+ except (BrokenPipeError, EOFError, ConnectionError, OSError):+ if self.finalized: # closed while this request ran: no images, never an error+ return None+ raise+ with self.render_lock:+ if self.cameras:+ if self.camera is None:+ self.camera = CameraWorker(players_scene(self.sport, self.plugin, self.cfg),+ self.renderer_name)+ t = time.monotonic()+ out = self.camera.draw_job(job)+ out["worker_s"] = time.monotonic() - t+ return out+ return self.sport.worker_call(None, "render", job)++ def reply_job(self, seat, cmd, info):+ """With the lock held, right after Match.apply(seat, cmd) returned `info`: the job that draws the images of+ the action's result for its reply (Match.reply_views, core 0.2.8), or None."""+ if not self.replies:+ return None+ return reply_job(self.m, self.m.reply_views(seat, cmd, info), self.columns)++ def reply_images(self, seat, job) -> dict:+ """Off the lock: draw a reply job -> the reply's `observation` (image_png_b64 + tiles, as /observe)."""+ out = self.draw(seat, job) or {}+ obs = {"of": "the result of this action", "render_wall_s": round(out.get("worker_s", 0.0), 3)}+ if out.get("png"):+ obs["image_png_b64"] = base64.b64encode(out["png"]).decode()+ for k in ("tiles", "note"):+ if out.get(k):+ obs[k] = out[k]+ with self.cond: # information only (not replayed): what the seat was shown+ st = self.seats[seat]+ st.count("reply_images")+ st.sample("reply_render_s", obs["render_wall_s"])+ self.ep.write("reply_images", seat=seat, k=self.m.k, tiles=len(obs.get("tiles") or []),+ png_bytes=len(out.get("png") or b""), render_wall_s=obs["render_wall_s"])+ return obs++ def observation(self, seat, query=None, since=None) -> dict:+ """With the lock held: the sport's whitelisted observation (+ the team channel: the teammates' messages after+ the client's read mark `since`, else the recent ones, and the side's newest seq; reading never consumes)."""+ obs, bad = filter_fields(self.m.observe(seat, query), self.allowed)+ if bad:+ self.errors.append({"where": "observation", "error": f"fields outside the whitelist: {bad}"})+ if self.channel.enabled:+ obs["team_messages"], obs["team_seq"] = self.channel.messages(seat, self.m.k, self.m.dt or 1.0, since)+ self.delivered(seat, obs["team_messages"])+ return obs++ def delivered(self, seat, rows):+ """With the lock held: log the teammates' messages `seat` gets for the first time (team_delivered)."""+ for d in self.channel.deliver(seat, rows, self.m.k):+ self.diag("team_delivered", **d)++ def team_since(self, body):+ """The client's team-channel read mark in a request body (`team_since`), None when absent (400 if invalid)."""+ return self.channel.since_arg((body or {}).get("team_since"))++ def team(self, seat, body):+ """POST /<seat>/team {"since": n}: the teammates' messages after seq n (read-only; never consumes)."""+ with self.cond:+ code, out = self.channel.page(seat, self.m.k, (body or {}).get("since"))+ if code == 200:+ self.delivered(seat, out["messages"])+ return code, out++ def say(self, seat, body):+ with self.cond:+ if self.phase == "over":+ return 409, {"error": "the match is over"}+ code, out = self.channel.say(seat, body.get("text"), self.m.k, self.m.dt or 1.0)+ if code == 200:+ self.ep.write("team", seat=seat, k=self.m.k, seq=out["sent"]["seq"], text=body.get("text"))+ return code, out++ def refused_invalid(self, seat, exc):+ """With the lock held: a malformed action (core.sport.parse_action) -- the player's own error, counted and+ logged (not replayed), never a technical failure."""+ st = self.seats[seat]+ st.count("refused_invalid")+ if "refused" in st.stats:+ st.count("refused")+ self.ep.write("refused_invalid", seat=seat, k=self.m.k, error=str(exc)[:200], cause=exc.cause or None)++ def query_guard(self, seat, query, fn):+ """With the lock held: run fn (it reads the sport's observation / cameras with the player's query). With a+ query, any exception is the player's error (Refused, HTTP 400; the sport refuses what it cannot read);+ without one it is a technical failure as before."""+ if query is None:+ return fn()+ try:+ return fn()+ except Refused:+ raise+ except Exception as exc: # noqa: BLE001+ err = Refused("invalid observation query (see /spec)")+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"+ self.ep.write("refused_query", seat=seat, k=self.m.k, cause=err.cause)+ raise err from exc++ def failure(self, where, exc):+ """A request's technical failure: an error of the trial (not valid) and the end of the match. After the match+ is finalized (core 0.2.26) the trial is decided: a late request's failure is only logged, never an error (a+ player that observes after the end once voided a finished, replayed match)."""+ if self.finalized:+ print(f"after finalization, {where}: {type(exc).__name__}: {str(exc)[:200]}", file=sys.stderr, flush=True)+ return+ with self.cond:+ self.errors.append({"where": where, "error": str(exc)[:300]})+ self.ep.write("error", where=where, error=str(exc)[:300])+ self.end("technical_error")++ def forfeit(self, seat, why):+ """With the lock held: a core decision, logged for the replay (and recorded in the world if it wants)."""+ self.forfeiting = seat+ self.ep.write("forfeit", k=self.m.k, seat=seat, why=why)+ self.m.forfeit(seat, why)++ def active_sides(self):+ return [s for s in self.cfg.side_list() if s not in self.retired]++ def lose(self, seat, why) -> bool:+ """With the lock held: `seat` loses (review time, clock, abandonment). With more than two sides the sport may+ let the match go on without that side (Match.retire); then True, else the match ends."""+ side = self.cfg.side_of(seat)+ if len(self.active_sides()) > 2 and self.m.retire(side, why):+ self.retired.append(side)+ for s in self.cfg.seats_of(side):+ self.seats[s].retired = True+ self.ep.write("retire", k=self.m.k, seat=seat, side=side, why=why)+ self.cond.notify_all()+ return True+ self.end(why, seat)+ return False++ def start_window(self) -> float:+ return float(os.environ.get("START_TIMEOUT_S", "1800"))++ def start_rule(self) -> dict:+ """The start window as /spec states it (both protocols)."""+ if len(self.cfg.side_list()) == 1:+ return {"window_s": self.start_window(),+ "rule": "the window opens when the match service starts; if you have not started when it closes, "+ "or your session ends before you start, you lose the match (no_show)"}+ return {"window_s": self.start_window(),+ "rule": "the match begins when every seat has started; the window opens with the first start; a side "+ "that has not started when it closes, or when every player session has ended, loses the match "+ "(no_show); if no side starts, the match does not count"}++ def absent_sides(self) -> list:+ """With the lock held: the sides (not retired) of which some seat has not started, in seat order."""+ absent = []+ for s in self.cfg.seats:+ side = self.cfg.side_of(s)+ if not self.seats[s].joined and side not in self.retired and side not in absent:+ absent.append(side)+ return absent++ def close_start_window(self, at="start_timeout") -> bool:+ """With the lock held, when the start window ran out in prepare (core rule 5, docs/framework_zh.md §9; core+ 0.2.2), or at the collect before the start (Service.no_show_at_collect, core 0.2.7; `at` names the logged+ row). A side is absent if any of its seats has not started. With two or more sides and at least one side+ present, every absent side loses ("no_show", a valid forfeit): with two sides the present side wins; with more,+ an absent side retires if the sport lets the others play on (Match.retire), else the match ends there. If no+ side is present the match is incomplete (a technical failure, no winner). A single-side format (whose window+ opens when the service starts) is a valid loss ("no_show", success 0). True = the match goes on with the+ present sides, who have all started."""+ absent = self.absent_sides()+ present = [x for x in self.active_sides() if x not in absent]+ self.ep.write(at, started={s: st.joined for s, st in self.seats.items()}, absent=absent)+ if not absent:+ return True+ if len(self.cfg.side_list()) == 1: # a single player (or team) who never started: a valid loss+ self.lose(next(s for s in self.cfg.seats if not self.seats[s].joined), "no_show")+ return False+ if not present:+ self.end("incomplete")+ return False+ for side in absent:+ seat = next(s for s in self.cfg.seats_of(side) if not self.seats[s].joined)+ if not self.lose(seat, "no_show"):+ return False+ return True++ def no_show_at_collect(self) -> bool:+ """With the lock held, at the collect (every player session has ended) before the match has started: the+ session end is a no-show, decided at once instead of when the start window closes (core rule 5,+ docs/framework_zh.md §9; core 0.2.7). Every side that has not started loses ("no_show", a valid forfeit;+ Service.close_start_window): a single side (alone or against a scripted opponent) has a valid loss (success 0);+ with two sides the present side wins; with more, the absent sides retire or the match ends as at the window.+ If no side has started (with two or more sides) nothing is decided here: the match does not count, as before+ (the caller ends it unfinished). True = the match ended; False = not before the start, no side present, or+ present sides would play on (more than two sides; the caller ends the match unfinished)."""+ if self.phase != "prepare" or self.in_play():+ return False+ if len(self.cfg.side_list()) > 1 and not [x for x in self.active_sides() if x not in self.absent_sides()]:+ return False+ return not self.close_start_window("collect_before_start")++ def in_play(self) -> bool:+ """With the lock held: the match has started (play has begun, or every seat has started and play is about to+ begin) and is not over."""+ if self.phase == "prepare":+ return all(st.joined for st in self.seats.values())+ return self.phase != "over"++ def abandon_single(self) -> bool:+ """With the lock held, at the collect (the verifier collects once every player session has ended): a single+ side (alone or against a scripted opponent) whose match has started and is not over loses, "abandoned", a+ valid loss (success 0), in both protocols (core rule 6, docs/framework_zh.md §9; core 0.2.6). Ending the+ session early (the player thinks it is done, gives up, hits the agent time limit or runs out of context) is the+ player's own problem; API and infrastructure failures are Harbor agent errors, rerun, not handled here. Before+ the start the session end is a no-show (Service.no_show_at_collect, core rule 5, core 0.2.7). True = the side+ lost."""+ if len(self.cfg.side_list()) != 1 or not self.in_play():+ return False+ self.lose(self.cfg.seats[0], "abandoned")+ return True++ def end(self, reason, forfeiting=None):+ with self.cond:+ if self.finalizing:+ return+ if forfeiting is not None:+ self.forfeit(forfeiting, reason)+ self.on_end()+ self.phase, self.reason, self.finalizing = "over", reason, True+ self.ep.write("end", k=self.m.k, reason=reason)+ self.bc.frame(force=True)+ self.bc.event("end", reason=reason)+ self.cond.notify_all()+ threading.Thread(target=self.finalize, daemon=True).start()++ def on_end(self):+ pass++ def finalize(self):+ try:+ subprocess.run([sys.executable, "-m", "core.episode", self.plugin, str(self.data)], check=True,+ timeout=float(os.environ.get("RO_REPLAY_TIMEOUT_S", "600")), cwd=ROOT.parent,+ stdout=subprocess.DEVNULL)+ self.replay = json.loads((self.data / "replay_check.json").read_text())+ except Exception as exc: # noqa: BLE001+ self.errors.append({"where": "replay", "error": str(exc)[:300]})+ with self.cond:+ self.finalized = True+ self.write_final()+ self.cond.notify_all()+ for w in self.workers.values():+ busy = w.lock.acquire(timeout=60) # a reply image may still be drawn after the last action+ w.close()+ if busy:+ w.lock.release()+ if os.environ.get("RCB_RENDER_VIDEO", "0") == "1": # after graded-ready: spectators only, never an error+ try:+ subprocess.run([sys.executable, "-m", "core.spectator", self.plugin, str(self.data)], check=True,+ timeout=float(os.environ.get("RCB_VIDEO_TIMEOUT_S", "300")), cwd=ROOT.parent,+ stdout=subprocess.DEVNULL)+ self.video_info = json.loads((self.data / "video.json").read_text())+ except Exception as exc: # noqa: BLE001+ self.video_info = {"video": False, "why": str(exc)[:200]}+ with self.cond:+ self.write_final()++ def outcome(self):+ return decide(self.m, self.forfeiting, self.reason, self.cfg.side_list(), self.cfg.side_of, self.retired)++ def continuous(self) -> dict | None:+ """With the lock held: the continuous score of every side (sport.toml [score], core/score.py; core 0.2.14). A+ side that forfeited or retired gets the declared forfeit value. A sport error here is a technical failure.+ None before the match is over (final.json is also written at the start and while it runs)."""+ if self.phase != "over":+ return None+ gone = list(self.retired)+ if self.forfeiting is not None and self.reason in FORFEIT_REASONS:+ gone.append(self.cfg.side_of(self.forfeiting))+ try:+ return score_mod.compute(self.m, self.decl, self.cfg.side_list(), gone)+ except Exception as exc: # noqa: BLE001+ if not any(e.get("where") == "continuous_score" for e in self.errors):+ self.errors.append({"where": "continuous_score", "error": str(exc)[:300]})+ return None++ def seed_proof(self) -> dict | None:+ """A hidden official seed's record (core/seeds.py; core 0.2.14): the commitment of the seed and the salt the+ runner handed over (RO_SEED, RO_SEED_SALT: sim service only), and the index the runner names (RO_SEED_INDEX,+ information only). Neither the seed nor the salt is written; the verifier finds the commitment in the+ registered cell of the match's format and level."""+ if not self.hidden:+ return None+ idx = os.environ.get("RO_SEED_INDEX", "")+ return {"commitment": self.hidden["commitment"], "index": int(idx) if idx.lstrip("-").isdigit() else None}++ def write_final(self):+ with self.cond:+ out = self.outcome()+ sha, cmds = self.m.state_digest(), self.ep.commands_sha()+ r = self.replay+ replay_ok = bool(r and r.get("state_sha") == sha and r.get("scores") == self.m.scores()+ and r.get("winner") == out.winner and r.get("commands_sha") == cmds+ and r.get("source_sha") == self.source_sha and r.get("k") == self.m.k)+ v = validity_fields(self.seats, self.need_meter)+ single = len(self.cfg.side_list()) == 1+ complete = self.reason == "match_over" or (self.reason in FORFEIT_REASONS and+ (out.winner is not None or single))+ valid = bool(self.finalized and complete and replay_ok and not self.errors+ and not any(v["meter_error"].values()) and not any(v["proxy_error"].values()))+ cont = self.continuous()+ valid = valid and not self.errors+ sport = self.m.final_fields()+ seats = {s: dict(st.stats) for s, st in self.seats.items()}+ for s, extra in (sport.pop("seats", None) or {}).items():+ seats.setdefault(s, {}).update(extra)+ final = {"sport": self.sport.name, "protocol": self.protocol, "revision": self.sport.revision,+ "versions": self.versions, "source_sha": self.source_sha, "cfg": self.cfg_json(),+ "seed": self.cfg_json()["seed"], "first": self.cfg.first, "action_level": self.cfg.action_level,+ "play": self.cfg.play, "format": self.cfg.format,+ "sides": {s: self.cfg.side_of(s) for s in self.cfg.seats}, "phase": self.phase,+ "reason": self.reason, "forfeiting": self.forfeiting, "retired": list(self.retired),+ "scores": self.m.scores(), "match_winner": out.winner, "decided_by": out.decided_by,+ "ranking": out.ranking, "solo": out.solo,+ "winner": out.winner if valid else None, "state_sha": sha, "commands_sha": cmds,+ "steps": self.m.k, "deterministic": replay_ok, "replay_scores": r.get("scores"),+ "finalized": self.finalized, "graded_ready": self.finalized, "valid_trial": valid,+ "technical_failure": not valid, "errors": self.errors, "seats": seats,+ "joined": {s: st.joined for s, st in self.seats.items()}, "reviews": self.reviews,+ "renderer": self.renderer_used(), "team_messages": len(self.channel.log),+ "video": bool(self.video_info.get("video")), "video_info": self.video_info, "elapsed_s": round(time.monotonic() - self.t0, 1), **v, **self.extra_final(),+ "continuous": cont, "seed_proof": self.seed_proof(),+ "sport_fields": sport}+ compat = {k: v for k, v in sport.items() if k not in final} # see COMPAT below+ if "score" not in final and "score" not in compat:+ compat["score"] = final["scores"]+ final.update(compat)+ final["compat"] = {"schema": COMPAT, "lifted": sorted(compat)}+ tmp = self.data / "final.json.tmp"+ if self.hidden: # the sport's fields (a sport may record its seed): scrubbed+ for k in {"sport_fields", "seats", "video_info", "errors", *compat}:+ if k in final:+ final[k] = self.public(final[k])+ tmp.write_text(json.dumps(final, default=float))+ tmp.replace(self.data / "final.json")++ def renderer_used(self):+ if not self.cameras:+ return "sport" # the sport draws its own images (a stage-0 wrapper)+ import renderers+ return self.renderer_name or renderers.DEFAULT++ def need_meter(self, seat) -> bool:+ return seat.mode == "model" and seat.joined++ def extra_final(self) -> dict:+ return {}++ def header_extra(self) -> dict:+ """Protocol-specific fields of the episode header (realtime: its timing, core 0.2.23)."""+ return {}++ def spec(self, seat, body=None):+ out = {"seat": seat, "side": self.cfg.side_of(seat), "protocol": self.protocol_id,+ "revision": self.sport.revision, "versions": self.versions, "action_level": self.cfg.action_level,+ "play": self.cfg.play, "format": self.cfg.format, **self.spec_core(),+ **public_spec(self.sport, self.cfg, seat, self.m, self.layer, self.decl)}+ if self.channel.enabled:+ out["team_channel"] = {"say": "POST /<seat>/say {'text': ...}", "max_bytes": self.channel.max_bytes,+ "min_interval_s": self.channel.min_interval_s,+ "max_messages": self.channel.max_messages,+ "read": ("observe / status show `team_messages` (from, seq, k, text) and `team_seq` "+ "(the newest seq); reading never consumes: send team_since = the "+ "largest seq you have (observe / wait body, status ?team_since=N) to get "+ "only newer ones, else you get the recent ones (the last "+ f"{self.channel.recent_s:g} game seconds, at most "+ f"{self.channel.recent_max}); POST /<seat>/team {{'since': n}} pages "+ "through the log"),+ "teammates": [s for s in self.cfg.seats_of(self.cfg.side_of(seat)) if s != seat]}+ return 200, outdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/spec.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/spec.pynew file mode 100644index 0000000000..a93e3fdcf4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/spec.py@@ -0,0 +1,32 @@+"""The sport's declarations (sport.toml next to its plugin.py, docs/framework_zh.md §4.2): data, read by the core+(observation whitelist, team channel, success line, timing), the generator, the checks and the documentation."""+from __future__ import annotations++import os+import tomllib+from pathlib import Path+++def load(plugin_path: str | os.PathLike) -> dict:+ p = Path(plugin_path)+ p = p / "sport.toml" if p.is_dir() else p.with_name("sport.toml")+ if not p.exists():+ return {}+ return tomllib.loads(p.read_text())+++def whitelist(decl: dict) -> set[str] | None:+ fields = (decl.get("observation") or {}).get("fields")+ return set(fields) if fields is not None else None+++def reaction_delay(decl: dict) -> int:+ """sport.toml [timing] reaction_delay_steps (core 0.2.18): the sport's declared reaction delay D in control+ steps, the same for every seat. In real time an act takes effect at step max(the next control-step boundary, s + D),+ where s is the step of the latest world state the service sent to the seat (any reply's `now`); the act is+ lowered at that step. The screening harness (tools/screen/play.py) plays with the same D. Not declared: 0, every+ act takes effect at the next control-step boundary (the rule before 0.2.18)."""+ v = (decl.get("timing") or {}).get("reaction_delay_steps", 0)+ if isinstance(v, bool) or not isinstance(v, int) or v < 0:+ raise ValueError(f"[timing] reaction_delay_steps must be an integer >= 0 (control steps), not {v!r}")+ return vdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/spectator.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/spectator.pynew file mode 100644index 0000000000..804621c1de--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/spectator.py@@ -0,0 +1,179 @@+"""What spectators get (docs/framework_zh.md §3.1, §4.3): the broadcast log and the replay video. Neither is ever read+back by the match, the replay or the grader; any failure here only switches the spectator output off.++Broadcast log (/data/broadcast.jsonl, RCB_BROADCAST=1): the unchanged legacy writer (broadcast_log.py, copied next+to core/ as spectator/broadcast_log.py by the generator) with the same lines as every legacy sport: a header, a frame+{"k", "q": qpos, ...extra} every `every` control steps (realtime) or after every action (turn), and the events run,+action, unit_over, end. A frame is Match.broadcast_frame() ({"q": [...], ...extra}) when the sport defines it, else+the qpos of Match.render_state().++Replay video (/data/replay.mp4, RCB_RENDER_VIDEO=1): after the match is graded-ready, a fresh process replays the+episode and draws the spectator camera with the spectator renderer (RO_VIDEO_RENDERER, default the players'+renderer; any renderer of renderers/ can re-render later from the episode). The camera: sport.toml+[broadcast] camera (a camera definition), else the first camera of the first seat. Frames of a non-default+renderer carry its label. python -m core.video is this module's video part: python -m core.spectator PLUGIN DIR.+The video is written as replay.part.mp4 and renamed when complete (core 0.2.13): replay.mp4 exists only after a+finished render, which is what the grader's video_rendered reads.++The spectator scene (core 0.2.4): the sport's presentation scene when it declares one (sports/<sport>/presentation/,+renderers/presentation: the match scene with fine visual meshes on the same bodies, same kinematics) and its assets+are present, else the match scene; RO_VIDEO_SCENE=match forces the match scene. A presentation scene is in the+simulator directory only when the sport declares it for its players' images (core 0.2.9: then a task's video shows+the players' scene, untagged: it is the competition picture); otherwise a task's video is the match scene and+re-renders from a checkout get the presentation. Every frame drawn from a spectators-only presentation scene carries+the presentation tag (renderer rule 6), whatever the renderer.+The players' images never use it (observe.CameraWorker).++A sport's own spectator scene (core 0.2.28): when the sport defines Sport.spectator_scene(cfg), the video draws that+scene (no presentation dressing) with Match.spectator_state() (default render_state()) - e.g. bodies the players'+scene leaves out (e.g. the vehicles, as mocap bodies, over a course scene without them). The players'+images and the replayed match never use either.+"""+from __future__ import annotations++import importlib.util+import json+import os+import sys+from pathlib import Path++from . import spec as spec_mod+from .sport import FINISHED, MatchBase, MatchConfig++ROOT = Path(__file__).resolve().parent+WRITER = ROOT.parent / "spectator" / "broadcast_log.py"+++def frame_of(m) -> dict | None:+ """The spectator frame of a match now: Match.broadcast_frame() if the sport defines it, else render_state's qpos."""+ if getattr(type(m), "broadcast_frame", None) is not MatchBase.broadcast_frame:+ return m.broadcast_frame()+ st = m.render_state() or {}+ return {"q": list(st["qpos"])} if "qpos" in st else None+++class Broadcast:+ def __init__(self, sport, cfg, m, decl, **header):+ self.m, self.log = m, None+ self.clean = lambda x: x # the service's scrub of a hidden seed (core/seeds.py)+ if os.environ.get("RCB_BROADCAST", "1") != "1" or not WRITER.exists():+ return+ try:+ spec = importlib.util.spec_from_file_location("ro_broadcast_log", WRITER)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ every = int((decl.get("broadcast") or {}).get("every", 2 if sport.protocol == "realtime" else 1))+ self.log = mod.BroadcastLog(every=every, path=os.path.join(os.environ.get("RCB_DATA", "/data"),+ "broadcast.jsonl"),+ sport=sport.name, mode=cfg.format, protocol=sport.protocol, dt=m.dt,+ seats=list(cfg.seats), sides={s: cfg.side_of(s) for s in cfg.seats}, **header)+ except Exception: # noqa: BLE001 (spectator output only)+ self.log = None++ def frame(self, force: bool = False):+ if self.log is None:+ return+ try:+ fr = frame_of(self.m)+ if fr is not None:+ fr = self.clean(dict(fr))+ self.log.frame(self.m.k, fr.pop("q", ()), force=force, **fr)+ except Exception: # noqa: BLE001+ self.log = None++ def event(self, ev: str, **fields):+ if self.log is not None:+ self.log.event(ev, self.m.k, **self.clean(fields))+++# ------------------------------------------------------------------------------------------------ the replay video+def video_camera(sport, cfg, m, decl) -> dict | None:+ cam = (decl.get("broadcast") or {}).get("camera")+ if cam:+ return dict(cam)+ cams = m.cameras(cfg.seats[0], None) if hasattr(m, "cameras") else []+ return dict(cams[0]) if cams else None+++def spectator_scene(sport, plugin: str, cfg):+ """(scene, what): the scene spectators see, what = "match" | "presentation" | "match (presentation unavailable:+ ...)". Spectator output only: a failure here falls back to the match scene."""+ if hasattr(sport, "spectator_scene") and os.environ.get("RO_VIDEO_SCENE", "presentation") != "match":+ try:+ return sport.spectator_scene(cfg), "spectator"+ except Exception as exc: # noqa: BLE001 (spectator output only: the match scene)+ return sport.scene(cfg), f"match (spectator scene unavailable: {exc})"+ base = sport.scene(cfg)+ if os.environ.get("RO_VIDEO_SCENE", "presentation") == "match":+ return base, "match"+ if not (Path(plugin).resolve().parent / "presentation" / "presentation.toml").is_file():+ return base, "match" # no presentation (in a task: unless declared for the players)+ try:+ from renderers import presentation+ scene = presentation.for_plugin(plugin, base)+ except Exception as exc: # noqa: BLE001 (missing assets, no tomllib, ...: the match scene)+ return base, f"match (presentation unavailable: {exc})"+ return (scene, "presentation") if scene is not None else (base, "match")+++def render_video(plugin: str, data: Path, fps: int = 10, hold_s: float = 1.0) -> dict:+ """Replay data/episode.jsonl and draw the spectator camera -> data/replay.mp4 (+ video.json)."""+ from .episode import header_cfg, load_plugin, read_rows, replay+ sport = load_plugin(plugin)+ decl = spec_mod.load(plugin)+ rows = read_rows(Path(data) / "episode.jsonl")+ cfg = header_cfg(next(r for r in rows if r["ev"] == "header"))+ m0 = sport.build(cfg)+ cam = video_camera(sport, cfg, m0, decl)+ if cam is None or not hasattr(sport, "scene"):+ return {"video": False, "why": "the sport defines no camera or scene for spectators"}+ import imageio.v2 as imageio+ import renderers+ from renderers.base import CameraDef+ name = os.environ.get("RO_VIDEO_RENDERER") or cfg.renderer or (decl.get("observation") or {}).get("renderer") \+ or renderers.DEFAULT+ scene, scene_what = spectator_scene(sport, plugin, cfg)+ R = renderers.load(name)(scene)+ cd = CameraDef.from_dict(cam)+ every = max(1, int(round(1.0 / (fps * m0.dt)))) if sport.protocol == "realtime" and m0.dt else 1+ repeat = max(1, int(round(fps * hold_s))) if sport.protocol == "turn" else 1+ out = Path(data) / "replay.mp4"+ part = out.with_suffix(".part.mp4") # renamed once complete: a killed render leaves no replay.mp4+ w = imageio.get_writer(str(part), fps=fps, codec="libx264", quality=7, macro_block_size=8)+ n = 0+ from renderers.label import frame_label+ tag = frame_label(R, scene) # None: the default renderer on the match scene (no tag)+ stamp = None+ if tag is not None:+ from renderers.label import stamp as stamp_fn+ stamp = stamp_fn++ def draw(match, *_):+ nonlocal n+ if sport.protocol == "realtime" and match.k % every and match.phase().state != FINISHED:+ return+ own = scene_what == "spectator" and hasattr(match, "spectator_state")+ img = R.render(match.spectator_state() if own else match.render_state(), [cd])[0]+ if stamp is not None:+ img = stamp(img, tag)+ for _ in range(repeat):+ w.append_data(img)+ n += 1++ try:+ replay(sport, rows, observer=draw)+ finally:+ w.close()+ part.replace(out)+ info = {"video": n > 0, "frames": n, "fps": fps, "renderer": name, "camera": cam["name"] if "name" in cam else "",+ "scene": scene_what, "label": tag}+ (Path(data) / "video.json").write_text(json.dumps(info))+ return info+++def main(argv):+ print(json.dumps(render_video(argv[0], Path(argv[1]))))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/sport.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/sport.pynew file mode 100644index 0000000000..02401a2a78--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/sport.py@@ -0,0 +1,464 @@+"""Contract ② (docs/framework_zh.md §4.2): the one interface between the core and a sport (sports/<sport>/).++A sport's plugin module exports SPORT. The core calls only the functions below and never names a sport; a sport never+imports another sport. A sport answers four questions, one group of functions each (10 required):++ world Sport.build(cfg) -> Match Match.step() -> events Match.state_digest() -> hex+ actions Match.schema(seat) Match.apply(seat, low_cmd) -> info+ optional high-level plugin: Sport.action_layer(level) -> ActionLayer whose lower() turns a high-level+ command into a low-level one (the episode log holds LOW-LEVEL commands only)+ referee Match.phase() -> Phase Match.scores() -> {side: n} Match.tiebreaks() -> [(name, rule)]+ optional: to_move(), forfeit(), resume(), retire(), ranking()+ observation Match.observe(seat, query) -> dict (own body + referee information, whitelisted in sport.toml)+ Match.cameras(seat, query) -> [camera definitions] (drawn by the task's renderer, renderers/)++Optional hooks have defaults in MatchBase; none of them is required by every sport, and the core never branches on a+sport. Stage-0 hooks (all optional): sides != seats (MatchConfig.sides, Match.entities: one act in flight per entity),+N sides with a classification (Match.ranking) and in-match retirement (Match.retire), a delayed effect+(ActionLayer.delay_steps), observation parameters (the `query` of observe/cameras), a team channel (core/channel.py,+declared in sport.toml) and a scored single format without an opponent (tiebreaks() == []).++Reply images (core 0.2.8, optional): Match.reply_views(seat, cmd, info) names the cameras (and optionally a short+strip of frames) that show the result of an action; the core snapshots them under the lock right after the action+took effect, draws them off the lock with the task's renderer (the path of the observation images) and attaches them+to the action's reply as `observation` (image_png_b64 + tiles, as /observe). In the turn protocol the core also tells+the sport whose review is due (Match.awaiting_review), so that a sport serving images only on turn can hold them+back from the other seats while the actor reviews.++Presentation (core 0.2.4, optional, spectators only): sports/<sport>/presentation/presentation.toml dresses the scene+of Sport.scene(cfg) for spectator renderers (renderers/presentation; e.g. fine visual meshes on a robot's bodies,+same kinematics). It is not part of the simulator directory and never reaches the players' images, unless the sport+declares `players` there (core 0.2.9): then the generator bundles it (and the models' files) into the simulator and+the players' images are drawn from it (core/observe.players_scene; a sport drawing its own images uses+renderers.players_model).+"""+from __future__ import annotations++import hashlib+import json+import math+from dataclasses import asdict, dataclass, field, fields+from typing import Any, Callable, Protocol+++@dataclass(frozen=True)+class MatchConfig:+ sport: str+ format: str # single | duel | team | multi (the sport declares which it supports)+ seats: tuple[str, ...] # e.g. ("A", "B"); the HTTP addresses /<seat>/<endpoint>+ seed: int+ first: str | None = None # the side that starts (serves / throws first; the rules say what that means)+ slowdown: float | None = None # realtime only+ level: int | None = None # scripted opponent level (single)+ action_level: str = "high" # high | low+ play: str = "program" # program | direct+ params: dict = field(default_factory=dict)+ sides: dict | None = None # seat -> side; default: every seat is its own side+ renderer: str | None = None # the renderer of the players' images (renderers/; None = the default)++ def side_of(self, seat: str) -> str:+ return (self.sides or {}).get(seat, seat)++ def side_list(self) -> list[str]:+ out: list[str] = []+ for s in self.seats:+ if self.side_of(s) not in out:+ out.append(self.side_of(s))+ return out++ def seats_of(self, side: str) -> list[str]:+ return [s for s in self.seats if self.side_of(s) == side]++ def to_json(self) -> dict:+ d = asdict(self)+ d["seats"] = list(self.seats)+ return d++ @staticmethod+ def from_json(d: dict) -> "MatchConfig":+ known = {f.name for f in fields(MatchConfig)}+ return MatchConfig(**{**{k: v for k, v in d.items() if k in known}, "seats": tuple(d["seats"])})+++PLAYING, UNIT_OVER, FINISHED = "playing", "unit_over", "finished"+++@dataclass+class Phase:+ state: str # PLAYING | UNIT_OVER | FINISHED+ review: tuple[str, ...] = () # seats that review before play resumes (realtime: usually all seats)+ reason: str = ""+++class Refused(Exception):+ """An action the core must refuse: HTTP `code` (400 bad body, 409 wrong time) with `message`."""++ def __init__(self, message: str, code: int = 400):+ super().__init__(message)+ self.code = code+ self.cause = "" # parse_action: the hidden exception (logs only)+++Tiebreak = tuple[str, Callable[["Match"], "str | None"]] # (name, rule) -> winning side or None (undecided)+++class Match(Protocol):+ k: int # [R] control steps (realtime) / actions (turn) so far+ dt: float # [R realtime] control step, seconds++ # world+ def step(self) -> list[dict]: ... # [R realtime] advance one control step; events+ def state_digest(self) -> str: ... # [R] hex digest of everything that affects the score+ # actions+ def schema(self, seat: str) -> dict: ... # [R] the low-level command types and ranges (/spec)+ def apply(self, seat: str, cmd: dict) -> dict: ... # [R] a LOW-LEVEL command takes effect now; info+ # referee+ def phase(self) -> Phase: ... # [R]+ def scores(self) -> dict[str, float]: ... # [R] by side (informational: tiebreaks decide)+ def tiebreaks(self) -> list[Tiebreak]: ... # [R] rulebook -> extra play -> last resort; [] = solo+ # observation+ def observe(self, seat: str, query: dict | None = None) -> dict: ... # [R] own body + referee information+ def cameras(self, seat: str, query: dict | None = None) -> list[dict]: ... # [R] camera definitions (renderers/)+++class MatchBase:+ """Defaults of every optional hook (a sport subclasses this and overrides what it needs)."""+ k = 0+ dt = 0.0+ awaiting_review = None # turn protocol, set by the core: the seat whose review+ # is due now (None: nobody's); never part of the digest++ # referee+ def resume(self) -> None: # leaving a review: frozen-time work (next serve ...)+ pass++ def to_move(self): # turn protocol: the seat whose turn it is+ return None++ def forfeit(self, seat, why) -> bool: # record a core decision inside the world (True)+ return False++ def retire(self, side, why) -> bool: # N sides: True = the match goes on without `side`+ return False++ def ranking(self): # N sides: the classification, best first+ return None++ def unit(self) -> int: # index of the current unit (acts of an old unit drop)+ return 0++ # actions+ def schema(self, seat) -> dict:+ return {}++ def entities(self, seat) -> tuple[str, ...]: # what a seat commands; one act in flight per entity+ return ()++ # observation+ def cameras(self, seat, query=None) -> list[dict]:+ return []++ def render_state(self) -> dict: # what a renderer needs to draw the scene now+ return {}++ def camera_job(self, seat): # a sport that draws its own images: (job, meta)+ return None, {}++ def reply_views(self, seat, cmd, info) -> dict | None:+ """The images of an action's result for its reply (core 0.2.8), or None. Called under the lock right after+ Match.apply(seat, cmd) returned `info` (realtime: only for an act without a delayed effect); it must not change+ the match, and what it returns must follow from the match state and (seat, cmd, info) alone, so that a replay+ can draw the same images (python -m core.episode PLUGIN DIR --reply N).+ {"frames": [{"cameras": [camera definitions, as cameras()],+ "state": render state (optional; default: render_state() now),+ "label": short text (optional, e.g. "-200 ms"; shown in the tiles)}, ...],+ "order": "frame" (default: frame after frame) | "camera" (camera after camera: one strip per camera),+ "columns": tiles per row (default: sport.toml [observation] columns),+ "note": one line for the player (optional)}+ Drawn like the observation images: the task's renderer, the match scene (never a presentation scene),+ sport.toml [observation] frame_budget_ms for the whole reply image."""+ return None++ def final_fields(self) -> dict: # sport fields for final.json+ return {}++ def continuous_score(self): # sport.toml [score] from = "hook": {side: number},+ return None # larger is better (core/score.py, core 0.2.14)++ def broadcast_frame(self): # spectator frame (never read back)+ return None+++class ActionLayer(Protocol):+ level: str # "high" | "low"+ worker: str | None # Sport worker kind that runs prepare(), or None+ delay_steps: int # realtime: the effect is delay_steps after lowering++ def parse(self, seat: str, body: dict, match: Match, ctx: dict) -> dict: ...+ # validate a request body (raise Refused); ctx = core facts at the request (e.g. both chess clocks), which the+ # plugin may copy into the command so that replay sees them. Realtime: parse runs off the world lock and+ # Match.apply later, at the effect step, where the core checks again only that the unit (Match.unit) is the same,+ # so apply re-checks whatever else may have changed meanwhile (the phase, whose turn, a body's state) and returns+ # {"rejected": why} (counted) for a command that no longer holds+ def snapshot(self, seat: str, cmd: dict, match: Match, ordinal: int) -> Any: ... # under the lock, for prepare+ def prepare(self, job: Any) -> Any: ... # off the lock (in `worker` if set); expensive planning+ def lower(self, seat: str, cmd: dict, prepared: Any, match: Match) -> tuple[dict, dict]: ...+ # at the effect boundary, cheap: -> (low-level command for Match.apply, info for the reply)+ def reply(self, seat: str, cmd: dict, info: dict, match: Match) -> dict: ...+++class LowLayer:+ """The identity layer: the request body, validated by `validate(seat, body, match, ctx) -> cmd`, is the command."""+ level = "low"+ worker = None+ delay_steps = 0++ def __init__(self, validate):+ self._validate = validate++ def schema(self, match, seat): # what /spec shows of this layer's commands+ return match.schema(seat)++ def parse(self, seat, body, match, ctx):+ return self._validate(seat, body, match, ctx)++ def snapshot(self, seat, cmd, match, ordinal):+ return None++ def prepare(self, job):+ return None++ def lower(self, seat, cmd, prepared, match):+ return cmd, {}++ def reply(self, seat, cmd, info, match):+ return info+++def check_command(schema: dict, body: dict) -> dict:+ """Validate a request body against a Match.schema() and return the clean command (raises Refused).++ schema = {TYPE: {FIELD: {"type": "number"|"integer"|"boolean"|"enum"|"vector", "min", "max", "values", "len",+ "unit", "doc", "default"}}}; the command is {"type": TYPE, FIELD: value, ...}."""+ if not isinstance(body, dict):+ raise Refused("the action must be a JSON object")+ kind = body.get("type")+ if kind not in schema:+ raise Refused(f"unknown action type {kind!r}; one of {sorted(schema)}")+ out: dict = {"type": kind}+ spec = schema[kind]+ extra = sorted(set(body) - set(spec) - {"type", "entity"})+ if extra:+ raise Refused(f"unknown field(s) {extra} for {kind}")+ for name, f in spec.items():+ if name not in body:+ if "default" in f:+ out[name] = f["default"]+ continue+ raise Refused(f"{kind} needs {name}")+ out[name] = _value(name, f, body[name])+ if "entity" in body:+ out["entity"] = str(body["entity"])+ return out+++def _value(name, f, v):+ t = f.get("type", "number")+ if t == "boolean":+ if not isinstance(v, bool):+ raise Refused(f"{name} must be true or false")+ return v+ if t == "enum":+ if v not in f["values"]:+ raise Refused(f"{name} must be one of {f['values']}")+ return v+ if t == "vector":+ if not isinstance(v, list) or len(v) != f["len"]:+ raise Refused(f"{name} must be a list of {f['len']} numbers")+ return [_number(f"{name}[{i}]", f, x) for i, x in enumerate(v)]+ x = _number(name, f, v)+ if t == "integer":+ if x != int(x):+ raise Refused(f"{name} must be an integer")+ return int(x)+ return x+++def _number(name, f, v):+ if isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, int) and v.bit_length() > 60) or \+ not math.isfinite(v):+ raise Refused(f"{name} must be a finite number")+ lo, hi = f.get("min", -math.inf), f.get("max", math.inf)+ if not lo <= v <= hi:+ raise Refused(f"{name} must be in [{lo}, {hi}]")+ return round(float(v), f.get("digits", 6))+++# ------------------------------------------------------------------ request validation (core 0.2.11)+# Every request body is checked before an endpoint reads it (check_body), and every act body against the action+# layer's published schema before the layer parses it (check_action). A body that fails, or that makes the layer's+# parse raise ANY exception, is the player's own error: refused (HTTP 400, counted), never a technical failure.+BODY_MAX_DEPTH = 10 # nesting of lists / objects (the body object is depth 1)+BODY_MAX_ITEMS = 4096 # elements of one list, keys of one object+BODY_MAX_STR = 8192 # characters of one string (keys included)+BODY_MAX_ABS = 1e15 # |number|: no action of any sport needs more (and a huge integer overflows a float)+TYPE_MAX_STR = 64 # characters of the action type+++def check_body(value, depth: int = 1) -> None:+ """Generic sanity of a decoded JSON request body (raises Refused): finite, bounded numbers; bounded strings, list+ lengths and nesting."""+ if depth > BODY_MAX_DEPTH:+ raise Refused(f"the request is nested deeper than {BODY_MAX_DEPTH} levels")+ if value is None or isinstance(value, bool):+ return+ if isinstance(value, str):+ if len(value) > BODY_MAX_STR:+ raise Refused(f"strings are limited to {BODY_MAX_STR} characters")+ return+ if isinstance(value, int):+ if value.bit_length() > 60 or abs(value) > BODY_MAX_ABS:+ raise Refused(f"numbers are limited to +-{BODY_MAX_ABS:g}")+ return+ if isinstance(value, float):+ if not math.isfinite(value) or abs(value) > BODY_MAX_ABS:+ raise Refused(f"numbers must be finite and within +-{BODY_MAX_ABS:g}")+ return+ if isinstance(value, (list, dict)):+ if len(value) > BODY_MAX_ITEMS:+ raise Refused(f"lists and objects are limited to {BODY_MAX_ITEMS} items")+ for k in value if isinstance(value, dict) else ():+ if not isinstance(k, str) or len(k) > BODY_MAX_STR:+ raise Refused("object keys must be strings")+ for x in value.values() if isinstance(value, dict) else value:+ check_body(x, depth + 1)+ return+ raise Refused("unsupported JSON value")+++def _is_num(v) -> bool:+ return not isinstance(v, bool) and isinstance(v, (int, float))+++def _lens(spec_len) -> set | None:+ """A field's declared length: an int, or a text such as "1 or 2" (None: not declared)."""+ if isinstance(spec_len, int) and not isinstance(spec_len, bool):+ return {spec_len}+ if isinstance(spec_len, str):+ return {int(x) for x in spec_len.replace(",", " ").split() if x.isdigit()} or None+ return None+++def _check_field(kind: str, name: str, f, v) -> None:+ """The shape of one declared field (ranges and meaning stay with the layer's parse)."""+ if not isinstance(f, dict):+ return+ t, where = f.get("type", "number"), f"{kind}.{name}"+ if t in ("number", "integer"):+ if not _is_num(v):+ raise Refused(f"{where} must be a number")+ elif t == "boolean":+ if not isinstance(v, bool):+ raise Refused(f"{where} must be true or false")+ elif t == "enum":+ if isinstance(v, (list, dict)):+ raise Refused(f"{where} must be one of {f.get('values')}")+ elif t == "vector":+ lens = _lens(f.get("len"))+ if not isinstance(v, list) or (lens and len(v) not in lens) or not all(_is_num(x) for x in v):+ raise Refused(f"{where} must be a list of {f.get('len', 'some')} numbers")+ elif t == "rows":+ lens, top = _lens(f.get("len")), f.get("max_rows")+ if not isinstance(v, list) or (isinstance(top, int) and len(v) > top) or not all(+ isinstance(r, list) and (not lens or len(r) in lens) and all(_is_num(x) for x in r) for r in v):+ raise Refused(f"{where} must be a list of rows of {f.get('len', 'some')} numbers"+ + (f", at most {top} rows" if isinstance(top, int) else ""))+ elif t == "list":+ if not isinstance(v, list):+ raise Refused(f"{where} must be a list")+ elif t == "object":+ if not isinstance(v, dict):+ raise Refused(f"{where} must be an object")+ keys = f.get("keys")+ if isinstance(keys, (list, tuple)) and set(v) - set(keys):+ raise Refused(f"{where}: unknown key(s) {sorted(set(v) - set(keys))[:8]}; the keys are {list(keys)}")+++def check_action(schema, body) -> None:+ """An act body against the action layer's published schema, before the layer parses it (raises Refused). The+ type, if given, must be a short string; for a type the schema names, each declared field that is present must+ have its shape (number, boolean, scalar enum value, vector / rows lengths, list, object keys). Unknown types and+ fields, ranges and defaults stay with the layer's parse (a layer may take an implicit type)."""+ if not isinstance(body, dict):+ raise Refused("the action must be a JSON object")+ kind = body.get("type")+ if kind is not None and (not isinstance(kind, str) or len(kind) > TYPE_MAX_STR):+ raise Refused(f"type must be a string of at most {TYPE_MAX_STR} characters")+ spec = schema.get(kind) if isinstance(schema, dict) and kind is not None else None+ if isinstance(spec, dict):+ for name, f in spec.items():+ if name in body:+ _check_field(kind, name, f, body[name])+++def parse_action(layer, seat: str, body, match, ctx: dict):+ """What the core runs for every act (and core.local for built-in players): check_body, check_action against the+ layer's schema (what /spec shows), then layer.parse. ANY exception on the way is the player's own error: Refused+ (HTTP 400); a malformed action never ends a match as a technical failure. The exception's text is not shown to+ the player; the caller may log it (`Refused.cause`). A seat without entities (Match.entities) may not name one+ (core 0.2.13): realtime acts are one in flight per (seat, entity)."""+ try:+ check_body(body)+ check_action(layer.schema(match, seat) if hasattr(layer, "schema") else {}, body)+ if "entity" in body and not match.entities(seat):+ raise Refused("unknown field entity: this seat commands no entities")+ return layer.parse(seat, body, match, ctx)+ except Refused:+ raise+ except Exception as exc: # noqa: BLE001+ err = Refused("invalid action: the action layer could not read it (see /spec for the command schema)")+ err.cause = f"{type(exc).__name__}: {str(exc)[:200]}"+ raise err from exc+++class SchemaLayer(LowLayer):+ """The default low level: the body is checked against Match.schema(seat); `ctx_keys` copies core facts (e.g. the+ chess clocks) into the command so that the replay sees them."""++ def __init__(self, ctx_keys: tuple[str, ...] = ()):+ super().__init__(None)+ self.ctx_keys = ctx_keys++ def parse(self, seat, body, match, ctx):+ cmd = check_command(match.schema(seat), body)+ ents = tuple(match.entities(seat))+ if ents and cmd.get("entity", ents[0]) not in ents:+ raise Refused(f"entity must be one of {list(ents)}")+ if ents:+ cmd.setdefault("entity", ents[0])+ for k in self.ctx_keys:+ cmd[k] = ctx.get(k)+ return cmd+++class Sport(Protocol):+ name: str+ protocol: str # "realtime" | "turn"+ revision: str # bump on any change that alters play+ source_dirs: list[str] # whose files enter source_sha (the plugin dir; the core adds itself)++ def build(self, cfg: MatchConfig) -> Match: ...+ def action_layer(self, level: str) -> ActionLayer: ...+ def spec(self, cfg: MatchConfig, seat: str, match: Match) -> dict: ...+ # optional: the scene for renderers, worker processes (render / plan), built-in players+ def scene(self, cfg: MatchConfig): ... # renderers.base.Scene (needed when cameras() is used);+ # the MATCH scene: the base of the presentation scene+ # (sports/<s>/presentation) and the players' images+ # unless that declares `players`+ def worker_init(self, kind: str, seat: str, cfg: MatchConfig) -> Any: ...+ def worker_call(self, obj: Any, kind: str, job: Any) -> dict: ...+ def players(self) -> dict: ... # {name: factory(spec, seat, seed) -> built-in player}+++def sha_json(value) -> str:+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), default=float).encode()).hexdigest()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/testkit.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/testkit.pynew file mode 100644index 0000000000..9c96c43f51--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/testkit.py@@ -0,0 +1,648 @@+"""The generic test suite every sport passes (tools/check stages 2 and 4; docs/framework_zh.md §9 sport rules). It+loads the sport like the core does and plays in-process matches of the sport's built-in players (core/local.py).++ python3 -m core.testkit tests PLUGIN [--json OUT] stage 2: the generic tests + the sport's exploit tests+ python3 -m core.testkit fairness PLUGIN [--json OUT] stage 4: first-order and seat advantage of built-ins++Tests (each one result row {name, ok, detail}):+ determinism the same match twice in-process gives the same digest; its episode replays in a fresh process+ (python -m core.episode) to the same digest, scores and winner, within replay_timeout(decl)+ (core 0.2.17: sport.toml [timing] replay_timeout_s when it is above 1800 s, else 1800 s)+ no_draw every finished match of every format with two or more sides has a winner; the tiebreak names+ are sport.toml [tiebreaks] order+ mirror_symmetry sport.toml [fairness] mirror = "exact": swapping seats and the first order swaps the result and+ a player sees exactly the same observations+ whitelist no observation field outside sport.toml [observation] fields in any match; the core drops an+ injected field and records the error+ observe_is_pure observe / cameras / render_state / reply_views never change the state digest+ refuses_bad malformed or out-of-range actions are refused (HTTP 400) and change nothing+ fuzz_actions every format and action level: hostile bodies (huge integers, NaN / inf, wrong types, nested+ junk, oversize strings and lists) through the core's parse_action are refused, raise nothing but+ Refused and change nothing; junk observation queries change nothing (core 0.2.11)+ frame_budget the task renderer draws one observation within [observation] frame_budget_ms; a sport with+ reply images (Match.reply_views) also draws the first action's reply image within it+ exploit:<id> every [[exploits]] entry names a test in tests/test_*.py, and that test passes+ solo_quit every single-side format: a session that ends mid-match (the core's forfeit "abandoned" after+ some play, core 0.2.6) is a loss with no winner, and its episode replays in a fresh process to the+ same digest and decision+ prestart_no_show every format of one or two sides: a side that never started (the core's forfeit "no_show" at+ step 0, at the start window or at a collect before the start, core 0.2.7) replays to a loss: no+ winner for a single side, the other side's win in a duel, with no play (k = 0); the sport's+ forfeit hook may end its world (core 0.2.12: the core decides a forfeit first, whatever the phase)+ seed_private information (core 0.2.14): where the sport itself shows the seed (observe, /spec, final fields);+ the core scrubs them in hidden-seed matches+ continuous_score sport.toml [score] (core 0.2.14): well formed; the values of every no_draw match are finite, within+ its range and not below the forfeit value; a side that never started gets the forfeit value+"""+from __future__ import annotations++import importlib.util+import json+import math+import os+import subprocess+import sys+import tempfile+import time+import traceback+from pathlib import Path++from . import local+from . import score as score_mod+from . import spec as spec_mod+from .episode import load_plugin+from .observe import filter_fields, players_scene+from .service import own_hook+from .sport import FINISHED, MatchConfig, Refused, check_body, parse_action++ROOT = Path(__file__).resolve().parent+REPLAY_TIMEOUT_S = 1800 # the fresh-process replay of a test match, unless the sport declares a longer one+++def replay_timeout(decl) -> float:+ """The limit of the tests' fresh-process replays (determinism, solo_quit), core 0.2.17: sport.toml [timing]+ replay_timeout_s when it is longer than REPLAY_TIMEOUT_S (a long match, e.g. 600 s of play, replays in more than+ 1800 s), else REPLAY_TIMEOUT_S. Never shorter than the 1800 s of cores <= 0.2.16: the task's own limit (default+ 600 s, tools/sportlib.py post_match_timeouts) does not tighten the check."""+ t = (decl.get("timing") or {}).get("replay_timeout_s")+ return max(float(REPLAY_TIMEOUT_S), float(t)) if t else float(REPLAY_TIMEOUT_S)+++def fresh_replay(plugin, data, decl) -> tuple[dict, str]:+ """Replay the episode in `data` in a fresh process (python -m core.episode): (replay_check.json or {}, stderr)."""+ limit = replay_timeout(decl)+ try:+ p = subprocess.run([sys.executable, "-m", "core.episode", plugin, data], cwd=ROOT.parent,+ capture_output=True, text=True, timeout=limit)+ except subprocess.TimeoutExpired:+ return {}, f"the fresh-process replay took more than {limit:.0f} s (sport.toml [timing] replay_timeout_s)"+ return (json.loads((Path(data) / "replay_check.json").read_text()) if p.returncode == 0 else {}), p.stderr+++def configs(decl, sport, seeds=(1, 2, 3)):+ """One MatchConfig per (format, action level, seed, first side) the sport declares."""+ levels = (decl.get("modes") or {}).get("action_levels", ["high"])+ for fmt, f in (decl.get("formats") or {}).items():+ firsts = f.get("first") or [f["seats"][0]]+ for level in levels:+ for seed in seeds:+ for first in firsts:+ yield MatchConfig(sport=sport.name, format=fmt, seats=tuple(f["seats"]), seed=seed, first=first,+ action_level=level, sides=f.get("sides"))+++class Recorder:+ """Wraps a built-in player and keeps what it saw (the state part of each view)."""++ def __init__(self, inner):+ self.inner, self.seen = inner, []++ def act(self, view):+ self.seen.append({k: v for k, v in view["state"].items() if k != "seat"})+ return self.inner.act(view)+++def row(name, ok, detail=""):+ return {"name": name, "ok": bool(ok), "detail": detail if isinstance(detail, str) else json.dumps(detail)[:600]}+++def t_determinism(sport, plugin, decl):+ out = []+ cfg = next(configs(decl, sport, seeds=(7,)))+ names = {s: "reference" for s in cfg.seats}+ with tempfile.TemporaryDirectory() as tmp:+ a = local.play(sport, cfg, local.make_players(sport, cfg, names, plugin=plugin), data=tmp, plugin=plugin)+ b = local.play(sport, cfg, local.make_players(sport, cfg, names, plugin=plugin), plugin=plugin)+ out.append(row("determinism:in_process", a["digest"] == b["digest"] and a["scores"] == b["scores"],+ {"a": a["digest"][:16], "b": b["digest"][:16]}))+ rc, err = fresh_replay(plugin, tmp, decl)+ ok = rc.get("state_sha") == a["digest"] and rc.get("scores") == a["scores"] and rc.get("winner") == a["winner"]+ out.append(row("determinism:fresh_process_replay", ok, rc and {k: rc[k] for k in ("scores", "winner", "k")}+ or err[-400:]))+ return out+++def t_no_draw_and_whitelist(sport, plugin, decl, n=4):+ order = (decl.get("tiebreaks") or {}).get("order")+ bad, leaks, played, names_ok, cont = [], set(), 0, True, []+ checks = (decl.get("players") or {}).get("check", ["random"])+ for cfg in configs(decl, sport, seeds=tuple(range(1, n + 1))):+ for pol in checks + ["reference"]:+ names = {s: (pol if i % 2 == 0 else "reference") for i, s in enumerate(cfg.seats)}+ r = local.play(sport, cfg, local.make_players(sport, cfg, names, plugin=plugin), plugin=plugin)+ played += 1+ leaks |= set(r["observation_leaks"])+ if r.get("continuous"):+ cont.append(r["continuous"]["by_side"])+ if len(cfg.side_list()) >= 2 and r["finished"] and r["winner"] is None:+ bad.append({"cfg": cfg.to_json(), "scores": r["scores"]})+ if not r["finished"]:+ bad.append({"cfg": cfg.to_json(), "unfinished": True})+ m = sport.build(cfg)+ if order is not None and len(cfg.side_list()) >= 2 and [x for x, _ in m.tiebreaks()] != order:+ names_ok = False+ out = [row("no_draw", not bad, bad[:3] or f"{played} matches, every one decided"),+ row("tiebreaks_declared", names_ok and order is not None or not any(+ len(f["seats"]) > 1 for f in decl.get("formats", {}).values()),+ f"sport.toml [tiebreaks] order = {order}"),+ row("whitelist:no_leak", not leaks, sorted(leaks) or "every observation within the whitelist")]+ sd = score_mod.declaration(decl)+ if sd is not None:+ vals = [v for by in cont for v in by.values()]+ lo, hi = (sd.get("range") or [-math.inf, math.inf])+ out.append(row("continuous_score:values", vals and all(lo <= v <= hi for v in vals)+ and all(sd["forfeit"] <= v for v in vals),+ f"{len(vals)} values in [{min(vals, default=None)}, {max(vals, default=None)}], range "+ f"{sd.get('range')}, forfeit {sd['forfeit']} (must be the worst)"))+ cfg = next(configs(decl, sport))+ m = sport.build(cfg)+ allowed = spec_mod.whitelist(decl)+ obs = dict(m.observe(cfg.seats[0], None), _secret_state=[1, 2, 3])+ kept, dropped = filter_fields(obs, allowed)+ out.append(row("whitelist:declared", allowed is not None, "sport.toml [observation] fields"))+ out.append(row("whitelist:enforced", "_secret_state" not in kept and dropped == ["_secret_state"], dropped))+ return out+++def t_mirror(sport, plugin, decl, seeds=(1, 2, 3, 4)):+ if (decl.get("fairness") or {}).get("mirror") != "exact":+ return [row("mirror_symmetry", True, "skipped: [fairness] mirror is not \"exact\" (the fairness check covers it)")]+ out = []+ for fmt, f in decl.get("formats", {}).items():+ seats = f["seats"]+ if len(seats) != 2:+ continue+ for level in (decl.get("modes") or {}).get("action_levels", ["high"]):+ for seed in seeds:+ res = []+ for swap in (False, True):+ cfg = MatchConfig(sport=sport.name, format=fmt, seats=tuple(seats), seed=seed,+ first=seats[1] if swap else seats[0], action_level=level)+ pol = ["reference", "random"][::-1] if swap else ["reference", "random"]+ ps = {s: Recorder(local.make_players(sport, cfg, {s: n}, plugin=plugin, seed=seed)[s])+ for s, n in zip(seats, pol)}+ r = local.play(sport, cfg, ps, plugin=plugin)+ res.append((r, ps))+ (r1, p1), (r2, p2) = res+ a, b = seats+ swapped = r1["scores"] == {a: r2["scores"][b], b: r2["scores"][a]} and \+ ({a: b, b: a}.get(r1["winner"]) == r2["winner"])+ same_view = p1[a].seen == p2[b].seen and p1[b].seen == p2[a].seen+ out.append(row(f"mirror_symmetry:{fmt}:{level}:seed{seed}", swapped and same_view,+ {"scores": [r1["scores"], r2["scores"]], "same_observations": same_view}))+ return out or [row("mirror_symmetry", True, "no two-seat format")]+++def t_pure(sport, plugin, decl):+ cfg = next(c for c in configs(decl, sport) if len(c.seats) >= 1)+ m = sport.build(cfg)+ ps = local.make_players(sport, cfg, {s: "reference" for s in cfg.seats}, plugin=plugin)+ layer = sport.action_layer(cfg.action_level)+ views = local.Views(sport, cfg, m, decl, True, plugin)+ bad = []+ for _ in range(4):+ if m.phase().state == FINISHED:+ break+ seat = m.to_move() or cfg.seats[0]+ d0 = m.state_digest()+ for s in cfg.seats:+ m.observe(s, None)+ m.cameras(s, None)+ m.render_state()+ v = views.view(seat, {})+ if m.state_digest() != d0:+ bad.append("observe/cameras/render_state changed the digest")+ if sport.protocol == "turn":+ low, _ = layer.lower(seat, layer.parse(seat, ps[seat].act(v), m, {"clock_left_s": {}}), None, m)+ info = m.apply(seat, low) or {}+ d1 = m.state_digest()+ m.reply_views(seat, low, info)+ if m.state_digest() != d1:+ bad.append("reply_views changed the digest")+ else:+ m.step()+ return [row("observe_is_pure", not bad, bad or "digest unchanged by observations")]+++def bad_bodies(schema: dict):+ kind, fields = next(iter(schema.items()))+ good = {k: (f.get("min", 0) + f.get("max", 0)) / 2 if f.get("type", "number") == "number" else f.get("default")+ for k, f in fields.items()}+ yield {"type": "no-such-action"}+ yield {"type": kind}+ for k, f in fields.items():+ if f.get("type", "number") in ("number", "integer"):+ for v in (float("nan"), "1", f.get("max", 1e9) + 1e6 if "max" in f else None):+ if v is not None:+ yield {"type": kind, **good, k: v}+ yield {"type": kind, **good, "unexpected_field": 1}+++def t_refuses(sport, plugin, decl):+ out = []+ for level in (decl.get("modes") or {}).get("action_levels", ["high"]):+ cfg = next(c for c in configs(decl, sport) if c.action_level == level)+ m = sport.build(cfg)+ layer = sport.action_layer(level)+ seat = m.to_move() or cfg.seats[0]+ schema = layer.schema(m, seat) if hasattr(layer, "schema") else {}+ if not schema:+ out.append(row(f"refuses_bad:{level}", True, "skipped: the layer publishes no schema"))+ continue+ d0, leaked = m.state_digest(), []+ for body in bad_bodies(schema):+ try:+ layer.parse(seat, body, m, {"clock_left_s": {}})+ leaked.append(body)+ except Refused:+ pass+ out.append(row(f"refuses_bad:{level}", not leaked and m.state_digest() == d0,+ [str(b) for b in leaked][:3] or "every malformed action refused, nothing changed"))+ return out+++FUZZ_ALWAYS_BAD = { # the core refuses these in any field of any action (core 0.2.11)+ "inf": float("inf"), "-inf": float("-inf"), "nan": float("nan"), "hugeint": 10 ** 400, "-hugeint": -10 ** 400,+ "int2^70": 2 ** 70, "1e300": 1e300, "deep": json.loads("[" * 30 + "]" * 30), "longstr": "x" * 20000,+ "longlist": [0.1] * 5000}+FUZZ_WRONG_TYPE = {"null": None, "true": True, "str": "x", "list": [1, 2, 3], "nested": [[1], [2]], "dict": {"a": 1},+ "empty_list": [], "dict_nested": {"a": {"b": [1, {"c": None}]}}}+FUZZ_QUERIES = ({"camera": float("inf")}, {"camera": {"a": 1}}, {"camera": 10 ** 400}, {"aim": "x"}, {"aim": [1]},+ {"x": [[1]]}, {"view": None}, {"camera": "x" * 5000})+++def fuzz_bodies(schema: dict):+ """(name, body, must_refuse): malformed act bodies for every action type and field of a layer's schema."""+ for junk in ([], "x", 5, None, [{"type": "x"}]):+ yield f"body={junk!r}", junk, True+ for v in (None, [], {}, ["x"], 10 ** 400, float("nan"), "x" * 5000, True, 3):+ yield f"type={str(v)[:12]}", {"type": v}, v is not None+ for kind, fields in (schema or {}).items():+ fields = fields if isinstance(fields, dict) else {}+ good = {}+ for k, f in fields.items():+ f = f if isinstance(f, dict) else {}+ if f.get("type", "number") in ("number", "integer"):+ lo, hi = f.get("min", 0), f.get("max", 0)+ good[k] = (lo + hi) / 2 if all(isinstance(x, (int, float)) for x in (lo, hi)) else 0+ elif "default" in f:+ good[k] = f["default"]+ for k in [*fields, "type", "entity", "unexpected_field"]:+ for name, v in FUZZ_ALWAYS_BAD.items():+ yield f"{kind}.{k}={name}", {"type": kind, **good, k: v}, True+ for name, v in FUZZ_WRONG_TYPE.items():+ yield f"{kind}.{k}={name}", {"type": kind, **good, k: v}, k == "type" and v is not None+++def t_fuzz(sport, plugin, decl):+ """Malformed actions and observation queries, through the core's own path (core.sport.parse_action, the same+ function the HTTP service runs): every always-bad body is refused, nothing raises anything but Refused, nothing+ changes the state digest. Every format and action level."""+ out, seen = [], set()+ for cfg in configs(decl, sport, seeds=(1,)):+ if (cfg.format, cfg.action_level) in seen:+ continue+ seen.add((cfg.format, cfg.action_level))+ m = sport.build(cfg)+ layer = sport.action_layer(cfg.action_level)+ seat = m.to_move() or cfg.seats[0]+ schema = layer.schema(m, seat) if hasattr(layer, "schema") else {}+ d0, bad, n = m.state_digest(), [], 0+ for name, body, must in fuzz_bodies(schema):+ n += 1+ try:+ parse_action(layer, seat, body, m, {"clock_left_s": {s: 600.0 for s in cfg.seats}})+ if must:+ bad.append(f"{name}: accepted")+ except Refused:+ pass+ except Exception as exc: # noqa: BLE001+ bad.append(f"{name}: {type(exc).__name__} escaped parse_action")+ for q in FUZZ_QUERIES: # the core: check_body, then any exception with a query is a refusal+ n += 1+ try:+ check_body({"query": q})+ m.observe(seat, q)+ m.cameras(seat, q)+ except Exception: # noqa: BLE001+ pass+ if m.state_digest() != d0:+ bad.append("the state digest changed")+ out.append(row(f"fuzz_actions:{cfg.format}:{cfg.action_level}", not bad,+ bad[:4] or f"{n} malformed bodies and queries refused, nothing changed"))+ return out+++def t_budget(sport, plugin, decl):+ obs = decl.get("observation") or {}+ budget = obs.get("frame_budget_ms")+ cfg = next(configs(decl, sport))+ m = sport.build(cfg)+ pres = Path(plugin).resolve().parent / "presentation"+ players = None+ if (pres / "presentation.toml").is_file():+ from renderers import presentation+ players = presentation.players_meshes(pres)+ if not own_hook(m, "cameras") or own_hook(m, "camera_job"):+ if players is None:+ return [row("frame_budget", True, "skipped: the sport draws its own images (a wrapper)")]+ return [_own_budget(sport, cfg, m, decl, plugin, budget, players)]+ from renderers import budget as B+ import renderers+ from renderers.base import CameraDef+ name = obs.get("renderer") or renderers.DEFAULT+ cams = [CameraDef.from_dict(c) for c in m.cameras(cfg.seats[0], None)]+ ok, ms = B.check_budget(renderers.load(name), players_scene(sport, plugin, cfg), m.render_state(), cams,+ budget_ms=budget or 1e9)+ what = f", players' presentation scene ({players} meshes)" if players else ""+ out = [row("frame_budget", budget is not None and ok,+ f"{name}{what}: {ms:.1f} ms per observation, budget {budget} ms")]+ if own_hook(m, "reply_views"):+ out.append(t_reply_budget(sport, plugin, decl, cfg, name, budget))+ return out+++def t_reply_budget(sport, plugin, decl, cfg, name, budget):+ """The first action's reply image (Match.reply_views, core 0.2.8), drawn as the service draws it (the core's+ camera worker), within [observation] frame_budget_ms (median of 3 after one warm-up)."""+ from .observe import CameraWorker, reply_job+ m = sport.build(cfg)+ layer = sport.action_layer(cfg.action_level)+ ps = local.make_players(sport, cfg, {s: "reference" for s in cfg.seats}, plugin=plugin)+ views = local.Views(sport, cfg, m, decl, True, plugin)+ job = None+ for _ in range(50): # the first action that has reply images+ if m.phase().state == FINISHED:+ break+ seat = m.to_move() or cfg.seats[0]+ if sport.protocol != "turn":+ m.step()+ continue+ low, _ = layer.lower(seat, layer.parse(seat, ps[seat].act(views.view(seat, {})), m, {"clock_left_s": {}}),+ None, m)+ info = m.apply(seat, low) or {}+ job = reply_job(m, m.reply_views(seat, low, info), int((decl.get("observation") or {}).get("columns", 2)))+ if job is not None:+ break+ if job is None:+ return row("reply_budget", False, "Match.reply_views gave no image for the first actions of the reference")+ w = CameraWorker(players_scene(sport, plugin, cfg), name)+ w.draw_job(job)+ times = []+ for _ in range(3):+ t = time.perf_counter()+ img = w.draw_job(job)+ times.append((time.perf_counter() - t) * 1000.0)+ ms = sorted(times)[1]+ ok = budget is not None and ms <= float(budget)+ return row("reply_budget", ok, f"{name}: {ms:.1f} ms per reply image ({len(img['tiles'])} tiles), budget {budget} ms")+++def _own_budget(sport, cfg, m, decl, plugin, budget, players, n: int = 5, between: int = 30):+ """A sport that draws its own images from its players' presentation scene: the median wall time of its own+ observation path (Views.view) from a fresh world, `between` control steps apart early in play (a realtime world+ may freeze between rallies: only observations whose image changed count), after a warm-up."""+ m = sport.build(cfg)+ views = local.Views(sport, cfg, m, decl, True, plugin)+ seat = cfg.seats[0]++ def run(k):+ if sport.protocol == "realtime":+ for _ in range(k):+ if m.phase().state == FINISHED:+ break+ m.step()+ last = views.view(seat, {})["observation"].get("image_png_b64")+ times, tries = [], 0+ while len(times) < n and tries < 4 * n:+ tries += 1+ run(between)+ t = time.perf_counter()+ img = views.view(seat, {})["observation"].get("image_png_b64")+ ms = (time.perf_counter() - t) * 1000.0+ if img != last or sport.protocol != "realtime":+ times.append(ms)+ last = img+ if not times:+ return row("frame_budget", False, "no observation with a new image to time")+ ms = sorted(times)[len(times) // 2]+ return row("frame_budget", budget is not None and ms <= float(budget),+ f"the sport's own images from its players' presentation scene ({players} meshes): {ms:.1f} ms per "+ f"observation (median of {len(times)} with a new image), budget {budget} ms")+++def t_exploits(sport, plugin, decl):+ out = []+ tests_dir = Path(plugin).parent / "tests"+ funcs = {}+ for p in sorted(tests_dir.glob("test_*.py")):+ spec = importlib.util.spec_from_file_location(f"sport_test_{p.stem}", p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ funcs.update({k: v for k, v in vars(mod).items() if k.startswith("test_") and callable(v)})+ for ex in decl.get("exploits", []):+ f = funcs.get(ex.get("test", ""))+ if f is None:+ out.append(row(f"exploit:{ex.get('id')}", False, f"no test {ex.get('test')!r} in tests/test_*.py"))+ continue+ try:+ f()+ out.append(row(f"exploit:{ex['id']}", True, ex.get("text", "")))+ except Exception: # noqa: BLE001+ out.append(row(f"exploit:{ex['id']}", False, traceback.format_exc()[-500:]))+ if not decl.get("exploits"):+ out.append(row("exploit_list", False, "sport.toml has no [[exploits]]"))+ return out+++class Idle:+ """A built-in player that never acts (the realtime world runs on without it)."""++ def act(self, view):+ return None+++def t_solo_quit(sport, plugin, decl, steps=40):+ """core 0.2.6 (core rule 6): the collect of a started single-side match writes a forfeit row "abandoned" at the+ current step; the sport's forfeit hook and the fresh-process replay must agree on a loss without a winner."""+ from .episode import read_rows, replay+ out = []+ for fmt, f in (decl.get("formats") or {}).items():+ if len({(f.get("sides") or {}).get(s, s) for s in f["seats"]}) != 1:+ continue+ cfg = next(c for c in configs(decl, sport, seeds=(1,)) if c.format == fmt)+ with tempfile.TemporaryDirectory() as tmp:+ r = local.play(sport, cfg, {s: Idle() for s in cfg.seats}, data=tmp, render=False, plugin=plugin,+ max_actions=0, max_steps=steps)+ ep = Path(tmp) / "episode.jsonl"+ rows = [x for x in read_rows(ep) if x["ev"] != "end"]+ rows += [{"ev": "forfeit", "k": r["k"], "seat": cfg.seats[0], "why": "abandoned"},+ {"ev": "end", "k": r["k"], "reason": "abandoned"}]+ ep.write_text("".join(json.dumps(x, default=float) + "\n" for x in rows))+ mine = replay(sport, rows)+ rc, err = fresh_replay(plugin, tmp, decl)+ ok = (not r["finished"] and mine["winner"] is None and mine["decided_by"] == "forfeit:abandoned"+ and rc.get("state_sha") == mine["state_sha"] and rc.get("winner") is None+ and rc.get("decided_by") == "forfeit:abandoned" and rc.get("k") == r["k"])+ out.append(row(f"solo_quit:{fmt}", ok, {"k": r["k"], "finished_before": r["finished"],+ "decided_by": mine["decided_by"], "replay": rc.get("decided_by")}+ if rc else err[-400:]))+ return out+++def t_prestart_no_show(sport, plugin, decl):+ """core 0.2.7 (core rule 5): a side that never started loses before any play ("no_show" at step 0, when the start+ window closes or at a collect before the start). For every format of one or two sides, the episode the core then+ writes (header, the forfeit row of the first seat of the last side, end) must replay to that decision: a single+ side's loss without a winner, or the other side's win, at step 0. Whether the world then reports itself finished+ is the sport's own business (Match.forfeit records the decision inside the world; a sport may end it there,+ game over, winner set): the core decides a forfeit before it looks at the phase (core.outcome.decide), and the+ service's validity reads the end reason, not the phase (core 0.2.12)."""+ from .episode import replay+ out = []+ for fmt, f in (decl.get("formats") or {}).items():+ cfg = next(c for c in configs(decl, sport, seeds=(1,)) if c.format == fmt)+ sides = list(cfg.side_list())+ if len(sides) > 2:+ continue+ seat = next(s for s in cfg.seats if cfg.side_of(s) == sides[-1])+ rows = [{"ev": "header", "cfg": cfg.to_json(), "sport": sport.name, "protocol": sport.protocol},+ {"ev": "forfeit", "k": 0, "seat": seat, "why": "no_show"}, {"ev": "end", "k": 0, "reason": "no_show"}]+ r = replay(sport, rows)+ want = sides[0] if len(sides) == 2 else None+ ok = r["winner"] == want and r["decided_by"] == "forfeit:no_show" and r["k"] == 0+ out.append(row(f"prestart_no_show:{fmt}", ok, {"absent": seat, "winner": r["winner"], "want": want,+ "decided_by": r["decided_by"], "k": r["k"],+ "finished": r["finished"]}))+ return out+++def t_continuous(sport, plugin, decl):+ """core 0.2.14 (sport.toml [score], core/score.py): the declaration is well formed, and a side that never started+ gets the forfeit value while the other side's value is a finite number (the definition copes with no play)."""+ from .episode import replay+ sd = score_mod.declaration(decl)+ if sd is None:+ return [row("continuous_score", True, "not declared (sport.toml [score]); tools/check warns")]+ bad = score_mod.problems(decl, own_hook(sport.build(next(configs(decl, sport, seeds=(1,)))), "continuous_score"))+ out = [row("continuous_score:declared", not bad, "; ".join(bad) or f"{sd['name']} (from {sd['from']})")]+ for fmt, f in (decl.get("formats") or {}).items():+ cfg = next(c for c in configs(decl, sport, seeds=(1,)) if c.format == fmt)+ sides = list(cfg.side_list())+ if len(sides) > 2:+ continue+ seat = next(s for s in cfg.seats if cfg.side_of(s) == sides[-1])+ rows = [{"ev": "header", "cfg": cfg.to_json(), "sport": sport.name, "protocol": sport.protocol},+ {"ev": "forfeit", "k": 0, "seat": seat, "why": "no_show"}, {"ev": "end", "k": 0, "reason": "no_show"}]+ try:+ by = replay(sport, rows, decl=decl)["continuous"]+ ok = by[sides[-1]] == sd["forfeit"] and all(math.isfinite(v) for v in by.values())+ except Exception as exc: # noqa: BLE001+ by, ok = f"{type(exc).__name__}: {exc}"[:300], False+ out.append(row(f"continuous_score:no_show:{fmt}", ok, {"by_side": by, "forfeit": sd["forfeit"]}))+ return out+++def t_seed_private(sport, plugin, decl, seed=987123):+ """core 0.2.14 (core/seeds.py): where the sport itself shows a match's seed (observation, /spec, final fields). For+ information: in a hidden-seed match the core scrubs all three, but a sport should not show the seed at all."""+ import re+ cfg = next(configs(decl, sport, seeds=(seed,)))+ m = sport.build(cfg)+ pat = re.compile(rf"(?<![\d.]){seed}(?![\d.])|\"\w*seed\"")+ where = [name for name, fn in (("observe", lambda: [m.observe(s, None) for s in cfg.seats]),+ ("spec", lambda: local.seat_spec(sport, cfg, cfg.seats[0], m, plugin)),+ ("final_fields", m.final_fields))+ if pat.search(json.dumps(fn(), default=str))]+ return [row("seed_private", True, f"the sport shows the seed in {where} (scrubbed in hidden-seed matches)"+ if where else "the sport shows the seed nowhere")]+++def tests(plugin):+ sport, decl = load_plugin(plugin), spec_mod.load(plugin)+ out = []+ for f in (t_determinism, t_no_draw_and_whitelist, t_mirror, t_pure, t_refuses, t_fuzz, t_budget, t_exploits,+ t_solo_quit, t_prestart_no_show, t_continuous, t_seed_private):+ t = time.time()+ try:+ rows = f(sport, plugin, decl)+ except Exception: # noqa: BLE001+ rows = [row(f.__name__[2:], False, traceback.format_exc()[-800:])]+ for r in rows:+ r["s"] = round(time.time() - t, 1)+ out += rows+ return out+++def advantage(wins: int, games: int, fair: float, lim: float) -> dict:+ """A side's (or a seat's) advantage in percentage points with its 95% confidence interval (normal approximation of+ the win rate). The rule (sport rule 6): FAIL only if the whole interval lies beyond +-lim (a real advantage);+ WARN if the interval is wider than +-lim (too few matches to tell)."""+ p = wins / games if games else fair+ adv = 100.0 * (p - fair)+ h = 196.0 * math.sqrt(max(p * (1 - p), 1e-9) / games) if games else 100.0+ return {"advantage_pp": round(adv, 2), "ci95_pp": round(h, 2), "lo": adv - h, "hi": adv + h,+ "fail": adv - h > lim or adv + h < -lim, "wide": h > lim}+++def fairness(plugin, matches=None):+ """Built-in players on every seat, both first orders, N seeds each: the advantage of the side that starts and of the+ first seat, each with its 95% confidence interval (advantage()); the seeds are fixed, so the check is+ reproducible. A format plays with its declared sides, and the fair share is one over their number (core 0.2.13:+ a team format is two sides, not one side per seat). Turn-based sports (cheap to play) must also play enough+ matches: an interval wider than +-lim FAILS there; realtime sports only WARN (decided 2026-10-06). An explicit+ `matches` (tools/check --quick) only warns."""+ sport, decl = load_plugin(plugin), spec_mod.load(plugin)+ fc = decl.get("fairness") or {}+ pol, lim = fc.get("policy", "reference"), fc.get("max_advantage_pp", 5)+ n = int(matches or fc.get("matches_per_order", 100))+ out = []+ for fmt, f in decl.get("formats", {}).items():+ seats = f["seats"]+ if len(seats) < 2:+ continue+ level = (decl.get("modes") or {}).get("action_levels", ["high"])[0]+ firsts = f.get("first") or seats+ first_wins = seat_wins = games = 0+ for first in firsts:+ for seed in range(1, n + 1):+ cfg = MatchConfig(sport=sport.name, format=fmt, seats=tuple(seats), seed=seed, first=first,+ action_level=level, sides=f.get("sides"))+ r = local.play(sport, cfg, local.make_players(sport, cfg, {s: pol for s in seats}, plugin=plugin),+ plugin=plugin)+ games += 1+ first_wins += r["winner"] == cfg.side_of(first)+ seat_wins += r["winner"] == cfg.side_of(seats[0])+ k = len(set(MatchConfig(sport.name, fmt, tuple(seats), 1, sides=f.get("sides")).side_list()))+ verdicts = {}+ for what, wins in (("first_side", first_wins), ("seat_" + seats[0], seat_wins)):+ verdicts[what] = advantage(wins, games, 1.0 / k, lim)+ wide = any(v["wide"] for v in verdicts.values())+ strict = sport.protocol == "turn" and matches is None+ fail = any(v["fail"] for v in verdicts.values()) or (strict and wide)+ warn = wide and not strict+ r = row(f"fairness:{fmt}", not fail, {"policy": pol, "N": games, "per_order": n, "max_pp": lim,+ **{w: {x: v[x] for x in ("advantage_pp", "ci95_pp")}+ for w, v in verdicts.items()}})+ r["warn"] = warn and not fail+ if r["warn"]:+ r["detail"] += f" -- WARN: the 95% CI is wider than +-{lim} pp; play more matches ([fairness] matches_per_order)"+ if strict and wide and not any(v["fail"] for v in verdicts.values()):+ r["detail"] += f" -- FAIL: turn-based sport, the 95% CI is wider than +-{lim} pp; raise [fairness] matches_per_order"+ out.append(r)+ return out or [row("fairness", True, "no format with two or more sides")]+++def main(argv):+ cmd, plugin = argv[0], os.path.abspath(argv[1])+ res = tests(plugin) if cmd == "tests" else fairness(+ plugin, int(argv[argv.index("--matches") + 1]) if "--matches" in argv else None)+ if "--json" in argv:+ Path(argv[argv.index("--json") + 1]).write_text(json.dumps(res, indent=1))+ for r in res:+ print(f"{('WARN' if r.get('warn') else 'ok ') if r['ok'] else 'FAIL'} {r['name']}: {r['detail']}")+ return 0 if all(r["ok"] for r in res) else 1+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture/plugin.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture/plugin.pynew file mode 100644index 0000000000..b6b40886bc--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture/plugin.py@@ -0,0 +1,108 @@+"""A synthetic realtime world for the core's tests: every entity has a position on a line and a commanded velocity;+a unit ends every UNIT steps (all seats review), the match after UNITS units; a side's score is the sum of its+entities' positions; more than two sides are ranked by score (retired sides last). No physics, no images."""+import os++from core.sport import FINISHED, PLAYING, UNIT_OVER, MatchBase, Phase, Refused, SchemaLayer, sha_json++UNIT, UNITS, ENTITIES = 30, 3, ("e0", "e1")+++class World(MatchBase):+ dt = 0.01++ def __init__(self, cfg):+ self.cfg, self.k, self.u, self.frozen = cfg, 0, 0, False+ self.pos = {f"{s}.{e}": 0.0 for s in cfg.seats for e in ENTITIES}+ self.vel = dict.fromkeys(self.pos, 0.0)+ self.out: list[str] = []++ def schema(self, seat):+ return {"move": {"v": {"type": "number", "min": -1, "max": 1}}}++ def entities(self, seat):+ return ENTITIES++ def apply(self, seat, cmd):+ self.vel[f"{seat}.{cmd['entity']}"] = cmd["v"]+ return {}++ def step(self):+ for key, v in self.vel.items():+ if key.split(".")[0] not in self.retired_seats():+ self.pos[key] = round(self.pos[key] + v, 6)+ self.k += 1+ if self.k % UNIT == 0:+ self.frozen = True+ return [{"kind": "unit_end", "unit": self.u}] # an event (core 0.2.25 logs it as an `event` row)+ return []++ def retired_seats(self):+ return [s for s in self.cfg.seats if self.cfg.side_of(s) in self.out]++ def phase(self):+ if self.k >= UNIT * UNITS:+ return Phase(FINISHED, reason="match_over")+ if self.frozen:+ return Phase(UNIT_OVER, review=tuple(self.cfg.seats), reason="unit")+ return Phase(PLAYING)++ def resume(self):+ self.frozen, self.u = False, self.u + 1++ def unit(self):+ return self.u++ def retire(self, side, why):+ self.out.append(side)+ return True++ def scores(self):+ out = {}+ for s in self.cfg.seats:+ out[self.cfg.side_of(s)] = round(out.get(self.cfg.side_of(s), 0.0) + sum(+ self.pos[f"{s}.{e}"] for e in ENTITIES), 6)+ return out++ def ranking(self):+ sc = self.scores()+ return sorted(sc, key=lambda s: (s in self.out, -sc[s], s))++ def tiebreaks(self):+ if len(self.cfg.side_list()) < 2:+ return [] # one side: solo+ a, b = self.cfg.side_list()[:2]+ return [("score", lambda m: None if m.scores()[a] == m.scores()[b] else+ (a if m.scores()[a] > m.scores()[b] else b)), ("first_side", lambda m: a)]++ def state_digest(self):+ return sha_json({"k": self.k, "pos": self.pos, "out": self.out})++ def observe(self, seat, query=None):+ if query is not None and query.get("view") not in ("near", "far"):+ raise Refused("query.view must be near or far")+ mine = {e: self.pos[f"{seat}.{e}"] for e in ENTITIES}+ extra = {"view": query["view"]} if query else {}+ if query and query["view"] == "far":+ extra["secret_state"] = self.pos # not whitelisted: the core must drop it and record an error+ return {"unit": self.u, "pos": mine, **extra}+++class Layer(SchemaLayer):+ def __init__(self, delay):+ super().__init__()+ self.delay_steps = delay+++class Fixture:+ name, protocol, revision, workers = "fixture", "realtime", "fixture-1", ()+ source_dirs = [os.path.dirname(os.path.abspath(__file__))]++ def build(self, cfg):+ return World(cfg)++ def action_layer(self, level):+ return Layer(int(os.environ.get("FIXTURE_DELAY", "0")))+++SPORT = Fixture()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture/sport.toml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture/sport.tomlnew file mode 100644index 0000000000..eee97c6f64--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture/sport.toml@@ -0,0 +1,17 @@+# The core's realtime test fixture (core/tests/test_core.py): a synthetic world with no physics, written against the+# interface only, that exercises the stage-0 hooks a real sport may use: several seats per side and two entities per+# seat, N sides with a ranking and retirement, a delayed effect, observation queries and the team channel.+[sport]+name = "fixture"+protocol = "realtime"+revision = "fixture-1"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"++[observation]+fields = ["unit", "pos", "view"]++[team_channel]+max_bytes = 40+min_interval_s = 0.2+max_messages = 50diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_images/plugin.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_images/plugin.pynew file mode 100644index 0000000000..0339fecfeb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_images/plugin.py@@ -0,0 +1,103 @@+"""A synthetic turn-protocol game with images for the core's reply-image tests (core 0.2.8): two sides move in turn,+each move v in [0, 1] adds v to the mover's score and puts the mover's block at x = v (TURNS moves each). The scene+is a floor and two mocap blocks; cameras() serves the top view to the seat on turn only, and not while another seat's+review is due (Match.awaiting_review); reply_views() shows the move's result: two frames (the block before and after+the move), camera order."""+import os++from core.sport import FINISHED, PLAYING, LowLayer, MatchBase, Phase, Refused, sha_json++TURNS = 2+XML = ('<mujoco><visual><headlight ambient=".5 .5 .5"/></visual><worldbody><geom type="plane" size="5 5 .1" '+ 'rgba=".3 .5 .3 1"/><body mocap="true" pos="0 0 .1"><geom type="box" size=".1 .1 .1" rgba="1 0 0 1"/></body>'+ '<body mocap="true" pos="0 1 .1"><geom type="box" size=".1 .1 .1" rgba="0 0 1 1"/></body></worldbody></mujoco>')+TOP = {"name": "top", "pos": [0.5, 0.5, 4], "lookat": [0.5, 0.5, 0], "up": [1, 0, 0], "fovy_deg": 50, "width": 80,+ "height": 60}+++class Game(MatchBase):+ def __init__(self, cfg):+ self.cfg, self.k = cfg, 0+ self.order = list(cfg.seats) if cfg.first in (None, cfg.seats[0]) else list(cfg.seats)[::-1]+ self.score = dict.fromkeys(cfg.seats, 0.0)+ self.x = dict.fromkeys(cfg.seats, 0.0)+ self.moves = dict.fromkeys(cfg.seats, 0)+ self.before = None # the mover's block before its last move++ def schema(self, seat):+ return {"add": {"v": {"type": "number", "min": 0, "max": 1}}}++ def apply(self, seat, cmd):+ self.before = dict(self.x)+ self.score[seat] = round(self.score[seat] + cmd["v"], 6)+ self.x[seat] = cmd["v"]+ self.moves[seat] += 1+ self.k += 1+ return {"moved": seat}++ def to_move(self):+ if self.phase().state == FINISHED:+ return None+ return min(self.order, key=lambda s: (self.moves[s], self.order.index(s)))++ def phase(self):+ return Phase(FINISHED, reason="match_over") if all(n >= TURNS for n in self.moves.values()) else Phase(PLAYING)++ def scores(self):+ return dict(self.score)++ def tiebreaks(self):+ a, b = self.order[:2]+ return [("score", lambda m: None if m.score[a] == m.score[b] else (a if m.score[a] > m.score[b] else b)),+ ("first", lambda m: a)]++ def state_digest(self):+ return sha_json({"k": self.k, "score": self.score, "x": self.x})++ def observe(self, seat, query=None):+ return {"unit": self.k, "pos": self.x[seat]}++ def cameras(self, seat, query=None):+ if seat != self.to_move() or self.awaiting_review not in (None, seat):+ return []+ return [TOP]++ def state_of(self, x):+ s = list(self.cfg.seats)+ return {"qpos": [], "mocap_pos": [[x[s[0]], 0.0, 0.1], [x[s[1]], 1.0, 0.1]],+ "mocap_quat": [[1, 0, 0, 0], [1, 0, 0, 0]]}++ def render_state(self):+ return self.state_of(self.x)++ def reply_views(self, seat, cmd, info):+ return {"frames": [{"cameras": [TOP], "state": self.state_of(self.before), "label": "before"},+ {"cameras": [TOP], "label": "after"}], "note": "your block before and after the move"}+++def validate(seat, body, match, ctx):+ try:+ v = float(body.get("v"))+ except (TypeError, ValueError):+ raise Refused("v must be a number") from None+ if not 0 <= v <= 1:+ raise Refused("v must be in [0, 1]")+ return {"type": "add", "v": v}+++class Fixture:+ name, protocol, revision, workers = "fixture_images", "turn", "fixture-images-1", ()+ source_dirs = [os.path.dirname(os.path.abspath(__file__))]++ def build(self, cfg):+ return Game(cfg)++ def action_layer(self, level):+ return LowLayer(validate)++ def scene(self, cfg):+ from renderers.base import Scene+ return Scene(xml=XML)+++SPORT = Fixture()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_images/sport.toml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_images/sport.tomlnew file mode 100644index 0000000000..b1237e9197--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_images/sport.toml@@ -0,0 +1,13 @@+# The core's reply-image test fixture (core/tests/test_core.py, core 0.2.8): the turn fixture's game with a tiny+# MuJoCo scene: each move puts the mover's block at x = v; cameras for the seat on turn; reply images of the move.+[sport]+name = "fixture_images"+protocol = "turn"+revision = "fixture-images-1"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"++[observation]+fields = ["unit", "pos"]+columns = 2+reply_images = "the top camera after the move"diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_turn/plugin.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_turn/plugin.pynew file mode 100644index 0000000000..4fbe331bcb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_turn/plugin.py@@ -0,0 +1,106 @@+"""A synthetic turn-protocol game for the core's tests: the sides move in turn (the first side first), each move adds+v in [0, 1] to the mover's side score; the match ends when every side still in has made TURNS moves. Two sides are+decided by score, then the first side; more sides are ranked by score (retired sides last). The built-in player adds+0.5 on every turn (the fairness check, core/testkit.py). No physics, no images."""+import os++from core.sport import FINISHED, PLAYING, LowLayer, MatchBase, Phase, Refused, sha_json++TURNS = 2+++class Game(MatchBase):+ def __init__(self, cfg):+ self.cfg, self.k = cfg, 0+ sides = cfg.side_list()+ first = cfg.side_of(cfg.first) if cfg.first in cfg.seats else (cfg.first or sides[0])+ i = sides.index(first) if first in sides else 0+ self.order = sides[i:] + sides[:i]+ self.score = dict.fromkeys(sides, 0.0)+ self.moves = dict.fromkeys(sides, 0)+ self.out: list[str] = []++ def schema(self, seat):+ return {"add": {"v": {"type": "number", "min": 0, "max": 1}}}++ def apply(self, seat, cmd):+ side = self.cfg.side_of(seat)+ self.score[side] = round(self.score[side] + cmd["v"], 6)+ self.moves[side] += 1+ self.k += 1+ return {}++ def live(self):+ return [s for s in self.order if s not in self.out]++ def to_move(self):+ if self.phase().state == FINISHED:+ return None+ side = min(self.live(), key=lambda s: (self.moves[s], self.order.index(s)))+ return self.cfg.seats_of(side)[0]++ def phase(self):+ if all(self.moves[s] >= TURNS for s in self.live()):+ return Phase(FINISHED, reason="match_over")+ return Phase(PLAYING)++ def retire(self, side, why):+ self.out.append(side)+ return True++ def scores(self):+ return dict(self.score)++ def ranking(self):+ return sorted(self.score, key=lambda s: (s in self.out, -self.score[s], self.order.index(s)))++ def tiebreaks(self):+ if len(self.order) < 2:+ return [] # one side: solo+ a, b = self.order[:2]+ return [("score", lambda m: None if m.score[a] == m.score[b] else (a if m.score[a] > m.score[b] else b)),+ ("first_side", lambda m: a)]++ def state_digest(self):+ return sha_json({"k": self.k, "score": self.score, "moves": self.moves, "out": self.out})++ def final_fields(self): # a sport that records its seed (core/seeds.py scrub test)+ return {"seed": self.cfg.seed, "draws": [self.cfg.seed, 1]}++ def observe(self, seat, query=None):+ return {"unit": self.k, "pos": self.score[self.cfg.side_of(seat)]}+++def validate(seat, body, match, ctx):+ try:+ v = float(body.get("v"))+ except (TypeError, ValueError):+ raise Refused("v must be a number") from None+ if not 0 <= v <= 1:+ raise Refused("v must be in [0, 1]")+ return {"type": "add", "v": v}+++class Steady:+ def __init__(self, spec, seat, seed):+ pass++ def act(self, view):+ return {"type": "add", "v": 0.5}+++class Fixture:+ name, protocol, revision, workers = "fixture_turn", "turn", "fixture-turn-1", ()+ source_dirs = [os.path.dirname(os.path.abspath(__file__))]++ def build(self, cfg):+ return Game(cfg)++ def action_layer(self, level):+ return LowLayer(validate)++ def players(self):+ return {"reference": Steady}+++SPORT = Fixture()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_turn/sport.toml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_turn/sport.tomlnew file mode 100644index 0000000000..9a1e51bb07--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/fixture_turn/sport.toml@@ -0,0 +1,24 @@+# The core's turn-protocol test fixture (core/tests/test_core.py): a synthetic game with no physics, written against+# the interface only: the sides take turns adding a number to their score; N sides with a ranking and retirement;+# a team format whose sides are not its seats (the fairness check, core/testkit.py).+[sport]+name = "fixture_turn"+protocol = "turn"+revision = "fixture-turn-1"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"++[observation]+fields = ["unit", "pos"]++[formats.team]+seats = ["A1", "A2", "B1", "B2"]+sides = { A1 = "A", A2 = "A", B1 = "B", B2 = "B" }+first = ["A", "B"]++[score] # core 0.2.14: the continuous score (core/score.py), checked through the turn tests+name = "score_share"+text = "the side's share of all points scored"+from = "share"+forfeit = 0.0+range = [0, 1]diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/test_core.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/test_core.pynew file mode 100644index 0000000000..aee2e901ad--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/test_core.py@@ -0,0 +1,2044 @@+"""Unit tests of the core's stage-0 hooks on the synthetic realtime fixture (core/tests/fixture), of the start window+(no-show rule, at the window and at a collect before the start, both protocols; turn fixture core/tests/fixture_turn) and of the outcome and grading rules. Standard library + numpy; run in the sim image:+ docker run --rm -v $PWD:/w -w /w ghcr.io/mll-lab-nu/eai-olympiad:0.1.0 \\+ python3 core/tests/test_core.py+"""+from __future__ import annotations++import json+import os+import shutil+import sys+import tempfile+import threading+import time+import traceback+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+os.environ.update(READY_TIMEOUT_S="1.5", START_TIMEOUT_S="5", BARRIER_LEAD_S="0.05")++from core.episode import load_plugin # noqa: E402+from core.grading import grade, line_ok # noqa: E402+from core.outcome import decide # noqa: E402+from core.realtime import RealtimeService # noqa: E402+from core.sport import FINISHED, PLAYING, MatchConfig, Phase, Refused # noqa: E402+from core.turn import TurnService # noqa: E402++PLUGIN = str(Path(__file__).resolve().parent / "fixture" / "plugin.py")+SPORT = load_plugin(PLUGIN)+PLUGIN_TURN = str(Path(__file__).resolve().parent / "fixture_turn" / "plugin.py")+SPORT_TURN = load_plugin(PLUGIN_TURN)+++def service(seats, sides=None, fmt="team"):+ for s in seats:+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format=fmt, seats=tuple(seats), seed=1, slowdown=1.0, sides=sides)+ svc = RealtimeService(SPORT, PLUGIN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ return svc, svc.routes(True)+++def turn_service(seats, sides=None, fmt="duel"):+ for s in seats:+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture_turn", format=fmt, seats=tuple(seats), seed=1, first=seats[0], sides=sides,+ action_level="low")+ svc = TurnService(SPORT_TURN, PLUGIN_TURN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ return svc, svc.routes(True)+++def play_turn(svc, post, seat, v=0.5):+ """One seat's turn loop: start, then on its turn act (v) and review, until the end."""+ post["start"](seat, {})+ while svc.phase != "over":+ st = post["wait"](seat, {"timeout_s": 1})[1]["state"]+ if st["done"] or not st["your_turn"]:+ continue+ if st["awaiting_review"]:+ post["ready"](seat, {"why": "w", "plan": "p"})+ else:+ post["act"](seat, {"v": v})+++def play(svc, post, seat, review=True, act=None):+ """One seat's loop: start, then act (act(seat, post) each round) and review at every unit end until the end."""+ post["start"](seat, {})+ while svc.phase != "over":+ if svc.phase == "review":+ if review and not svc.seats[seat].ready and seat in svc.due():+ post["ready"](seat, {"why": "w", "plan": "p"})+ time.sleep(0.01)+ continue+ if svc.phase == "running" and act:+ act(seat, post)+ time.sleep(0.01)+++def finish(svc, timeout=60):+ t = time.time()+ while not svc.finalized and time.time() - t < timeout:+ time.sleep(0.1)+ return json.loads((svc.data / "final.json").read_text())+++def run_all(svc, post, seats, **kw):+ th = [threading.Thread(target=play, args=(svc, post, s), kwargs=kw.get(s, {}), daemon=True) for s in seats]+ for t in th:+ t.start()+ return finish(svc)+++def test_seats_sides_entities_and_team_channel():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ svc, post = service(list(sides), sides)+ th = [threading.Thread(target=post["start"], args=(s, {}), daemon=True) for s in sides]+ for t in th:+ t.start()+ while svc.phase != "running":+ time.sleep(0.01)+ lock = svc.seats["A1"].act_lock("e0")+ lock.acquire() # an act of A1's entity e0 is in flight+ try:+ assert post["act"]("A1", {"type": "move", "v": 0.5, "entity": "e0"})[0] == 429+ code, out = post["act"]("A1", {"type": "move", "v": 0.5, "entity": "e1"}) # another entity: accepted+ assert code == 200, out+ finally:+ lock.release()+ try:+ post["act"]("A1", {"type": "move", "v": 0.5, "entity": "e9"})+ raise AssertionError("unknown entity accepted")+ except Refused:+ pass+ assert post["say"]("A1", {"text": "x" * 41})[0] == 400 # longer than max_bytes+ assert post["say"]("A1", {"text": "press high"})[0] == 200+ assert post["say"]("A1", {"text": "again"})[0] == 429 # min_interval_s in game time+ time.sleep(0.05)+ get = svc.routes(False)+ a2 = get["status"]("A2", {})[1]+ b1 = get["status"]("B1", {})[1]+ assert [m["text"] for m in a2["team_messages"]] == ["press high"] and a2["team_messages"][0]["from"] == "A1"+ assert a2["team_messages"][0]["seq"] == 1 and a2["team_seq"] == 1+ assert b1["team_messages"] == [] and b1["team_seq"] == 0 # never shown to the other side+ # core 0.2.20: reading never consumes: a second client of the same seat (the agent's own status, a monitor)+ # sees the same message; a read mark gives only newer ones; the sender never gets its own message back+ again = get["status"]("A2", {})[1]+ assert [m["text"] for m in again["team_messages"]] == ["press high"]+ assert get["status"]("A2", {"team_since": 1})[1]["team_messages"] == []+ assert get["status"]("A1", {})[1]["team_messages"] == [] and get["status"]("A1", {})[1]["team_seq"] == 1+ assert post["team"]("A2", {"since": 0})[1]["messages"][0]["text"] == "press high"+ assert post["team"]("B1", {})[1]["messages"] == []+ for bad in (-1, 1.5, "x", [1], True):+ try:+ get["status"]("A2", {"team_since": bad})+ raise AssertionError(f"read mark {bad!r} accepted")+ except Refused:+ pass+ th = [threading.Thread(target=play, args=(svc, post, s), daemon=True) for s in sides]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["match_winner"] == "home" and fin["sides"]["A2"] == "home" and fin["team_messages"] == 1+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "team" and r["text"] == "press high" for r in rows)+ cmds = [r for r in rows if r["ev"] == "cmd"]+ assert cmds and cmds[0]["cmd"]["entity"] == "e1"+++def test_n_sides_ranking_and_retirement():+ svc, post = service(["A", "B", "C"], fmt="multi")++ def mover(v):+ return lambda seat, p: p["act"](seat, {"type": "move", "v": v, "entity": "e0"})+ fin = run_all(svc, post, ["A", "B", "C"], A={"act": mover(0.2)}, B={"act": mover(0.1)},+ C={"act": mover(0.9), "review": False}) # C never reviews: it retires, A and B play on+ assert fin["retired"] == ["C"] and fin["reason"] == "match_over", fin+ assert fin["ranking"] == ["A", "B", "C"] and fin["match_winner"] == "A"+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "retire" and r["side"] == "C" for r in rows)+ r = {"cfg": fin["cfg"], **fin}+ out = grade(r, json.loads((svc.data / "replay_check.json").read_text()), {}, lambda d: {})+ assert out["A_place"] == 1 and out["C_place"] == 3 and out["A_won"] == 1 and out["success"] == 1+++def test_delayed_effect_is_logged_at_its_step():+ os.environ["FIXTURE_DELAY"] = "3"+ try:+ svc, post = service(["A", "B"], fmt="duel")+ got = []++ def act(seat, p):+ if seat == "A" and not got:+ got.append(p["act"](seat, {"type": "move", "v": 0.3, "entity": "e0"}))+ fin = run_all(svc, post, ["A", "B"], A={"act": act})+ finally:+ os.environ.pop("FIXTURE_DELAY")+ code, out = got[0]+ assert code == 200, out+ eff = out["took_effect"]+ assert eff["effect_step"] == eff["step"] + 3+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ cmd = next(r for r in rows if r["ev"] == "cmd" and r["seat"] == "A")+ assert cmd["k"] == eff["effect_step"]+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ rc = fin["reaction"] # core 0.2.23: the layer's delay is part of the report+ assert rc["effect_delay_steps"] == 3 and rc["by_seat"]["A"]["acts"] == 1 and rc["replayed"] is True, rc+ assert rc["by_seat"]["A"]["delay_steps"]["max"] == cmd["k"] - cmd["seen"] >= 3, (rc, cmd)+++def fixture_with_reaction_delay(D):+ """A copy of the realtime fixture whose sport.toml declares [timing] reaction_delay_steps = D (core 0.2.18)."""+ import shutil+ d = Path(tempfile.mkdtemp(prefix="core-test-react-")) / "fixture"+ shutil.copytree(Path(PLUGIN).parent, d, ignore=shutil.ignore_patterns("__pycache__"))+ (d / "sport.toml").write_text((d / "sport.toml").read_text() + f"\n[timing]\nreaction_delay_steps = {D}\n")+ return str(d / "plugin.py")+++def test_reaction_delay_rule():+ """core 0.2.18: with a declared reaction delay D an act takes effect at max(the next boundary, s + D), s = the+ step of the latest world state the seat was sent (an observation or any reply's `now`); the effect step is+ logged and replayed (deterministic); the same D for every seat; /spec shows it."""+ from core import spec as spec_mod+ assert spec_mod.reaction_delay({}) == 0 and spec_mod.reaction_delay({"timing": {"reaction_delay_steps": 3}}) == 3+ for bad in (-1, 2.0, True, "2"):+ try:+ spec_mod.reaction_delay({"timing": {"reaction_delay_steps": bad}})+ raise AssertionError(f"accepted {bad!r}")+ except ValueError:+ pass+ D, plugin = 4, fixture_with_reaction_delay(4)+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=5.0) # 50 ms per step+ svc = RealtimeService(load_plugin(plugin), plugin, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ assert svc.spec("A")[1]["timing"]["reaction_delay_steps"] == D+ got = []++ def act(seat, p):+ if len(got) >= 6 or svc.phase != "running":+ return+ code, ob = p["observe"](seat, {})+ if code != 200 or ob["now"]["phase"] != "running":+ return+ code, out = p["act"](seat, {"type": "move", "v": 0.1, "entity": "e0"})+ if code != 200:+ return+ got.append(("observe", ob["now"]["step"], out["took_effect"]))+ code, out2 = p["act"](seat, {"type": "move", "v": 0.2, "entity": "e0"}) # answers the act reply's `now`+ if code == 200:+ got.append(("act", out["now"]["step"], out2["took_effect"]))+ fin = run_all(svc, post, ["A", "B"], A={"act": act})+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert len(got) >= 4, got+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ ks = [r["k"] for r in rows if r["ev"] == "cmd" and r["seat"] == "A"]+ for kind, seen, eff in got:+ assert eff["seen_step"] == seen and eff["reaction_delay_steps"] == D, (kind, seen, eff)+ assert eff["step"] >= seen + D, (kind, seen, eff) # never earlier than s + D+ assert eff["step"] in ks, (eff, ks) # the logged (replayed) step is the effect step+ exact = sum(eff["step"] == seen + D for _, seen, eff in got)+ assert exact >= len(got) - 1, got # a fast program gets exactly D (50 ms per step)+++def test_reaction_delay_undeclared_unchanged():+ """No declaration: D = 0 in /spec, an act takes effect at the next control-step boundary, its reply as before."""+ svc, post = service(["A", "B"], fmt="duel")+ assert svc.react == 0 and svc.spec("A")[1]["timing"]["reaction_delay_steps"] == 0+ got = []++ def act(seat, p):+ if not got and svc.phase == "running":+ code, ob = p["observe"](seat, {})+ code, out = p["act"](seat, {"type": "move", "v": 0.3, "entity": "e0"})+ if code == 200:+ got.append((ob["now"]["step"], out["took_effect"]))+ fin = run_all(svc, post, ["A", "B"], A={"act": act})+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ seen, eff = got[0]+ assert "seen_step" not in eff and "reaction_delay_steps" not in eff and eff["step"] < seen + 4, got+++def test_reaction_delay_local_play_deterministic():+ """core/local.py plays by the same rule: an act answers the observation at k and takes effect at k + D; two runs+ give the same state digest, the episode replays to it in a fresh replay, and without the declaration the+ commands are where they were before (at the observation step)."""+ from core import local+ from core.episode import read_rows, replay++ class Mover:+ def __init__(self):+ self.n = 0++ def act(self, view):+ self.n += 1+ return {"type": "move", "entity": "e0", "v": round(0.1 * (self.n % 7) - 0.3, 3)}++ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=1.0)+ out = {}+ for name, plugin in (("D3", fixture_with_reaction_delay(3)), ("D3 again", fixture_with_reaction_delay(3)),+ ("none", PLUGIN)):+ d = Path(tempfile.mkdtemp(prefix="core-test-"))+ r = local.play(SPORT, cfg, {"A": Mover(), "B": Mover()}, data=d, render=False, plugin=plugin)+ rows = read_rows(d / "episode.jsonl")+ rep = replay(SPORT, rows)+ assert rep["state_sha"] == r["digest"] and rep["scores"] == r["scores"], (name, rep, r)+ out[name] = (r["digest"], [x["k"] for x in rows if x["ev"] == "cmd"])+ assert out["D3"] == out["D3 again"]+ assert out["D3"][1] and all(k % 5 == 3 for k in out["D3"][1]), out["D3"][1][:10]+ assert out["none"][1] and all(k % 5 == 0 for k in out["none"][1]) and out["none"][0] != out["D3"][0]+++def reaction_match(plugin, slow_s=0.35, slowdown=5.0, n=8):+ """A duel on the fixture at 50 ms per step: seat A is a fast player (acts right after each observation), seat B a+ slow one (thinks slow_s wall seconds between its observation and its act). Returns final.json, replay_check.json,+ the episode rows and what each act's reply said."""+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=slowdown)+ svc = RealtimeService(load_plugin(plugin), plugin, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ got = {"A": [], "B": []}++ def player(think):+ def act(seat, p):+ if len(got[seat]) >= n or svc.phase != "running":+ return+ code, ob = p["observe"](seat, {})+ if code != 200 or ob["now"]["phase"] != "running":+ return+ time.sleep(think)+ code, out = p["act"](seat, {"type": "move", "v": 0.1, "entity": "e0"})+ if code == 200:+ got[seat].append((ob["now"]["step"], out["took_effect"]))+ return act+ os.environ["READY_TIMEOUT_S"] = "5" # a loaded host: the slow seat still reviews in time+ try:+ fin = run_all(svc, post, ["A", "B"], A={"act": player(0.0)}, B={"act": player(slow_s)})+ finally:+ os.environ["READY_TIMEOUT_S"] = "1.5"+ assert fin["valid_trial"], {k: fin.get(k) for k in ("reason", "phase", "finalized", "deterministic", "errors")}+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ return fin, json.loads((svc.data / "replay_check.json").read_text()), rows, got+++def check_reaction_report(fin, rep, rows, D):+ """final.json `reaction` = the rows' numbers = the replay's, and grading never sees it."""+ from core.episode import reaction_report+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ r = fin["reaction"]+ assert r["policy"] == "report_only" and r["reaction_delay_steps"] == D and r["replayed"] is True, r+ assert rep["reaction"]["by_seat"] == r["by_seat"], (rep["reaction"], r)+ head = next(x for x in rows if x["ev"] == "header")+ assert head["timing"] == {"reaction_delay_steps": D, "effect_delay_steps": 0}, head+ assert reaction_report(rows, ("A", "B"), D)["by_seat"] == r["by_seat"]+ for seat in ("A", "B"):+ lags = sorted(x["k"] - x["seen"] for x in rows if x["ev"] == "cmd" and x["seat"] == seat+ and x.get("seen") is not None)+ b = r["by_seat"][seat]+ assert b["acts"] == len(lags) > 0 and b["within_d"] == sum(d <= D for d in lags), (seat, b, lags)+ assert b["share"] == round(b["within_d"] / b["acts"], 6) and b["delay_steps"]["max"] == lags[-1], b+ out = grade({"cfg": fin["cfg"], **fin}, rep, {}, lambda d: {})+ assert not any("reaction" in k or "within" in k for k in out), sorted(out)+ return r["by_seat"]+++def test_reaction_report_declared_delay():+ """core 0.2.23 (report only): with D declared, a fast player's acts all take effect within D (exactly D), a slow+ player's (0.35 s of thinking = 7 steps at 50 ms) none; final.json gives the counts, the share and the delay's+ median / p90 / max per seat, the fresh-process replay recomputes the same numbers, grading ignores them."""+ D = 2+ fin, rep, rows, got = reaction_match(fixture_with_reaction_delay(D))+ by = check_reaction_report(fin, rep, rows, D)+ a, b = by["A"], by["B"]+ assert a["within_d"] >= a["acts"] - 1 and a["delay_steps"]["median"] == D, a # D exactly when fast+ assert b["within_d"] == 0 and b["share"] == 0 and b["delay_steps"]["median"] >= D + 3, b+ for seen, eff in got["B"]: # the replies agree with the report+ assert eff["seen_step"] == seen and eff["step"] - seen > D, (seen, eff)+++def test_reaction_report_without_declared_delay():+ """D = 0 (not declared): within D means the next control-step boundary after the seen state; the slow player is+ never within it; the act replies are unchanged (no seen_step), the report is in final.json and the replay."""+ fin, rep, rows, got = reaction_match(PLUGIN)+ by = check_reaction_report(fin, rep, rows, 0)+ assert by["B"]["within_d"] == 0 and by["B"]["delay_steps"]["median"] >= 4, by["B"]+ assert by["A"]["delay_steps"]["median"] <= 1, by["A"]+ assert all("seen_step" not in eff for _, eff in got["A"] + got["B"])+++def test_reaction_report_rule_and_old_episodes():+ """reaction_report on rows: the layer's fixed effect delay counts as part of D; ticks (no `seen`) are not acts; an+ act whose seat had been sent no world state is `unseen`; an episode before 0.2.23 gives empty seats."""+ from core.episode import reaction_report+ rows = [{"ev": "cmd", "k": 10, "seat": "A", "cmd": {}, "seen": 7}, {"ev": "cmd", "k": 11, "seat": "A", "cmd": {}},+ {"ev": "cmd", "k": 20, "seat": "A", "cmd": {}, "seen": 14}, {"ev": "cmd", "k": 21, "seat": "B", "cmd": {},+ "seen": None}]+ r = reaction_report(rows, ("A", "B"), 2, 1)["by_seat"]+ assert r["A"] == {"acts": 2, "within_d": 1, "share": 0.5, "delay_steps": {"median": 4.5, "p90": 6, "max": 6},+ "unseen": 0}, r+ assert r["B"] == {"acts": 0, "within_d": 0, "share": None, "delay_steps": None, "unseen": 1}, r+ old = reaction_report([{"ev": "cmd", "k": 3, "seat": "A", "cmd": {}}], ("A",), 0)["by_seat"]+ assert old == {"A": {"acts": 0, "within_d": 0, "share": None, "delay_steps": None, "unseen": 0}}, old+++def test_local_play_team_channel_of_builtin_players():+ """core 0.2.21: a built-in player's optional message(view) goes on the team channel in local play as POST /say+ would (the channel's limits; a refused message is dropped), reaches its teammates' views (team_messages) and never+ the other side, is a `team` row of the episode, and changes nothing the replay sees."""+ from core import local+ from core.episode import read_rows, replay++ class Talker:+ def __init__(self, seat):+ self.seat, self.heard, self.n = seat, [], 0++ def act(self, view):+ self.heard += [(m["from"], m["text"]) for m in view["state"].get("team_messages") or []]+ self.n += 1+ return {"type": "move", "entity": "e0", "v": 0.1}++ def message(self, view):+ return f"{self.seat} {self.n}" if self.seat.endswith("1") else None++ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ cfg = MatchConfig(sport="fixture", format="team", seats=tuple(sides), seed=1, slowdown=1.0, sides=sides)+ d = Path(tempfile.mkdtemp(prefix="core-test-"))+ players = {s: Talker(s) for s in sides}+ r = local.play(SPORT, cfg, players, data=d, render=False, plugin=PLUGIN)+ rows = read_rows(d / "episode.jsonl")+ team = [x for x in rows if x["ev"] == "team"]+ assert team and {x["seat"] for x in team} == {"A1", "B1"}, team[:3]+ ks = [x["k"] for x in team if x["seat"] == "A1"]+ assert all(b - a >= 0.2 / SPORT.build(cfg).dt - 1e-9 for a, b in zip(ks, ks[1:])), ks[:5] # min_interval_s+ assert players["A2"].heard and all(f == "A1" for f, _ in players["A2"].heard)+ assert players["B2"].heard and all(f == "B1" for f, _ in players["B2"].heard)+ assert not players["A1"].heard and not players["B1"].heard # never their own, never the others'+ rep = replay(SPORT, rows)+ assert rep["state_sha"] == r["digest"] and rep["scores"] == r["scores"]+++def test_preview_format_is_never_official():+ """core 0.2.21: a format declared preview ([formats.<f>] preview = true, in the contract's formats) is never an+ official configuration, whatever its seed, level and first player; the same match in a non-preview format is."""+ from core.grading import official+ d = {"format": "tm", "seed": 202, "first": "A", "slowdown": 10.0, "play": "program",+ "cfg": {"seats": ["A1", "A2"], "level": 2}, "sides": {"A1": "A", "A2": "A"}}+ contract = {"official": {"seeds": [202], "levels": [2, 3], "first_any": True},+ "formats": {"tm": {"seats": ["A1", "A2"], "opponent": True, "preview": True}}}+ assert not official(d, contract)+ contract["formats"]["tm"].pop("preview")+ assert official(d, contract)+++def test_observation_query_and_runtime_whitelist():+ svc, post = service(["A", "B"], fmt="duel")+ th = [threading.Thread(target=post["start"], args=(s, {}), daemon=True) for s in "AB"]+ for t in th:+ t.start()+ while svc.phase != "running":+ time.sleep(0.01)+ code, out = post["observe"]("A", {"query": {"view": "near"}})+ assert code == 200 and out["now"]["view"] == "near"+ for bad in ({"query": {"view": "sideways"}}, {"query": "near"}):+ try:+ post["observe"]("A", bad)+ raise AssertionError(f"query {bad} accepted")+ except Refused:+ pass+ code, out = post["observe"]("A", {"query": {"view": "far"}}) # the sport leaks a field: dropped + error+ assert code == 200 and "secret_state" not in out["now"]+ assert any(e["where"] == "observation" for e in svc.errors)+ svc.end("collected")+ fin = finish(svc)+ assert not fin["valid_trial"]+++class start_window:+ """START_TIMEOUT_S for one test."""+ def __init__(self, s):+ self.s = s++ def __enter__(self):+ self.old, os.environ["START_TIMEOUT_S"] = os.environ.get("START_TIMEOUT_S"), str(self.s)++ def __exit__(self, *a):+ os.environ["START_TIMEOUT_S"] = self.old+++def graded(svc, fin):+ return grade(fin, json.loads((svc.data / "replay_check.json").read_text()), {}, lambda d: {})+++def check_no_show(svc, fin, absent="B", winner="A"):+ """The side that never started lost by forfeit, the trial is valid and replays; the grader agrees."""+ assert fin["reason"] == "no_show" and fin["forfeiting"] == absent, fin+ assert fin["match_winner"] == winner and fin["winner"] == winner and fin["decided_by"] == "forfeit:no_show"+ assert fin["valid_trial"] and fin["deterministic"] and not fin["technical_failure"], fin["errors"]+ assert fin["joined"][absent] is False and fin["steps"] == 0+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "forfeit" and r["seat"] == absent and r["why"] == "no_show" for r in rows)+ out = graded(svc, fin)+ assert out["valid_trial"] == 1 and out["success"] == 1 and out["no_show"] == 1, out+ assert out[f"{winner}_won"] == 1 and out[f"{absent}_won"] == 0 and out[f"{absent}_no_show"] == 1+ assert out[f"{winner}_no_show"] == 0+++def test_no_show_realtime_duel_present_side_wins():+ with start_window(1):+ svc, post = service(["A", "B"], fmt="duel")+ threading.Thread(target=post["start"], args=("A", {}), daemon=True).start() # B never starts+ fin = finish(svc)+ assert svc.spec("A")[1]["start"]["window_s"] == 1.0+ check_no_show(svc, fin)+++def test_no_show_turn_duel_present_side_wins():+ with start_window(1):+ svc, post = turn_service(["A", "B"])+ assert post["start"]("B", {})[0] == 200 # A never starts+ fin = finish(svc)+ check_no_show(svc, fin, absent="A", winner="B")+ assert "start" in svc.spec("B")[1]+++def test_no_show_turn_duel_late_start_refused():+ with start_window(1):+ svc, post = turn_service(["A", "B"])+ post["start"]("A", {})+ fin = finish(svc)+ assert post["start"]("B", {})[0] == 409 # the window has closed+ check_no_show(svc, fin)+++def test_no_show_nobody_started_is_invalid():+ for make, reason in ((lambda: service(["A", "B"], fmt="duel"), "collected"),+ (lambda: turn_service(["A", "B"]), "incomplete")):+ svc, post = make()+ time.sleep(0.6)+ svc.collect() # the session ends, nobody started+ fin = finish(svc)+ assert fin["reason"] == reason and fin["winner"] is None and fin["match_winner"] is None, fin+ assert not fin["valid_trial"] and fin["forfeiting"] is None+ out = graded(svc, fin)+ assert out["valid_trial"] == 0 and out["success"] == 0 and out["no_show"] == 0+++def test_no_show_every_side_absent_after_the_window_is_invalid():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ with start_window(1): # one home seat started: no side complete when the window closes+ svc, post = service(list(sides), sides)+ threading.Thread(target=post["start"], args=("A1", {}), daemon=True).start()+ fin = finish(svc)+ assert fin["reason"] == "incomplete" and fin["winner"] is None and not fin["valid_trial"], fin+ with start_window(1):+ svc, post = turn_service(list(sides), sides, fmt="team")+ post["start"]("B2", {})+ fin = finish(svc)+ assert fin["reason"] == "incomplete" and fin["winner"] is None and not fin["valid_trial"], fin+++def test_no_show_team_side_with_a_missing_seat_loses():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ with start_window(1):+ svc, post = turn_service(list(sides), sides, fmt="team")+ for s in ("A1", "B1", "B2"): # A2 never starts+ post["start"](s, {})+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["forfeiting"] == "A2" and fin["match_winner"] == "away", fin+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++def check_single_no_show(svc, fin):+ """A single side that never started: a valid loss by forfeit (no_show), replayed; success 0."""+ assert fin["reason"] == "no_show" and fin["forfeiting"] == "A" and fin["winner"] is None, fin+ assert fin["valid_trial"] and fin["deterministic"] and fin["decided_by"] == "forfeit:no_show", fin["errors"]+ assert fin["joined"]["A"] is False and fin["steps"] == 0, fin+ out = graded(svc, fin)+ assert out["valid_trial"] == 1 and out["success"] == 0 and out["no_show"] == 1 and out["A_no_show"] == 1, out+ assert out["A_won"] == 0 and out["abandoned"] == 0, out+++def test_no_show_single_player_valid_loss():+ """One side: the window opens at the service start; not started when it closes = a valid loss (no_show, success+ 0). A session that ends before the window closes is the same valid loss, decided at the collect (core 0.2.7)."""+ for make in (lambda: service(["A"], fmt="single"), lambda: turn_service(["A"], fmt="single")):+ with start_window(1):+ svc, post = make()+ fin = finish(svc)+ check_single_no_show(svc, fin)+ assert fin["elapsed_s"] >= 0.9, fin["elapsed_s"]+++# ---------------------------------------------- a session that ends before its side started (core 0.2.7, core rule 5)+def collect_rows(svc):+ return [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()+ if json.loads(x)["ev"] == "collect_before_start"]+++def test_prestart_single_collected_before_the_window_is_no_show():+ """The single side's session ends inside the start window (5 s here) without a start: no_show at once, a valid+ loss (cores 0.2.2-0.2.6: an unfinished, invalid match, "collected" / "incomplete")."""+ for make in (lambda: service(["A"], fmt="single"), lambda: turn_service(["A"], fmt="single")):+ svc, post = make()+ time.sleep(0.3)+ t = time.time()+ svc.collect()+ fin = finish(svc)+ check_single_no_show(svc, fin)+ assert time.time() - t < 4, "decided at the collect, not when the window closes"+ assert collect_rows(svc) and collect_rows(svc)[0]["absent"] == ["A"]+++def test_prestart_duel_collected_before_the_window_absent_side_loses():+ """Two sides, one started, the other never; the sessions end inside the window: the absent side loses (no_show,+ valid), the present side wins, as when the window closes (core rule 5)."""+ svc, post = service(["A", "B"], fmt="duel")+ threading.Thread(target=post["start"], args=("A", {}), daemon=True).start() # B never starts+ t = time.time()+ while not svc.seats["A"].joined and time.time() - t < 5:+ time.sleep(0.01)+ svc.collect()+ fin = finish(svc)+ check_no_show(svc, fin)+ svc, post = turn_service(["A", "B"])+ assert post["start"]("B", {})[0] == 200 # A never starts+ svc.collect()+ fin = finish(svc)+ check_no_show(svc, fin, absent="A", winner="B")+ assert collect_rows(svc)[0]["absent"] == ["A"]+++def test_prestart_no_show_check_accepts_a_forfeit_hook_that_ends_the_world():+ """core 0.2.21: the generic check prestart_no_show (core/testkit.py) asks for the forfeit's decision at step 0,+ not for an unfinished world. A sport whose forfeit hook ends its world (the game over, the winner set) is+ decided the same way (the forfeit comes first in core.outcome.decide); cores 0.2.7-0.2.11 failed it."""+ from core import testkit+ cfg = MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")+ game = type(SPORT_TURN.build(cfg))+ decl = {"formats": {"single": {"seats": ["A"]}, "duel": {"seats": ["A", "B"], "first": ["A", "B"]}},+ "modes": {"action_levels": ["low"]}}+ plain = testkit.t_prestart_no_show(SPORT_TURN, PLUGIN_TURN, decl)+ phase = game.phase++ def forfeit(self, seat, why):+ self.ended = why+ return True+ game.forfeit = forfeit+ game.phase = lambda self: Phase(FINISHED, reason=self.ended) if getattr(self, "ended", None) else phase(self)+ try:+ ended = testkit.t_prestart_no_show(SPORT_TURN, PLUGIN_TURN, decl)+ finally:+ del game.forfeit+ game.phase = phase+ for rows, finished in ((plain, False), (ended, True)):+ assert [r["name"] for r in rows] == ["prestart_no_show:single", "prestart_no_show:duel"], rows+ assert all(r["ok"] for r in rows), rows+ assert all(json.loads(r["detail"])["finished"] is finished for r in rows), rows+++def test_prestart_team_side_with_a_missing_seat_loses_at_the_collect():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ svc, post = turn_service(list(sides), sides, fmt="team")+ for s in ("A1", "B1", "B2"): # A2 never starts+ post["start"](s, {})+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["forfeiting"] == "A2" and fin["match_winner"] == "away", fin+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ out = graded(svc, fin)+ assert out["A2_no_show"] == 1 and out["A1_no_show"] == 0 and out["B1_won"] == 1 and out["A1_won"] == 0, out+++def test_prestart_no_side_present_at_the_collect_does_not_count():+ """No side complete (one home seat started): the collect leaves the match unfinished, as before core 0.2.7."""+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ for make, reason in ((lambda: service(list(sides), sides), "collected"),+ (lambda: turn_service(list(sides), sides, fmt="team"), "incomplete")):+ svc, post = make()+ threading.Thread(target=post["start"], args=("A1", {}), daemon=True).start()+ t = time.time()+ while not svc.seats["A1"].joined and time.time() - t < 5:+ time.sleep(0.01)+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == reason and fin["forfeiting"] is None and fin["winner"] is None, fin+ assert not fin["valid_trial"] and graded(svc, fin)["no_show"] == 0 and not collect_rows(svc), fin+++def test_prestart_n_sides_collect():+ """Three sides: one absent at the collect retires (the sport allows it) and the match, never begun, ends+ unfinished; two absent: the first retires, the second forfeits and the present side wins (as at the window)."""+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ for s in ("B", "C"):+ post["start"](s, {})+ svc.collect()+ fin = finish(svc)+ assert fin["retired"] == ["A"] and fin["reason"] == "incomplete" and not fin["valid_trial"], fin+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ post["start"]("C", {})+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["match_winner"] == "C" and fin["retired"] == ["A"], fin+ assert fin["ranking"] == ["C", "B", "A"] and fin["valid_trial"], fin+++def test_no_show_n_sides_absent_side_retires_others_play():+ with start_window(1):+ svc, post = service(["A", "B", "C"], fmt="multi")++ def mover(v):+ return lambda seat, p: p["act"](seat, {"type": "move", "v": v, "entity": "e0"})+ fin = run_all(svc, post, ["A", "B"], A={"act": mover(0.2)}, B={"act": mover(0.1)}) # C never starts+ assert fin["retired"] == ["C"] and fin["reason"] == "match_over", fin+ assert fin["ranking"] == ["A", "B", "C"] and fin["valid_trial"] and fin["deterministic"], \+ {k: fin[k] for k in ("ranking", "valid_trial", "deterministic", "finalized", "scores", "replay_scores", "steps")}+ with start_window(1):+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("B", .9), ("C", .1))]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["retired"] == ["A"] and fin["reason"] == "match_over", fin+ assert fin["ranking"] == ["B", "C", "A"] and fin["match_winner"] == "B", fin+ assert fin["valid_trial"] and fin["deterministic"], {k: fin[k] for k in ("finalized", "scores", "replay_scores")}+ with start_window(1): # two of three absent: the first retires, the second forfeits+ svc, post = turn_service(["A", "B", "C"], fmt="multi")+ post["start"]("C", {})+ fin = finish(svc)+ assert fin["reason"] == "no_show" and fin["match_winner"] == "C" and fin["retired"] == ["A"], fin+ assert fin["ranking"] == ["C", "B", "A"] and fin["valid_trial"], fin+++def test_turn_duel_plays_to_the_end():+ svc, post = turn_service(["A", "B"])+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("A", .3), ("B", .6))]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["reason"] == "match_over" and fin["match_winner"] == "B" and fin["valid_trial"], fin+ assert fin["deterministic"], fin["errors"]+++class Stub:+ def __init__(self, sc, finished=True, rules=None, rank=None):+ self.sc, self.fin, self.rules, self.rank = sc, finished, rules, rank++ def scores(self):+ return self.sc++ def phase(self):+ return Phase(FINISHED if self.fin else PLAYING)++ def tiebreaks(self):+ return self.rules if self.rules is not None else [("last", lambda m: "B")]++ def ranking(self):+ return self.rank+++def test_outcome_rules():+ assert decide(Stub({"A": 30}, rules=[]), sides=["A"]).solo # solo: no winner+ assert decide(Stub({"A": 30}, rules=[]), sides=["A"]).winner is None+ assert decide(Stub({"A": 1, "B": 1}), sides=["A", "B"]).winner == "B" # last tiebreak decides+ assert decide(Stub({"A": 1, "B": 1}), "A", "clock", ["A", "B"]).winner == "B"+ o = decide(Stub({"A": 1, "B": 3, "C": 2}, rank=["B", "C", "A"]), sides=["A", "B", "C"])+ assert o.winner == "B" and o.ranking == ["B", "C", "A"]+ try:+ decide(Stub({"A": 1, "B": 1}, rules=[("x", lambda m: None)]), sides=["A", "B"])+ raise AssertionError("a draw was accepted")+ except RuntimeError:+ pass+ assert decide(Stub({"A": 1, "B": 1}, finished=False), sides=["A", "B"]).winner is None+++def test_grading_success_rules():+ assert line_ok(30, {"score_at_least": 30}) and not line_ok(29, {"score_at_least": 30})+ assert line_ok(3, {"score_at_most": 4})+ base = {"cfg": {"seats": ["A"]}, "sides": {"A": "A"}, "deterministic": True, "state_sha": "s", "scores": {"A": 31},+ "match_winner": None, "commands_sha": "c", "source_sha": "x", "steps": 5, "reason": "match_over",+ "valid_trial": True, "finalized": True, "errors": [], "meter_error": {}, "proxy_error": {}, "solo": True,+ "transient_api_errors": {}, "unrecovered_api_errors": {}, "player_modes": {"A": "oracle"},+ "format": "single", "play": "program"}+ rc = {"state_sha": "s", "scores": {"A": 31}, "winner": None, "commands_sha": "c", "source_sha": "x", "k": 5}+ contract = {"formats": {"single": {"success": {"score_at_least": 30}}}}+ assert grade(base, rc, contract, lambda d: {})["success"] == 1+ low = dict(base, scores={"A": 20})+ assert grade(low, dict(rc, scores={"A": 20}), contract, lambda d: {})["success"] == 0+ opp = dict(base, solo=False, match_winner="opponent") # single vs a scripted opponent+ assert grade(opp, dict(rc, winner="opponent"), contract, lambda d: {})["success"] == 0+ opp = dict(base, solo=False, match_winner="A")+ assert grade(opp, dict(rc, winner="A"), contract, lambda d: {})["success"] == 1+++def test_launch_seat_env_second_account_and_route():+ from core.launch import PROXY, seat_env+ env = {"KEY_ACCOUNT": "t1", "KEY_ACCOUNT_2": "t2", "THINK_OPENAI_ROUTE": "openrouter",+ "RO_SEAT_SELECT_A": "KEY_ACCOUNT=KEY_ACCOUNT_2", "RO_SEAT_SELECT_B": "",+ "RO_SEAT_ENV_THINK_OPENAI_ROUTE_B": "azure", "RO_SEAT_ENV_THINK_OPENAI_ROUTE_A": ""}+ a, b = seat_env("A", env, ["A", "B"]), seat_env("B", env, ["A", "B"])+ assert a["KEY_ACCOUNT"] == "t2" and b["KEY_ACCOUNT"] == "t1"+ assert a["THINK_OPENAI_ROUTE"] == "openrouter" and b["THINK_OPENAI_ROUTE"] == "azure"+ assert a["THINK_USAGE_FILE"].endswith("think_usage_A.json") and a["THINK_CLIENT_HOST"] == "seat_a"+ assert PROXY.parts[-2:] == ("metering", "think_proxy.py") # where tools/sportlib.py puts the proxy+++def test_launch_seat_env_holds_no_other_seats_variables():+ """After the mapping a proxy has no RO_SEAT_* and no other seat's per-seat variable; a seat on route chatgpt keeps+ only the credentials given to it alone (no task-wide key)."""+ from core.launch import seat_env+ env = {"SUB_TOKEN": "", "TASK_KEY": "task-key", "THINK_OPENAI_ROUTE": "azure", "SUB_TOKEN_A": "raw-a",+ "PLAYER_MODE_A": "model", "PLAYER_MODE_B": "model", "RO_SEAT_SELECT_A": "", "RO_SEAT_SELECT_B": ""}+ for s, tok, route in (("A", "secret-a", "chatgpt"), ("B", "secret-b", "chatgpt"), ("C", "", "azure")):+ env.update({f"RO_SEAT_ENV_SUB_TOKEN_{s}": tok, f"RO_SEAT_ENV_TASK_KEY_{s}": "",+ f"RO_SEAT_ENV_THINK_OPENAI_ROUTE_{s}": route, f"RO_SEAT_ENV_THINK_MODEL_{s}": f"model-{s}"})+ a, b, c = (seat_env(s, env, ["A", "B", "C"]) for s in "ABC")+ for e, own, others in ((a, "secret-a", ("secret-b",)), (b, "secret-b", ("secret-a", "raw-a")),+ (c, None, ("secret-a", "secret-b", "raw-a"))):+ assert not [k for k in e if k.startswith(("RO_SEAT_ENV_", "RO_SEAT_SELECT_"))], sorted(e)+ assert not [k for k, v in e.items() for x in others if x in v], sorted(e.items())+ assert e.get("SUB_TOKEN") == (own if own else "")+ assert "TASK_KEY" not in a and "TASK_KEY" not in b and c["TASK_KEY"] == "task-key" # route chatgpt: no task key+ assert (a["THINK_MODEL"], b["THINK_MODEL"], c["THINK_MODEL"]) == ("model-A", "model-B", "model-C")+ assert "PLAYER_MODE_B" not in a and "PLAYER_MODE_A" not in b and "SUB_TOKEN_A" in a+++# ------------------------------------------------------------------ the spectator scene (core 0.2.4, renderer rule 6)+_ARM = ('<mujoco><worldbody><light pos="0 0 3" dir="0 0 -1"/><body name="arm" pos="0 0 .2"><joint axis="0 0 1"/>'+ '<geom name="arm_c" type="box" size=".05 .05 .2" rgba=".8 .2 .2 1"/></body></worldbody></mujoco>')+_MODEL = ('<mujoco><asset><mesh name="m" file="tetra.obj"/></asset><worldbody>'+ '<body name="arm"><geom type="mesh" mesh="m" rgba=".1 .3 .9 1" contype="0" conaffinity="0" group="2"/>'+ '</body></worldbody></mujoco>')+++def test_spectator_scene_is_the_presentation_scene_and_players_keep_the_match_scene():+ from core.observe import CameraWorker+ from core.spectator import spectator_scene+ from renderers.base import Scene++ class Sport:+ def scene(self, cfg):+ return Scene(xml=_ARM)++ cfg = MatchConfig(sport="x", format="single", seats=("A",), seed=1)+ with tempfile.TemporaryDirectory() as tmp:+ plugin = Path(tmp) / "plugin.py"+ sc, what = spectator_scene(Sport(), str(plugin), cfg) # no presentation/: the match scene+ assert what == "match" and not sc.is_presentation+ d = Path(tmp) / "presentation"+ d.mkdir()+ (d / "arm.xml").write_text(_MODEL)+ (d / "tetra.obj").write_text("v -.1 -.1 0\nv .1 -.1 0\nv 0 .1 0\nv 0 0 .4\nf 1 3 2\nf 1 2 4\nf 2 3 4\nf 3 1 4\n")+ (d / "presentation.toml").write_text('[presentation]\nversion = 1\n[[presentation.robot]]\n'+ 'model = "./arm.xml"\nbodies = "arm"\nbody = "arm"\n')+ sc, what = spectator_scene(Sport(), str(plugin), cfg)+ assert what == "presentation" and sc.is_presentation and "_vis:arm:0" in sc.xml+ os.environ["RO_VIDEO_SCENE"] = "match"+ try:+ sc2, what2 = spectator_scene(Sport(), str(plugin), cfg)+ finally:+ del os.environ["RO_VIDEO_SCENE"]+ assert what2 == "match" and not sc2.is_presentation+ (d / "presentation.toml").write_text('[presentation]\nversion = 1\n[[presentation.robot]]\n'+ 'model = "not_in_the_manifest"\nbodies = "arm"\nbody = "arm"\n')+ sc3, what3 = spectator_scene(Sport(), str(plugin), cfg) # a broken presentation: the match scene+ assert what3.startswith("match (presentation unavailable") and not sc3.is_presentation+ try:+ CameraWorker(sc, None)+ raise AssertionError("players' images must refuse a presentation scene")+ except ValueError:+ pass++++def test_players_scene_is_the_presentation_scene_only_when_declared():+ """core 0.2.9, renderer rule 6: a presentation.toml with `players` = the players' images use it (CameraWorker+ accepts it, the same kinematics checked); without, the match scene."""+ from core.observe import CameraWorker, players_scene+ from core.spectator import spectator_scene+ from renderers.base import CameraDef, Scene+ from renderers.label import frame_label++ class Sport:+ def scene(self, cfg):+ return Scene(xml=_ARM)++ cfg = MatchConfig(sport="x", format="single", seats=("A",), seed=1)+ cam = CameraDef("c", pos=(1.2, -1.2, 0.8), lookat=(0, 0, 0.2), width=64, height=48).to_dict()+ with tempfile.TemporaryDirectory() as tmp:+ plugin = Path(tmp) / "plugin.py"+ assert not players_scene(Sport(), str(plugin), cfg).is_presentation # no presentation/+ d = Path(tmp) / "presentation"+ d.mkdir()+ (d / "arm.xml").write_text(_MODEL)+ (d / "tetra.obj").write_text("v -.1 -.1 0\nv .1 -.1 0\nv 0 .1 0\nv 0 0 .4\nf 1 3 2\nf 1 2 4\nf 2 3 4\nf 3 1 4\n")+ decl = '[presentation]\nversion = 2\n[[presentation.robot]]\nmodel = "./arm.xml"\nbodies = "arm"\nbody = "arm"\n'+ (d / "presentation.toml").write_text(decl)+ sc = players_scene(Sport(), str(plugin), cfg)+ assert not sc.is_presentation # spectators only+ (d / "presentation.toml").write_text(decl.replace("version = 2\n", 'version = 2\nplayers = "full"\n'))+ sc = players_scene(Sport(), str(plugin), cfg)+ assert sc.is_presentation and sc.players and "_vis:arm:0" in sc.xml+ w = CameraWorker(sc, None)+ fine = w.draw({"qpos": [0.3]}, [cam])+ plain = CameraWorker(Scene(xml=_ARM), None).draw({"qpos": [0.3]}, [cam])+ assert fine["png"] != plain["png"] and fine["renderer"] == "mujoco"+ assert frame_label(w.renderer, sc) is None # the competition picture: no tag+ sp, what = spectator_scene(Sport(), str(plugin), cfg)+ assert what == "presentation" and sp.is_presentation+ (d / "presentation.toml").write_text(decl.replace("version = 2\n", 'version = 2\nplayers = "fine"\n'))+ try:+ players_scene(Sport(), str(plugin), cfg)+ raise AssertionError("players must be full or a level of detail")+ except ValueError as e:+ assert "players" in str(e)+++# ---- core 0.2.14: hidden official seeds (core/seeds.py) and the continuous score (core/score.py) ---------------+def test_hidden_seed_commitments():+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 3, "single/L1": 2, "single/L2": 2}, avoid=[1, 2, 3])+ pub = seeds.public(priv)+ flat = [e["seed"] for v in priv["cells"].values() for e in v]+ assert pub["counts"] == {"duel": 3, "single/L1": 2, "single/L2": 2} and len(set(flat)) == 7 # no shared seeds+ assert all(seeds.SEED_RANGE[0] <= x <= seeds.SEED_RANGE[1] for x in flat)+ assert not any(str(x) in json.dumps(pub) for x in flat) # the public part names no seed+ for cell, entries in priv["cells"].items():+ fmt, _, lv = cell.partition("/L")+ for i, e in enumerate(entries):+ c = seeds.commitment("fixture_turn", e["seed"], e["salt"])+ assert seeds.index("fixture_turn", fmt, int(lv) if lv else None, c, pub) == i+ assert seeds.resolve(priv, cell, i, pub) == (e["seed"], e["salt"])+ e = priv["cells"]["single/L1"][0]+ c = seeds.commitment("fixture_turn", e["seed"], e["salt"])+ assert seeds.index("fixture_turn", "single", 2, c, pub) is None # another cell (level)+ assert seeds.index("fixture_turn", "duel", None, c, pub) is None # another cell (format)+ assert seeds.index("fixture_turn", "single", 1, seeds.commitment("fixture_turn", e["seed"], "0" * 32), pub) is None+ assert seeds.index("fixture_turn", "single", 1, None, pub) is None # no proof+ assert seeds.cell_of("duel", 2, pub["cells"]) == "duel" # a fixed level the sim reports+ forged = dict(pub, cells=dict(pub["cells"], duel=pub["cells"]["duel"][:-1] + ["ab" * 32]))+ assert seeds.index("fixture_turn", "duel", None, "ab" * 32, forged) is None # not the registered list+ try:+ seeds.resolve(seeds.new("fixture_turn", {"duel": 3, "single/L1": 2, "single/L2": 2}), "duel", 0, pub)+ raise AssertionError("a different private set resolved against the registration")+ except ValueError:+ pass+ s = seeds.scrub({"seed": 5, "x": {"rng_seed": 7, "v": [123456, "123456", 2.5]}, "step": 123456,+ "salt": "ab" * 16}, 123456, "ab" * 16)+ assert s == {"seed": -1, "x": {"rng_seed": -1, "v": [-1, "-1", 2.5]}, "step": 123456, "salt": "-1"}, s+++def hidden_turn_duel(seed, salt, index=None):+ """A turn duel of the fixture played to the end at `seed`, with the runner's salt (and the seed itself, for the+ fresh-process replay) in the sim's environment."""+ env = {"RO_SEED_SALT": salt or "", "RO_SEED": str(seed), "RO_SEED_INDEX": "" if index is None else str(index)}+ os.environ.update(env)+ try:+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=seed, first="A",+ action_level="low")+ svc = TurnService(SPORT_TURN, PLUGIN_TURN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("A", .3), ("B", .6))]+ for t in th:+ t.start()+ return svc, finish(svc)+ finally:+ for k in env:+ os.environ.pop(k, None)+++def test_hidden_seed_official_only_when_registered():+ """The verifier counts a match as official only when its commitment is in the registered cell (core 0.2.14)."""+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 3, "single": 2})+ reg = seeds.public(priv)+ e = priv["cells"]["duel"][1]+ svc, fin = hidden_turn_duel(e["seed"], e["salt"], 1)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["seed_proof"] == {"commitment": seeds.commitment("fixture_turn", e["seed"], e["salt"]), "index": 1}+ rc = json.loads((svc.data / "replay_check.json").read_text())+ assert rc["seed_commitment"] == fin["seed_proof"]["commitment"]+ contract = {"sport": "fixture_turn", "official": {"hidden_seeds": reg, "seeds": [e["seed"]], "first_any": True}}+ out = grade(fin, rc, contract, lambda d: {})+ assert out["official_config"] == 1 and out["hidden_seed"] == 1 and out["hidden_seed_index"] == 1, out+ assert out["seed"] == -1+ bad = dict(fin, seed_proof={"commitment": seeds.commitment("fixture_turn", e["seed"], "0" * 32)})+ out = grade(bad, dict(rc, seed_commitment=bad["seed_proof"]["commitment"]), contract, lambda d: {})+ assert out["official_config"] == 0 and out["hidden_seed"] == 0 and out["hidden_seed_index"] == -1+ out = grade(dict(fin, format="single"), rc, contract, lambda d: {}) # another cell+ assert out["hidden_seed"] == 0+ out = grade(dict(fin, seed_proof=None), rc, contract, lambda d: {}) # a public seed is not enough+ assert out["official_config"] == 0 and out["hidden_seed"] == 0+ other = seeds.public(seeds.new("fixture_turn", {"duel": 3, "single": 2})) # an unregistered set+ out = grade(fin, rc, dict(contract, official=dict(contract["official"], hidden_seeds=other)), lambda d: {})+ assert out["official_config"] == 0+ out = grade(fin, dict(rc, seed_commitment="ab" * 32), contract, lambda d: {}) # the replay must agree+ assert out["deterministic"] == 0 and out["official_config"] == 1 and out["valid_trial"] == 0+ svc2, fin2 = hidden_turn_duel(7, None) # no salt: an ordinary seed+ assert fin2["seed_proof"] is None and fin2["seed"] == 7+ assert grade(fin2, json.loads((svc2.data / "replay_check.json").read_text()), contract,+ lambda d: {})["official_config"] == 0+++def test_hidden_seeds_override_the_sports_official_rule():+ """Core 0.2.19: with a registered hidden seed set the sport's own official_config (a legacy public-seed rule in+ tests/sport_grade.py) cannot make a match official: only a registered hidden seed of the match's cell counts, and+ the sport's rule can only lower it."""+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 3, "single": 2})+ reg = seeds.public(priv)+ e = priv["cells"]["duel"][0]+ svc, fin = hidden_turn_duel(e["seed"], e["salt"], 0)+ rc = json.loads((svc.data / "replay_check.json").read_text())+ contract = {"sport": "fixture_turn", "official": {"hidden_seeds": reg, "first_any": True}}+ legacy = lambda d: {"official_config": 1} # noqa: E731 a sport that always says 1+ defer = lambda d: {} # noqa: E731 a sport that keeps the core's+ lower = lambda d: {"official_config": 0} # noqa: E731 e.g. its slowdown rule fails+ assert grade(fin, rc, contract, legacy)["official_config"] == 1 # hidden seed of the cell: official+ assert grade(fin, rc, contract, defer)["official_config"] == 1+ assert grade(fin, rc, contract, lower)["official_config"] == 0 # the sport can lower it+ svc2, pub = hidden_turn_duel(7, None) # a public seed: never official once frozen+ rc2 = json.loads((svc2.data / "replay_check.json").read_text())+ assert pub["seed_proof"] is None+ assert grade(pub, rc2, contract, legacy)["official_config"] == 0+ out = grade(dict(fin, format="single"), rc, contract, legacy) # a commitment of another cell+ assert out["official_config"] == 0 and out["hidden_seed"] == 0+ assert grade(pub, rc2, {"sport": "fixture_turn", "official": {}}, legacy)["official_config"] == 1 # not frozen+++def test_hidden_seed_is_never_written():+ """A hidden seed and its salt appear in no record of the match (episode, final.json, replay check, broadcast log,+ reward) nor in a reply to a player; the fresh-process replay still reproduces the match (core 0.2.14)."""+ from core import seeds+ priv = seeds.new("fixture_turn", {"duel": 2})+ e = priv["cells"]["duel"][0]+ svc, fin = hidden_turn_duel(e["seed"], e["salt"], 0)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["sport_fields"]["seed"] == -1 and fin["sport_fields"]["draws"] == [-1, 1]+ assert fin["cfg"]["seed"] == -1 and fin["seed"] == -1+ out = grade(fin, json.loads((svc.data / "replay_check.json").read_text()),+ {"sport": "fixture_turn", "official": {"hidden_seeds": seeds.public(priv)}}, lambda d: {})+ assert out["hidden_seed"] == 1 and out["seed"] == -1+ texts = {f.name: f.read_text() for f in svc.data.iterdir() if f.is_file() and f.suffix in (".json", ".jsonl")}+ texts["reward"] = json.dumps(out)+ os.environ.update(RO_SEED_SALT=e["salt"])+ try:+ texts["spec"] = json.dumps(svc.public(svc.spec("A")[1]))+ texts["observe"] = json.dumps(svc.public(svc.routes(True)["observe"]("A", {})[1]))+ finally:+ os.environ.pop("RO_SEED_SALT", None)+ assert "episode.jsonl" in texts and "replay_check.json" in texts and "final.json" in texts+ for name, text in texts.items():+ assert str(e["seed"]) not in text and e["salt"] not in text, name+ head = json.loads((svc.data / "episode.jsonl").read_text().splitlines()[0])+ assert head["cfg"]["seed"] == -1 and head["seed_hidden"]["commitment"] == fin["seed_proof"]["commitment"]+ from core.episode import header_cfg+ try:+ header_cfg(head) # an offline replay needs the seed from the host+ raise AssertionError("a hidden-seed episode replayed without its seed")+ except ValueError:+ pass+ os.environ.update(RO_SEED=str(e["seed"] + 1), RO_SEED_SALT=e["salt"])+ try:+ header_cfg(head)+ raise AssertionError("a wrong seed was accepted for a hidden-seed episode")+ except ValueError:+ pass+ finally:+ os.environ.pop("RO_SEED", None), os.environ.pop("RO_SEED_SALT", None)+++def test_continuous_score_in_final_reward_and_replay():+ svc, fin = hidden_turn_duel(5, None)+ c = fin["continuous"]+ assert c["name"] == "score_share" and c["higher_is_better"] is True and c["forfeited"] == []+ assert abs(c["by_side"]["A"] - .3 / .9) < 1e-6 and abs(c["by_side"]["B"] - .6 / .9) < 1e-6, c+ rc = json.loads((svc.data / "replay_check.json").read_text())+ assert rc["continuous"] == c["by_side"]+ out = grade(fin, rc, {"sport": "fixture_turn", "score": {"forfeit": 0.0}}, lambda d: {})+ assert out["A_continuous_score"] == c["by_side"]["A"] and out["B_continuous_score"] == c["by_side"]["B"]+ assert "continuous_score" not in out # two sides: per seat only+ out = grade(dict(fin, continuous=dict(c, by_side={"A": 0.9, "B": 0.1})), rc, {}, lambda d: {})+ assert out["deterministic"] == 0 and out["valid_trial"] == 0 # the replay must agree+++def test_continuous_score_forfeit_value_on_no_show():+ with start_window(1):+ svc, post = turn_service(["A", "B"])+ assert post["start"]("A", {})[0] == 200 # B never starts+ fin = finish(svc)+ check_no_show(svc, fin)+ assert fin["continuous"]["by_side"] == {"A": 0.5, "B": 0.0} and fin["continuous"]["forfeited"] == ["B"]+ out = graded(svc, fin)+ assert out["A_continuous_score"] == 0.5 and out["B_continuous_score"] == 0.0+++def test_continuous_score_rules():+ from core import score+ decl = {"score": {"name": "x", "text": "t", "from": "share", "forfeit": 0.0}, "formats": {"d": {"seats": ["A", "B"]}}}+ m = Stub({"A": 3, "opponent": 1})+ assert score.compute(m, decl, ["A"])["by_side"] == {"A": 0.75} # against a scripted opponent+ assert score.compute(Stub({"A": 0, "B": 0}), decl, ["A", "B"])["by_side"] == {"A": 0.5, "B": 0.5}+ assert score.compute(m, decl, ["A"], forfeited=["A"])["by_side"] == {"A": 0.0}+ d = {"score": dict(decl["score"], **{"from": "margin", "forfeit": -10})}+ assert score.compute(Stub({"A": 1, "B": 4, "C": 2}), d, ["A", "B"])["by_side"] == {"A": -3.0, "B": 2.0}+ d = {"score": dict(decl["score"], **{"from": "own"})}+ assert score.compute(Stub({"A": 31}), d, ["A"])["by_side"] == {"A": 31.0}+ assert score.compute(m, {}, ["A"]) is None # not declared: nothing+ h = Stub({"A": 0})+ h.continuous_score = lambda: {"A": float("nan")}+ try:+ score.compute(h, {"score": dict(decl["score"], **{"from": "hook"})}, ["A"])+ raise AssertionError("a non-finite continuous score was accepted")+ except RuntimeError:+ pass+ assert score.problems(decl, False) == []+ assert score.problems({"score": {"name": "Bad name", "from": "hook", "forfeit": "x"}}, False)+ solo = {"score": dict(decl["score"]), "formats": {"s": {"seats": ["A"]}}}+ assert any("opponent" in p for p in score.problems(solo, False))+++# ------------------------------------------------------------------ core 0.2.15: a layer's tick+def test_layer_tick_is_applied_logged_and_replayed():+ """An action layer's tick(seat, match) (the skill in the loop's step(), skilleval/inloop.py) runs every control+ step before the actions: its command is applied, logged as a command row and the episode replays without the+ layer (core/local.py and core/realtime.py share the rule)."""+ from core import local+ from core.episode import read_rows, replay++ class Tick(SPORT.action_layer("low").__class__):+ def tick(self, seat, match):+ return {"type": "move", "entity": "e0", "v": 0.25 if (match.k // 10) % 2 else -0.5} \+ if match.k % 10 == 0 else None++ class WithTick:+ def __getattr__(self, k):+ return getattr(SPORT, k)++ def action_layer(self, level):+ return Tick(0)++ class Idle:+ def act(self, view):+ return None++ cfg = MatchConfig(sport="fixture", format="solo", seats=("A",), seed=1, slowdown=1.0)+ d = Path(tempfile.mkdtemp(prefix="core-test-"))+ r = local.play(WithTick(), cfg, {"A": Idle()}, data=d, render=False)+ rows = read_rows(d / "episode.jsonl")+ cmds = [x for x in rows if x["ev"] == "cmd"]+ assert len(cmds) == 9 and all(c["cmd"]["entity"] == "e0" for c in cmds), cmds[:3]+ assert r["scores"]["A"] != 0+ rep = replay(SPORT, rows)+ assert rep["state_sha"] == r["digest"] and rep["scores"] == r["scores"], (rep, r)+++def main():+ tests = [(n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)]+ bad = 0+ for name, f in tests:+ t = time.time()+ try:+ f()+ print(f"ok {name} ({time.time() - t:.1f} s)")+ except Exception: # noqa: BLE001+ bad += 1+ print(f"FAIL {name}\n{traceback.format_exc()}")+ print(f"{len(tests) - bad}/{len(tests)} passed")+ return 1 if bad else 0++++def test_local_play_refused_action_is_a_refusal():+ """core 0.2.3: a built-in player's invalid action is refused (as HTTP 400 in a real match), not a crash."""+ from core import local+ cfg = MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")++ class Flaky:+ def __init__(self):+ self.n = 0++ def act(self, view):+ self.n += 1+ return {"type": "add", "v": 5.0} if self.n == 1 else {"type": "add", "v": 0.5} # first: out of range++ r = local.play(SPORT_TURN, cfg, {"A": Flaky(), "B": Flaky()}, render=False, plugin=PLUGIN_TURN)+ assert r["winner"] in ("A", "B"), r # the match was played out despite the refused first actions++++def test_team_channel_switch_off():+ """core 0.2.5: RO_TEAM_CHANNEL=off switches a declared team channel off (403), on by default."""+ from core.channel import TeamChannel+ cfg = MatchConfig(sport="fixture", format="team", seats=("A1", "A2", "B1", "B2"), seed=1,+ sides={"A1": "A", "A2": "A", "B1": "B", "B2": "B"})+ conf = {"max_bytes": 64, "min_interval_s": 0.0, "max_messages": 5}+ os.environ.pop("RO_TEAM_CHANNEL", None)+ assert TeamChannel(cfg, conf).say("A1", "go left", 0, 0.01)[0] == 200+ os.environ["RO_TEAM_CHANNEL"] = "off"+ try:+ code, body = TeamChannel(cfg, conf).say("A1", "go left", 0, 0.01)+ assert code == 403 and "off" in body["error"], (code, body)+ finally:+ os.environ.pop("RO_TEAM_CHANNEL", None)+ assert TeamChannel(cfg, None).say("A1", "x", 0, 0.01)[0] == 404 # not declared: no channel at all++++# ------------------------------------------------------------ a session that ends mid-match (core 0.2.6, core rule 6)+def check_abandoned(svc, fin):+ """A single side whose session ended after the start: a valid loss by forfeit (abandoned), replayed; success 0."""+ assert fin["reason"] == "abandoned" and fin["forfeiting"] == "A" and fin["winner"] is None, fin+ assert fin["decided_by"] == "forfeit:abandoned" and fin["match_winner"] is None, fin+ assert fin["valid_trial"] and fin["deterministic"] and not fin["technical_failure"], fin["errors"]+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "forfeit" and r["seat"] == "A" and r["why"] == "abandoned" for r in rows)+ out = graded(svc, fin)+ assert out["valid_trial"] == 1 and out["technical_failure"] == 0 and out["success"] == 0, out+ assert out["abandoned"] == 1 and out["no_show"] == 0 and out["A_won"] == 0 and out["A_no_show"] == 0, out+++def test_solo_quit_realtime_single_mid_match_is_a_valid_loss():+ for when in ("running", "review"):+ svc, post = service(["A"], fmt="single")+ threading.Thread(target=post["start"], args=("A", {}), daemon=True).start() # never reviews+ t = time.time()+ while svc.phase != when and time.time() - t < 10:+ time.sleep(0.005)+ assert svc.phase == when, svc.phase+ svc.collect() # the session ends mid-match+ fin = finish(svc)+ check_abandoned(svc, fin)+ assert fin["steps"] < 90 and (when == "running" or fin["steps"] == 30), fin["steps"]+++def test_solo_quit_turn_single_on_and_off_turn_is_a_valid_loss():+ for case in ("on_turn", "awaiting_review", "off_turn"):+ svc, post = turn_service(["A"], fmt="single")+ post["start"]("A", {})+ if case != "on_turn":+ assert post["act"]("A", {"v": 0.5})[0] == 200 # one move, review pending+ if case == "off_turn":+ post["ready"]("A", {"why": "w", "plan": "p"})+ with svc.cond: # a sport whose to_move() names nobody for a while (e.g. a pending action)+ svc.set_turn(None)+ svc.collect()+ fin = finish(svc)+ check_abandoned(svc, fin)+ assert fin["steps"] == (0 if case == "on_turn" else 1), fin["steps"]+++def test_solo_quit_realtime_duel_unchanged():+ """Two sides: the collect before the end still leaves the match unfinished ("collected", invalid). A side that+ stops playing while the other plays on loses at the next review it owes (ready_timeout, valid)."""+ svc, post = service(["A", "B"], fmt="duel")+ for s in ("A", "B"):+ threading.Thread(target=post["start"], args=(s, {}), daemon=True).start()+ t = time.time()+ while svc.phase != "running" and time.time() - t < 10:+ time.sleep(0.005)+ svc.collect()+ fin = finish(svc)+ assert fin["reason"] == "collected" and fin["forfeiting"] is None and fin["winner"] is None, fin+ assert not fin["valid_trial"] and graded(svc, fin)["abandoned"] == 0+ svc, post = service(["A", "B"], fmt="duel")+ threading.Thread(target=play, args=(svc, post, "A"), daemon=True).start()+ threading.Thread(target=post["start"], args=("B", {}), daemon=True).start() # B starts, then never reviews+ fin = finish(svc)+ assert fin["reason"] == "ready_timeout" and fin["forfeiting"] == "B" and fin["winner"] == "A", fin+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++PLUGIN_IMG = str(Path(__file__).resolve().parent / "fixture_images" / "plugin.py")+_TINY = ('<mujoco><visual><headlight ambient=".5 .5 .5"/></visual><worldbody><geom type="plane" size="5 5 .1" '+ 'rgba=".3 .5 .3 1"/><body mocap="true" pos="0 0 .2"><geom type="box" size=".1 .1 .1" rgba="1 0 0 1"/>'+ '</body></worldbody></mujoco>')+_CAM = {"name": "top", "pos": [0, 0, 3], "lookat": [0, 0, 0], "up": [1, 0, 0], "fovy_deg": 60, "width": 64,+ "height": 48}+++def _img_service():+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ sport = load_plugin(PLUGIN_IMG)+ cfg = MatchConfig(sport="fixture_images", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")+ svc = TurnService(sport, PLUGIN_IMG, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ post["start"]("A", {})+ post["start"]("B", {})+ return svc, post+++def test_reply_images_turn_attached_replayable_and_review_state():+ """core 0.2.8: Match.reply_views -> the act reply carries the result's images (observe's format, frames with+ labels), drawn off the lock by the task renderer; a replay draws the same PNG; the sport sees whose review is due+ (the other seat gets no images while the actor reviews, although the sport's to_move() already names it)."""+ import base64+ import struct+ from core.episode import read_rows, reply_image+ svc, post = _img_service()+ assert post["observe"]("A", {})[1]["observation"].get("image_png_b64") # on turn: the camera image+ code, out = post["act"]("A", {"v": 0.7})+ assert code == 200, out+ ob = out["observation"]+ raw = base64.b64decode(ob["image_png_b64"])+ assert raw[:8] == b"\x89PNG\r\n\x1a\n" and struct.unpack(">II", raw[16:24]) == (160, 60)+ assert [(t["camera"], t["frame"], t["label"]) for t in ob["tiles"]] == [("top", 0, "before"), ("top", 1, "after")]+ assert ob["of"] and ob["note"] and "render_wall_s" in ob+ assert svc.m.awaiting_review == "A" and out["state"]["awaiting_review"] and svc.m.to_move() == "B"+ assert "image_png_b64" not in post["observe"]("B", {})[1]["observation"] # the review-window leak is closed+ rows = read_rows(svc.data / "episode.jsonl")+ assert [(r["seat"], r["tiles"]) for r in rows if r["ev"] == "reply_images"] == [("A", 2)] # information row+ img = reply_image(PLUGIN_IMG, rows, 1)+ assert img["png"] == raw and img["tiles"] == ob["tiles"] # a pure function of the recorded match+ post["ready"]("A", {"why": "w", "plan": "p"})+ assert svc.m.awaiting_review is None+ assert post["observe"]("B", {})[1]["observation"].get("image_png_b64") # B's turn now+ assert svc.camera is not None and not svc.camera.renderer.scene.is_presentation # the match scene only+ svc.collect()+ finish(svc)+++def test_reply_images_off_the_lock_and_off_the_clock():+ """Drawing the reply image neither blocks the other seat nor runs the actor's chess clock."""+ svc, post = _img_service()+ orig = svc.draw++ def slow(seat, job):+ time.sleep(1.5)+ return orig(seat, job)+ svc.draw = slow+ res = {}+ th = threading.Thread(target=lambda: res.update(r=post["act"]("A", {"v": 0.5})), daemon=True)+ t0 = time.time()+ th.start()+ time.sleep(0.5)+ t = time.time()+ code, st = svc.routes(False)["status"]("B", {})+ assert code == 200 and time.time() - t < 0.3, "the other seat was blocked by the drawing"+ assert svc.seats["A"].frozen == 1+ th.join()+ assert time.time() - t0 >= 1.5 and res["r"][0] == 200 and res["r"][1]["observation"].get("image_png_b64")+ used = svc.seats["A"].clock_used()+ assert used < 0.5, f"the drawing ran the actor's clock: {used:.2f} s"+ svc.collect()+ finish(svc)+++def test_reply_images_realtime():+ """Realtime: an act that takes effect at once carries its result's images (frames, camera order, labels), drawn+ after the act's timing was taken; the match stays deterministic."""+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ from renderers.base import Scene+ World = type(SPORT.build(MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)))++ class ImgWorld(World):+ def cameras(self, seat, query=None):+ return [_CAM]++ def render_state(self):+ return {"qpos": [], "mocap_pos": [[self.pos["A.e0"] * 0.01, 0.0, 0.2]], "mocap_quat": [[1, 0, 0, 0]]}++ def reply_views(self, seat, cmd, info):+ later = {"qpos": [], "mocap_pos": [[0.5, 0.0, 0.2]], "mocap_quat": [[1, 0, 0, 0]]}+ return {"frames": [{"cameras": [_CAM, dict(_CAM, name="top2")], "label": "now"},+ {"cameras": [_CAM, dict(_CAM, name="top2")], "state": later, "label": "later"}],+ "order": "camera", "columns": 2, "note": "two frames"}++ class ImgSport(type(SPORT)):+ def build(self, cfg):+ return ImgWorld(cfg)++ def scene(self, cfg):+ return Scene(xml=_TINY)++ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=1.0)+ svc = RealtimeService(ImgSport(), PLUGIN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ post = svc.routes(True)+ for s in ("A", "B"):+ threading.Thread(target=post["start"], args=(s, {}), daemon=True).start()+ while svc.phase != "running":+ time.sleep(0.01)+ code, out = post["act"]("A", {"type": "move", "v": 0.5, "entity": "e0"})+ assert code == 200, out+ ob = out["observation"]+ assert [(t["camera"], t["frame"], t["label"]) for t in ob["tiles"]] == [+ ("top", 0, "now"), ("top", 1, "later"), ("top2", 0, "now"), ("top2", 1, "later")], ob["tiles"]+ assert ob["note"] == "two frames" and ob["image_png_b64"] and "wall_s_after_request" in out["took_effect"]+ fin = run_all(svc, post, ["A", "B"])+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++# ------------------------------------------------------------------ core 0.2.11: malformed requests never void a match+HOSTILE_RAW = [b'{"type": "add", "v": 1' + b"0" * 400 + b"}", b'{"type": "add", "v": NaN}',+ b'{"type": "add", "v": Infinity}', b'{"type": "add", "v": 1e400}', b'{"type": []}', b'{"type": {}}',+ b'{"type": null}', b'{"type": "add", "v": [1, [2, [3]]]}', b'{"type": "add", "v": {"a": 1}}',+ b"[" * 5000 + b"]" * 5000, b'{"type": "' + b"x" * 20000 + b'"}', b"not json", b"\xff\xfe",+ b'{"type": "add", "v": "0.5"}', b"[1, 2]", b'"x"', b'{"type": "add", "v": 0.5, "x": ' ++ b"[" * 50 + b"]" * 50 + b"}"]+++def _http(svc, seats):+ from core.http import make_server+ srv = make_server(svc, seats, {}, port=0)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ return srv, srv.server_address[1]+++def _post(port, path, raw, timeout=10):+ time.sleep(0.06) # under the 20 requests per second and seat (core/http.py)+ import urllib.error+ import urllib.request+ req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data=raw, method="POST",+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.status, json.loads(r.read() or b"{}")+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read() or b"{}")+++def test_turn_malformed_actions_are_refusals_over_http():+ """core 0.2.11 (anti-cheat G3): a hostile act body (huge integer, NaN / inf, an unhashable type, nested junk,+ oversize strings, broken JSON) is the player's own 400; the match goes on and stays a valid trial."""+ svc, post = turn_service(["A", "B"])+ srv, port = _http(svc, ("A", "B"))+ try:+ for s in ("A", "B"):+ assert post["start"](s, {})[0] == 200+ assert svc.on_turn == "A"+ for raw in HOSTILE_RAW:+ code, out = _post(port, "/A/act", raw)+ assert 400 <= code < 500, (raw[:40], code, out)+ assert "detail" not in out and "Error" not in json.dumps(out), out+ for raw in (b'{"timeout_s": 1' + b"0" * 400 + b"}", b'{"timeout_s": [1]}', b'{"query": {"a": 1e999}}'):+ code, out = _post(port, "/A/wait", raw)+ assert 400 <= code < 500, (raw[:40], code, out)+ code, out = _post(port, "/A/observe", b'{"query": {"a": [1' + b"0" * 400 + b"]}}")+ assert code == 400, (code, out)+ assert svc.phase == "play" and not svc.errors, (svc.phase, svc.errors)+ assert svc.seats["A"].stats["refused_invalid"] >= 6, svc.seats["A"].stats+ finally:+ srv.shutdown()+ srv.server_close()+ th = [threading.Thread(target=play_turn, args=(svc, post, s, v), daemon=True) for s, v in (("A", .3), ("B", .6))]+ for t in th:+ t.start()+ fin = finish(svc)+ assert fin["reason"] == "match_over" and fin["valid_trial"] and fin["deterministic"], fin+ rows = [json.loads(x) for x in (svc.data / "episode.jsonl").read_text().splitlines()]+ assert any(r["ev"] == "refused_invalid" for r in rows)+++def test_parse_exceptions_are_refusals_and_world_errors_stay_failures():+ """Any exception of the action layer's parse is a refusal (no exception text to the player); an exception of+ the world after the action was accepted is still a technical failure, and the 500 reply carries no detail."""+ from core.sport import parse_action+ svc, post = turn_service(["A", "B"])+ inner = svc.layer++ class Crashy:+ level, worker, delay_steps = "low", None, 0++ def schema(self, m, seat):+ return inner.schema(m, seat)++ def parse(self, seat, body, m, ctx):+ if body.get("v") == 0.25:+ raise ZeroDivisionError("secret internal detail")+ return inner.parse(seat, body, m, ctx)++ def __getattr__(self, k):+ return getattr(inner, k)++ svc.layer = Crashy()+ try:+ parse_action(svc.layer, "A", {"type": "add", "v": 0.25}, svc.m, {})+ raise AssertionError("not refused")+ except Refused as exc:+ assert "secret" not in str(exc) and "ZeroDivisionError" in exc.cause+ srv, port = _http(svc, ("A", "B"))+ try:+ for s in ("A", "B"):+ post["start"](s, {})+ code, out = _post(port, "/A/act", b'{"type": "add", "v": 0.25}')+ assert code == 400 and "secret" not in json.dumps(out), (code, out)+ assert svc.phase == "play" and not svc.errors+ world_apply = svc.m.apply++ def boom(seat, cmd):+ raise RuntimeError("secret world detail")+ svc.m.apply = boom+ code, out = _post(port, "/A/act", b'{"type": "add", "v": 0.5}')+ assert code == 500 and out.get("error") == "technical failure" and "detail" not in out, (code, out)+ assert "secret" not in json.dumps(out)+ svc.m.apply = world_apply+ assert svc.reason == "technical_error" and svc.errors+ finally:+ srv.shutdown()+ srv.server_close()+++def test_realtime_malformed_actions_are_refusals_over_http():+ """The realtime protocol: hostile act / wait / observe / ready / say bodies are 400s, the world runs on."""+ svc, post = service(["A", "B"], fmt="duel")+ srv, port = _http(svc, ("A", "B"))+ try:+ for s in ("A", "B"): # both seats start and review as usual; A also sends hostile bodies+ threading.Thread(target=play, args=(svc, post, s), daemon=True).start()+ t = time.time()+ while svc.phase != "running" and time.time() - t < 10:+ time.sleep(0.01)+ assert svc.phase == "running"+ for raw in [*HOSTILE_RAW, b'{"type": "move", "v": 0.5, "entity": "' + b"e" * 9000 + b'"}']:+ code, out = _post(port, "/A/act", raw)+ assert 400 <= code < 500, (raw[:40], code, out)+ assert "detail" not in out, out+ for ep, raw in (("wait", b'{"dt": 1' + b"0" * 400 + b"}"), ("wait", b'{"dt": [1]}'),+ ("observe", b'{"query": {"q": 1e999}}'), ("observe", b'{"query": [1]}'),+ ("say", b'{"text": ["x"]}'), ("ready", b'{"why": 1' + b"0" * 400 + b"}")):+ code, out = _post(port, f"/A/{ep}", raw)+ assert 400 <= code < 500, (ep, raw[:40], code, out)+ assert svc.reason != "technical_error" and not svc.errors, (svc.reason, svc.errors)+ assert svc.seats["A"].stats["refused_invalid"] >= 6 and svc.seats["A"].stats["refused"] >= 6+ finally:+ srv.shutdown()+ srv.server_close()+ fin = finish(svc)+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+++def test_check_body_and_check_action_limits():+ from core.sport import check_action, check_body+ for bad in (10 ** 400, 2 ** 70, float("nan"), float("inf"), 1e300, "x" * 9000, [0] * 5000,+ json.loads("[" * 20 + "]" * 20), {"k" * 9000: 1}):+ try:+ check_body({"v": bad})+ raise AssertionError(f"accepted {str(bad)[:20]}")+ except Refused:+ pass+ check_body({"type": "x", "q": [[0.1] * 8] * 600, "s": "ok", "n": None, "b": True, "i": -3})+ schema = {"go": {"v": {"type": "vector", "len": 3}, "r": {"type": "vector", "len": "1 or 2"},+ "rows": {"type": "rows", "len": 2, "max_rows": 3}, "o": {"type": "object", "keys": ["a"]},+ "e": {"type": "enum", "values": ["x"]}, "b": {"type": "boolean"}, "n": {"type": "number"}}}+ check_action(schema, {"type": "go", "v": [1, 2, 3], "r": [1], "rows": [[1, 2]], "o": {"a": 1}, "e": "x",+ "b": False, "n": 2})+ check_action(schema, {"rods": {}}) # an implicit type stays with the layer+ for body in ({"type": []}, {"type": 3}, {"type": "x" * 65}, {"type": "go", "v": [1, 2]},+ {"type": "go", "v": [1, 2, "3"]}, {"type": "go", "r": [1, 2, 3]}, {"type": "go", "rows": [[1]]},+ {"type": "go", "rows": [[1, 2]] * 4}, {"type": "go", "o": {"z": 1}}, {"type": "go", "e": ["x"]},+ {"type": "go", "b": 1}, {"type": "go", "n": "1"}, {"type": "go", "n": True}, [1]):+ try:+ check_action(schema, body)+ raise AssertionError(f"accepted {body}")+ except Refused:+ pass+# ------------------------------------------------------------------ unmetered seats (core 0.2.29)+def test_unmetered_seat_needs_no_meter_and_no_proxy():+ from core.launch import seat_mode+ from core.seats import Seat, validity_fields+ data = Path(tempfile.mkdtemp(prefix="core-test-"))+ os.environ["PLAYER_MODE_A"] = "unmetered"+ try:+ st = Seat("A", data)+ st.joined = True+ assert st.mode == "unmetered" and st.meter.decided_by_model() # acts pass without a metering proxy+ st.meter.check_ready()+ v = validity_fields({"A": st}, lambda s: s.mode == "model" and s.joined)+ assert v["meter_error"] == {"A": False} and v["proxy_error"] == {"A": False}+ assert v["player_modes"] == {"A": "unmetered"}+ assert seat_mode("A") == "unmetered" and seat_mode("B", {"RCB_PLAYER_MODE": "oracle"}) == "oracle"+ os.environ["PLAYER_MODE_A"] = "model"+ st = Seat("A", data)+ st.joined = True+ assert validity_fields({"A": st}, lambda s: s.mode == "model" and s.joined)["meter_error"] == {"A": True}+ os.environ["PLAYER_MODE_A"] = "metered-elsewhere"+ try:+ Seat("A", data)+ raise AssertionError("an unknown player mode must be refused")+ except ValueError:+ pass+ finally:+ os.environ.pop("PLAYER_MODE_A", None)+++# ------------------------------------------------------------------ core 0.2.13+def test_game_shortcuts_send_entity_and_enum_values_as_text():+ """The `game` shortcuts send `entity` as written and a value that is not a number (an enum value, true / false) as+ such; the core checks the body. Cores <= 0.2.12 sent robot 1 as entity "1.0" (refused) and exited with the usage+ text on an enum value."""+ from core.sport import MatchBase, SchemaLayer, parse_action+ cli = {"kick": ["kick", "entity", "power", "foot", "chip"]}+ game = {"__name__": "game"}+ exec(compile((ROOT / "core" / "game.py").read_text().replace("@@COMMANDS@@", json.dumps(cli)), "game", "exec"), game)+ sent = []+ game.update(call=lambda ep, body=None: sent.append(body) or {}, show=lambda out: None)+ game["main"](["kick", "1", "0.5", "left", "true"])+ assert sent == [{"type": "kick", "entity": "1", "power": 0.5, "foot": "left", "chip": True}], sent++ class Robots(MatchBase):+ def schema(self, seat):+ return {"kick": {"power": {"type": "number", "min": 0, "max": 1},+ "foot": {"type": "enum", "values": ["left", "right"]}, "chip": {"type": "boolean"}}}++ def entities(self, seat):+ return ("1", "2")+ assert parse_action(SchemaLayer(), "A", sent[0], Robots(), {}) == sent[0]+++def test_fairness_plays_and_counts_the_sides_of_a_team_format():+ """The fairness check plays a team format with its sides and judges it against one over the number of sides. The+ turn fixture's built-in player always adds 0.5, so the first side wins every match by the last tiebreak: +50 pp+ for the first side, 0 for seat A1 (whose side starts half the matches). Cores <= 0.2.12 played one side per seat+ (A1 won every match) and judged against 1/4: -25 pp and +75 pp."""+ from core import testkit+ rows = testkit.fairness(PLUGIN_TURN, matches=2)+ assert [r["name"] for r in rows] == ["fairness:team"], rows+ got = json.loads(rows[0]["detail"])+ assert got["N"] == 4 and got["first_side"]["advantage_pp"] == 50 and got["seat_A1"]["advantage_pp"] == 0, got+ assert not rows[0]["ok"]+++def test_replay_video_appears_only_when_complete():+ """The replay video is written to replay.part.mp4 and renamed once its writer has closed: a render that stops early+ (killed at RCB_VIDEO_TIMEOUT_S) leaves no replay.mp4 for the grader to count as rendered. Cores <= 0.2.12 wrote+ replay.mp4 in place."""+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ from core import episode, local, spectator+ sport = load_plugin(PLUGIN_IMG)+ cfg = MatchConfig(sport="fixture_images", format="duel", seats=("A", "B"), seed=1, first="A", action_level="low")++ class Mover:+ def act(self, view):+ return {"type": "add", "v": 0.5}+ data = Path(tempfile.mkdtemp(prefix="core-test-"))+ local.play(sport, cfg, {"A": Mover(), "B": Mover()}, data=data, render=False, plugin=PLUGIN_IMG)+ replay = episode.replay++ def stopped(sport, rows, observer): # the render stops after its first frame+ def first(match):+ observer(match)+ raise TimeoutError+ return replay(sport, rows, observer=first)+ episode.replay = stopped+ try:+ spectator.render_video(PLUGIN_IMG, data)+ raise AssertionError("the render went on")+ except TimeoutError:+ pass+ finally:+ episode.replay = replay+ assert (data / "replay.part.mp4").exists() and not (data / "replay.mp4").exists()+ info = spectator.render_video(PLUGIN_IMG, data)+ assert info["video"] and (data / "replay.mp4").stat().st_size and not (data / "replay.part.mp4").exists(), info+++def test_realtime_resume_time_is_not_game_time():+ """The world's clock restarts when Match.resume() has returned: a resume that takes 0.5 s (a sport setting up the+ next unit) no longer makes the loop run the missed control steps back to back. Cores <= 0.2.12 anchored the clock+ before resume(): the unit's first steps ran at once to catch up, the first one 0.5 s late."""+ World = type(SPORT.build(MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)))++ class SlowResume(World):+ def resume(self):+ time.sleep(0.5)+ super().resume()++ class SlowSport(type(SPORT)):+ def build(self, cfg):+ return SlowResume(cfg)++ for s in ("A", "B"):+ os.environ[f"PLAYER_MODE_{s}"] = "oracle"+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1, slowdown=1.0)+ svc = RealtimeService(SlowSport(), PLUGIN, cfg, Path(tempfile.mkdtemp(prefix="core-test-")))+ threading.Thread(target=svc.loop, daemon=True).start()+ fin = run_all(svc, svc.routes(True), ["A", "B"])+ assert fin["valid_trial"] and fin["deterministic"], fin["errors"]+ assert fin["sim_lag"]["late_max_s"] < 0.25, fin["sim_lag"]+++def test_entity_refused_from_a_seat_without_entities():+ """An act may name an entity only if the seat has entities (Match.entities); otherwise the core refuses it (400),+ in both protocols and in local play (parse_action). Cores <= 0.2.12 passed it on, and in real time every new+ entity string was a new act slot: one act in flight per (seat, entity), one pending act per (seat, entity)."""+ from core.sport import SchemaLayer, parse_action+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)+ world = SPORT.build(cfg)++ class OneBody(type(world)): # the realtime fixture's world without entities+ def entities(self, seat):+ return ()+ game = SPORT_TURN.build(MatchConfig(sport="fixture_turn", format="duel", seats=("A", "B"), seed=1, first="A"))+ assert parse_action(SchemaLayer(), "A", {"type": "move", "v": 0.5, "entity": "e1"}, world, {})["entity"] == "e1"+ for layer, m, body in ((SchemaLayer(), OneBody(cfg), {"type": "move", "v": 0.5}),+ (SPORT_TURN.action_layer("low"), game, {"v": 0.5})):+ for entity in ("x1", "x2", 7):+ try:+ parse_action(layer, "A", {**body, "entity": entity}, m, {})+ raise AssertionError(f"{type(m).__name__} accepted entity {entity!r}")+ except Refused as e:+ assert e.code == 400 and "entit" in str(e), e+ assert "entity" not in parse_action(layer, "A", body, m, {})+++# ------------------------------------------------------------------ core 0.2.16: the budget of the authenticated seat+class _Held:+ """A service whose `hold` stays open until the gate opens (open requests); `ping` answers at once."""++ def __init__(self):+ self.gate, self.entered = threading.Event(), threading.Semaphore(0)++ def routes(self, post):+ return {"hold": self.hold, "ping": lambda seat, body: (200, {"seat": seat})}++ def hold(self, seat, body):+ self.entered.release()+ self.gate.wait(30)+ return 200, {"seat": seat}++ def failure(self, ep, exc):+ pass+++def _call(port, path, timeout=30):+ """One POST without retries: (status, raw body); a connection refused before its request was read (closed while+ the client still wrote it, which core/client.py retries like a bare 429) is (429, b"")."""+ import urllib.error+ import urllib.request+ req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data=b"{}", method="POST",+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.status, r.read()+ except urllib.error.HTTPError as e:+ return e.code, e.read()+ except urllib.error.URLError as e:+ if isinstance(e.reason, (BrokenPipeError, ConnectionResetError)):+ return 429, b""+ raise+++def _hold(port, svc, seats, n=4):+ """n held requests per seat, each in its own thread; returns (threads, results) once all reached the service."""+ results, threads = [], []+ for s in seats:+ for _ in range(n):+ t = threading.Thread(target=lambda s=s: results.append((s, _call(port, f"/{s}/hold"))), daemon=True)+ t.start()+ threads.append(t)+ for _ in range(n * len(seats)):+ assert svc.entered.acquire(timeout=15), f"held requests refused: {results}"+ return threads, results+++def test_http_budget_belongs_to_the_authenticated_seat():+ """core 0.2.16: without SEAT_HOSTS every local seat may be any seat; each seat has its own 4 open requests and+ 20 per second (cores <= 0.2.15 charged every local connection to the first seat: a team format's 8 local seats+ shared 4 slots and got 429s). The 429 of a full seat is bare (core/client.py retries it), other seats go on."""+ from core.http import make_server+ seats = ("A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4")+ svc = _Held()+ srv = make_server(svc, seats, {}, port=0)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ port = srv.server_address[1]+ try:+ threads, results = _hold(port, svc, ["A1"])+ assert _call(port, "/A1/ping") == (429, b""), "a seat over its own 4 open requests"+ code, raw = _call(port, "/B1/ping")+ assert code == 200 and json.loads(raw) == {"seat": "B1"}, (code, raw)+ more, results2 = _hold(port, svc, seats[1:]) # every other seat: 4 open requests each, 32 in all+ svc.gate.set()+ for t in threads + more:+ t.join(15)+ got = results + results2+ assert len(got) == 32 and all(c == 200 and json.loads(raw)["seat"] == s for s, (c, raw) in got), got+ time.sleep(1.1) # a new second for every seat+ codes = [_call(port, "/A2/ping")[0] for _ in range(30)]+ assert codes[:20] == [200] * 20 and 429 in codes, codes # A2's 20 per second ...+ code, raw = _call(port, "/A3/ping")+ assert code == 200 and json.loads(raw) == {"seat": "A3"}, (code, raw) # ... are not A3's+ finally:+ svc.gate.set()+ srv.shutdown()+ srv.server_close()+++def test_http_seat_never_spends_another_seats_budget():+ """core 0.2.16: a request for a seat its address may not be (SEAT_HOSTS) is refused (403) before it spends any+ seat's budget, and before a request is read an address holds only the budget of the seats it may be."""+ from core.http import make_server+ svc = _Held()+ srv = make_server(svc, ("A", "B"), {"B": "192.0.2.1"}, port=0) # B's container: never this host (TEST-NET-1)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ port = srv.server_address[1]+ try:+ for _ in range(8):+ time.sleep(0.06)+ assert _call(port, "/B/ping")[0] == 403, "impersonating B"+ assert srv.arrivals["B"] == [] and srv.slots["B"].acquire(False), "B's budget spent by another address"+ srv.slots["B"].release()+ code, raw = _call(port, "/A/ping")+ assert code == 200 and json.loads(raw) == {"seat": "A"}, (code, raw)+ time.sleep(1.1)+ threads, results = _hold(port, svc, ["A"])+ assert _call(port, "/A/ping") == (429, b"") # this address may be A only: A's 4 open requests+ assert _call(port, "/B/ping") == (429, b"") # and no more, whatever seat the path names+ svc.gate.set()+ for t in threads:+ t.join(15)+ assert [c for _, (c, _) in results] == [200] * 4, results+ finally:+ svc.gate.set()+ srv.shutdown()+ srv.server_close()+++# ------------------------------------------------------------------ core 0.2.17: the testkit's replay limit+def test_testkit_replay_timeout_from_sport_toml():+ """core 0.2.17: the fresh-process replays of the generic tests (determinism, solo_quit) take sport.toml [timing]+ replay_timeout_s when it is above 1800 s (a 600 s match replays in more than 1800 s), never less than 1800 s;+ a replay over the limit is a failed row that names the limit, not a crash of the suite."""+ import subprocess+ from core import testkit+ assert testkit.replay_timeout({}) == 1800+ assert testkit.replay_timeout({"timing": {"slowdown": 20}}) == 1800+ assert testkit.replay_timeout({"timing": {"replay_timeout_s": 600}}) == 1800 # the task's default: no tighter+ assert testkit.replay_timeout({"timing": {"replay_timeout_s": 3600}}) == 3600+ decl = {"formats": {"duel": {"seats": ["A", "B"], "first": ["A"]}}, "modes": {"action_levels": ["low"]},+ "timing": {"replay_timeout_s": 4321}}+ seen, run = [], subprocess.run++ def spy(cmd, **kw):+ seen.append(kw.get("timeout"))+ return run(cmd, **kw)+ testkit.subprocess.run = spy+ try:+ rows = testkit.t_determinism(SPORT_TURN, PLUGIN_TURN, decl)+ assert seen == [4321] and all(r["ok"] for r in rows), (seen, rows)++ def slow(cmd, **kw):+ raise subprocess.TimeoutExpired(cmd, kw["timeout"])+ testkit.subprocess.run = slow+ rows = testkit.t_determinism(SPORT_TURN, PLUGIN_TURN, decl)+ finally:+ testkit.subprocess.run = run+ bad = {r["name"]: r for r in rows}["determinism:fresh_process_replay"]+ assert not bad["ok"] and "4321 s" in bad["detail"] and "replay_timeout_s" in bad["detail"], rows++++def test_team_channel_reads_after_a_seq_never_consume():+ """core 0.2.20: every message has a per-side seq; reads with a read mark return each message after it once per+ read mark, any number of clients; without a read mark the recent window (recent_s game seconds, at most recent_max);+ POST /team pages through the log; the limits of say are unchanged."""+ from core.channel import TeamChannel+ cfg = MatchConfig(sport="fixture", format="team", seats=("A1", "A2", "B1", "B2"), seed=1,+ sides={"A1": "A", "A2": "A", "B1": "B", "B2": "B"})+ ch = TeamChannel(cfg, {"max_bytes": 64, "min_interval_s": 0.2, "max_messages": 4, "recent_s": 1.0,+ "recent_max": 2})+ dt = 0.02+ assert ch.say("A1", "a", 0, dt)[1]["sent"]["seq"] == 1+ assert ch.say("A1", "b", 5, dt)[0] == 429 # 0.2 s between two messages of one seat+ assert ch.say("A2", "c", 5, dt)[1]["sent"]["seq"] == 2 # one seq per side+ assert ch.say("B1", "z", 5, dt)[1]["sent"]["seq"] == 1 # the other side counts its own+ assert ch.say("A1", "d", 10, dt)[1]["sent"]["seq"] == 3+ assert ch.say("A1", "e", 100, dt)[1]["sent"]["seq"] == 4+ for _ in range(3): # never consumed+ msgs, top = ch.messages("A2", 100, dt, since=0)+ assert [m["text"] for m in msgs] == ["a", "d", "e"] and top == 4, (msgs, top)+ assert [m["seq"] for m in ch.messages("A2", 100, dt, since=3)[0]] == [4]+ assert ch.messages("A2", 100, dt, since=4)[0] == []+ assert [m["text"] for m in ch.messages("A2", 100, dt)[0]] == ["e"] # recent: the last 1.0 s only+ assert [m["text"] for m in ch.messages("A2", 10, dt)[0]] == ["a", "d"] # at step 10: both within 1 s, max 2+ assert [m["text"] for m in ch.messages("B2", 100, dt, since=0)[0]] == ["z"]+ assert ch.messages("A1", 100, dt, since=0)[0][0]["text"] == "c" # A1 sees A2's only+ code, page = ch.page("A2", 100, 1)+ assert code == 200 and [m["seq"] for m in page["messages"]] == [3, 4] and page["team_seq"] == 4+ assert not page["more"]+ ch.page_max = 1+ assert ch.page("A2", 100, 0)[1]["more"] and len(ch.page("A2", 100, 0)[1]["messages"]) == 1+ assert ch.say("A1", "f", 200, dt)[0] == 200 # A1's 4th message+ assert ch.say("A1", "g", 300, dt)[0] == 429 # max_messages (4 per seat) unchanged+ off = TeamChannel(cfg, None)+ assert off.messages("A1", 0, dt) == ([], 0) and off.page("A1", 0, 0)[0] == 404+++def test_team_channel_turn_protocol_and_http_since():+ """core 0.2.20: the turn protocol reads the channel the same way (status / wait / observe with team_since, POST+ /team), and an HTTP GET carries the read mark as ?team_since=N (anything but a small integer is a 400)."""+ from core.http import make_server+ sides = {"A1": "A", "A2": "A", "B1": "B", "B2": "B"}+ svc, post = turn_service(list(sides), sides, fmt="team")+ if not svc.channel.enabled: # the turn fixture declares no channel+ svc.channel.declared = svc.channel.enabled = True+ assert post["say"]("A1", {"text": "hi"})[0] == 200+ get = svc.routes(False)+ st = get["status"]("A2", {})[1]["state"]+ assert [m["text"] for m in st["team_messages"]] == ["hi"] and st["team_seq"] == 1+ assert get["status"]("A2", {"team_since": 1})[1]["state"]["team_messages"] == []+ assert get["team"]("A2", {"since": 0})[1]["messages"][0]["from"] == "A1"+ srv = make_server(svc, tuple(sides), {}, port=0)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ port = srv.server_address[1]+ import urllib.error+ import urllib.request++ def fetch(path):+ try:+ with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=10) as r:+ return r.status, json.load(r)+ except urllib.error.HTTPError as e:+ return e.code, json.load(e)+ try:+ code, out = fetch("/A2/status?team_since=0")+ assert code == 200 and out["state"]["team_messages"][0]["text"] == "hi", out+ code, out = fetch("/A2/status?team_since=1")+ assert code == 200 and out["state"]["team_messages"] == [], out+ assert fetch("/A2/status?team_since=-3")[0] == 400+ assert fetch("/A2/status?team_since=abc")[0] == 400+ code, out = fetch("/A2/team?since=0")+ assert code == 200 and out["messages"][0]["text"] == "hi", out+ finally:+ srv.shutdown()+ srv.server_close()+++def test_requests_after_the_end_never_void_a_finished_match():+ """core 0.2.26: once a match is over, observe / act answer 409 with the final state and draw nothing (realtime and+ turn); after finalization the render workers are closed, so a late draw returns no images and a late request's+ failure is only logged: a player that keeps observing after the end (713 broken pipes in a four-seat match)+ never voids the finished, replayed match."""+ svc, post = service(["A", "B"], fmt="duel")+ fin = run_all(svc, post, ["A", "B"])+ assert fin["valid_trial"] and svc.finalized, fin["errors"]++ class Closed: # a render worker after finalize(): every call is a broken pipe+ lock = threading.Lock()++ def call(self, job, wait=True):+ raise BrokenPipeError(32, "Broken pipe")++ def close(self):+ pass+ svc.workers["render", "A"] = Closed()+ code, out = post["observe"]("A", {})+ assert code == 409 and out["error"] == "the match is over" and out["now"]["done"], (code, out)+ assert "observation" not in out+ code, out = post["act"]("A", {"type": "move", "v": 0.5})+ assert code == 409 and out["now"]["done"], (code, out)+ assert svc.draw("A", {"state": {}, "cams": []}) is None # finalized: nothing drawn+ svc.failure("observe", BrokenPipeError(32, "Broken pipe")) # what core/http.py reports+ with svc.cond:+ svc.write_final()+ fin2 = json.loads((svc.data / "final.json").read_text())+ assert fin2["valid_trial"] and not fin2["technical_failure"] and fin2["errors"] == fin["errors"], fin2+ assert fin2["winner"] == fin["winner"] and svc.phase == "over"++ tsvc, tpost = turn_service(["A", "B"])+ th = [threading.Thread(target=play_turn, args=(tsvc, tpost, s), daemon=True) for s in ("A", "B")]+ for t in th:+ t.start()+ tfin = finish(tsvc)+ assert tfin["valid_trial"], tfin["errors"]+ for ep in ("observe", "act"):+ code, out = tpost[ep]("A", {"v": 0.5} if ep == "act" else {})[:2]+ assert code == 409 and out["error"] == "the match is over" and out["state"]["done"], (ep, code, out)+++_SPECTATOR_PLUGIN = """import importlib.util, os+_spec = importlib.util.spec_from_file_location("fixture_images_base", os.environ["RO_TEST_FIXTURE_IMAGES"])+_base = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_base)+EXTRA = '<geom name="spectators_only" type="box" pos="0.5 0.5 0.2" size="0.2 0.2 0.2" rgba="1 1 0 1"/>'+++class Game(_base.Game):+ def spectator_state(self):+ with open(os.environ["RO_TEST_SPECTATOR_LOG"], "a") as f:+ f.write("x\\n")+ return self.render_state()+++class Fixture(_base.Fixture):+ def build(self, cfg):+ return Game(cfg)++ def spectator_scene(self, cfg):+ from renderers.base import Scene+ if os.environ.get("RO_TEST_SPECTATOR_FAIL"):+ raise RuntimeError("no spectator scene here")+ return Scene(xml=_base.XML.replace("</worldbody>", EXTRA + "</worldbody>"))+++SPORT = Fixture()+"""+++def test_sport_spectator_scene_and_state_draw_the_video_only():+ """core 0.2.28: a sport's own spectator scene (Sport.spectator_scene(cfg)) with Match.spectator_state() draws the+ replay video; RO_VIDEO_SCENE=match and a failing spectator_scene fall back to the match scene; the players' scene+ (Sport.scene) is untouched and the episode replays to the same digest."""+ os.environ.setdefault("MUJOCO_GL", "osmesa")+ from core import local, spectator+ from core.episode import read_rows, replay+ tmp = Path(tempfile.mkdtemp(prefix="core-test-"))+ plugin = tmp / "plugin.py"+ plugin.write_text(_SPECTATOR_PLUGIN)+ shutil.copy2(Path(PLUGIN_IMG).parent / "sport.toml", tmp / "sport.toml")+ log = tmp / "spectator.log"+ os.environ["RO_TEST_FIXTURE_IMAGES"] = PLUGIN_IMG+ os.environ["RO_TEST_SPECTATOR_LOG"] = str(log)+ try:+ sport = load_plugin(str(plugin))+ cfg = MatchConfig(sport="fixture_images", format="duel", seats=("A", "B"), seed=1, first="A",+ action_level="low")+ sc, what = spectator.spectator_scene(sport, str(plugin), cfg)+ assert what == "spectator" and "spectators_only" in sc.xml and "spectators_only" not in sport.scene(cfg).xml+ os.environ["RO_VIDEO_SCENE"] = "match"+ try:+ sc2, what2 = spectator.spectator_scene(sport, str(plugin), cfg)+ finally:+ del os.environ["RO_VIDEO_SCENE"]+ assert what2 == "match" and "spectators_only" not in sc2.xml+ os.environ["RO_TEST_SPECTATOR_FAIL"] = "1"+ try:+ sc3, what3 = spectator.spectator_scene(sport, str(plugin), cfg)+ finally:+ del os.environ["RO_TEST_SPECTATOR_FAIL"]+ assert what3.startswith("match (spectator scene unavailable") and "spectators_only" not in sc3.xml++ class Mover:+ def act(self, view):+ return {"type": "add", "v": 0.5}+ data = tmp / "run"+ r = local.play(sport, cfg, {"A": Mover(), "B": Mover()}, data=data, render=False, plugin=str(plugin))+ assert not log.exists() # the match itself never asks for the spectator state+ info = spectator.render_video(str(plugin), data)+ assert info["video"] and info["scene"] == "spectator" and info["label"] is None, info+ n = len(log.read_text().splitlines()) # one spectator state per drawn frame (held 1 s: turn protocol)+ assert n > 0 and info["frames"] == n * 10, (info, n)+ rep = replay(sport, read_rows(data / "episode.jsonl"))+ assert rep["state_sha"] == r["digest"], (rep, r)+ finally:+ for k in ("RO_TEST_FIXTURE_IMAGES", "RO_TEST_SPECTATOR_LOG"):+ os.environ.pop(k, None)++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/test_diagnose.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/test_diagnose.pynew file mode 100644index 0000000000..5331675bef--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/tests/test_diagnose.py@@ -0,0 +1,193 @@+"""Tests of the diagnostic records (core/diaglog.py, core 0.2.25) and the post-match diagnosis (core/diagnose.py):+in-process matches (core/local.py) of the realtime fixture and the live realtime service (a turn-protocol+example: the example sport's tests/test_diagnose.py). Run in the sim image:+ docker run --rm -v $PWD:/w -w /w -e MUJOCO_GL=osmesa ghcr.io/mll-lab-nu/eai-olympiad:0.1.0 \\+ python3 core/tests/test_diagnose.py+"""+from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import threading+import time+from pathlib import Path++HERE = Path(__file__).resolve().parent+ROOT = HERE.parents[1]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(HERE))++import test_core as tc # noqa: E402 (service helpers; sets the short timeouts)+from core import diagnose, local # noqa: E402+from core.episode import load_plugin, read_rows, replay # noqa: E402+from core.sport import MatchConfig # noqa: E402++++class Mover:+ """A fixture player: every observation, move entity e0 (and e1 every other time)."""++ def __init__(self, v=0.3):+ self.v, self.n = v, 0++ def act(self, view):+ self.n += 1+ return {"type": "move", "v": self.v if self.n % 2 else -self.v, "entity": "e0" if self.n % 3 else "e1"}+++def fixture_local(delay=0):+ os.environ["FIXTURE_DELAY"] = str(delay)+ try:+ cfg = MatchConfig(sport="fixture", format="duel", seats=("A", "B"), seed=1)+ d = Path(tempfile.mkdtemp(prefix="diag-fx-"))+ res = local.play(tc.SPORT, cfg, {"A": Mover(0.3), "B": Mover(-0.2)}, data=d, render=False,+ plugin=tc.PLUGIN, every=4)+ return d, res+ finally:+ os.environ.pop("FIXTURE_DELAY", None)+++def test_local_rows_link_every_act():+ d, res = fixture_local()+ rep = diagnose.load(d, tc.PLUGIN)+ assert rep["interface"] == diagnose.INTERFACE and all(rep["has"][n] for n in ("observe", "act_received",+ "effect", "event"))+ link = diagnose.linkage(rep)+ for seat in ("A", "B"):+ L = link[seat]+ assert L["acts"] > 10 and L["act_ids_contiguous"], L+ assert L["with_observation"] == L["acts"] and L["effect"] == L["acts"] == L["effect_with_cmd"], L+ assert L["unresolved"] == 0 and L["both"] == 0, L+ for a in rep["acts"][seat]:+ assert a["k_obs"] == a["k_recv"] == a["k_effect"] and a["view_steps"] == [], a+ # events: one per unit end, with the step at which the unit ended+ assert [e["k"] for e in rep["events"]] == [30, 60, 90], rep["events"]+ # the replay rows are unchanged by the diagnostic rows: the fresh replay gives the local result+ sport = load_plugin(tc.PLUGIN)+ assert replay(sport, read_rows(d / "episode.jsonl"))["state_sha"] == res["digest"]+++def test_local_delayed_effects_and_drops():+ d, _ = fixture_local(delay=3)+ rep = diagnose.load(d, tc.PLUGIN)+ link = diagnose.linkage(rep)+ for seat in ("A", "B"):+ L = link[seat]+ assert L["unresolved"] == 0 and L["both"] == 0 and L["dropped"] > 0, L+ assert set(L["dropped_by"]) <= {"unit_over", "match_over"}, L+ for a in rep["acts"][seat]:+ if a["k_effect"] is not None:+ assert a["k_effect"] == a["k_recv"] + 3, a+++def test_world_at_matches_the_replay():+ d, res = fixture_local(delay=2)+ rep = diagnose.load(d, tc.PLUGIN)+ w = rep["world"]()+ m = w.at(45)+ assert m.k == 45+ pos45 = dict(m.pos)+ w.at(90)+ assert w.k == 90+ assert w.at(45).pos == pos45 # backwards: rebuilt, same state+ w2 = rep["world"]()+ assert w2.run().state_digest() == res["digest"]+ assert sorted(w2.events) == [30, 60, 90]+ # before / after the rows of a step: an effect at step k changes the velocity, not yet the position+ a = next(a for a in rep["acts"]["A"] if a["k_effect"] is not None and a["k_effect"] > 5)+ pre = rep["world"]().at(a["k_effect"])+ post = rep["world"]().at(a["k_effect"], after=True)+ key = f"A.{a['decision']['entity']}"+ assert post.vel[key] == a["cmd"]["v"] and pre.pos == post.pos+++def test_turn_service_rows():+ svc, post = tc.turn_service(["A", "B"])++ def loop(seat):+ post["start"](seat, {})+ while svc.phase != "over":+ st = post["wait"](seat, {"timeout_s": 1})[1]["state"]+ if st["done"] or not st["your_turn"]:+ continue+ if st["awaiting_review"]:+ post["ready"](seat, {"why": "w", "plan": "p"})+ else:+ post["observe"](seat, {})+ post["act"](seat, {"v": 0.5})+ th = [threading.Thread(target=loop, args=(s,), daemon=True) for s in ("A", "B")]+ for t in th:+ t.start()+ final = tc.finish(svc)+ assert final["valid_trial"], final+ rep = diagnose.load(svc.data, tc.PLUGIN_TURN)+ link = diagnose.linkage(rep)+ for seat in ("A", "B"):+ L = link[seat]+ assert L["acts"] > 0 and L["with_observation"] == L["acts"] == L["effect"] == L["effect_with_cmd"], L+ for a in rep["acts"][seat]:+ assert a["k_obs"] == a["k_recv"] == a["k_effect"], a+ w = rep["world"]()+ assert w.run().state_digest() == final["state_sha"]+++def test_service_rows_link_acts_effects_and_team_delivery():+ sides = {"A1": "home", "A2": "home", "B1": "away", "B2": "away"}+ os.environ["FIXTURE_DELAY"] = "2"+ try:+ svc, post = tc.service(list(sides), sides)+ finally:+ os.environ.pop("FIXTURE_DELAY", None)+ said = []++ def act(seat, post):+ post["observe"](seat, {})+ post["act"](seat, {"type": "move", "v": 0.2, "entity": "e0"})+ if seat == "A1" and not said and svc.phase == "running":+ said.append(post["say"](seat, {"text": "go"})[0])+ final = tc.run_all(svc, post, list(sides), **{s: {"act": act} for s in sides})+ assert final["valid_trial"], final+ rep = diagnose.load(svc.data, tc.PLUGIN)+ link = diagnose.linkage(rep)+ for seat in sides:+ L = link[seat]+ assert L["acts"] > 0 and L["act_ids_contiguous"] and L["unresolved"] == 0 and L["both"] == 0, (seat, L)+ assert L["with_observation"] == L["acts"], (seat, L)+ assert L["effect"] == L["effect_with_cmd"], (seat, L)+ for a in rep["acts"][seat]:+ if a["k_effect"] is not None:+ assert a["k_effect"] - a["k_recv"] >= 2 and a["k_obs"] <= a["k_recv"], a+ # the reaction report (core 0.2.23) agrees with the act rows: acts with an effect = the report's acts+ rr = final["reaction"]["by_seat"]+ for seat in sides:+ assert rr[seat]["acts"] == link[seat]["effect"], (rr[seat], link[seat])+ assert [e["k"] for e in rep["events"]] == [30, 60, 90]+ if said == [200]:+ got = [r for r in rep["team_delivered"] if r["from"] == "A1"]+ assert [r["seat"] for r in got] == ["A2"], got # the teammate, once; never the other side+ assert got[0]["k"] >= got[0]["sent_k"]+ # the diagnostic rows are not replayed: the fresh replay of the service's episode passed+ assert final["deterministic"]+++def main():+ tests = [(n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)]+ bad = 0+ for name, f in tests:+ t = time.time()+ try:+ f()+ print(f"ok {name} ({time.time() - t:.1f} s)")+ except Exception: # noqa: BLE001+ import traceback+ bad += 1+ print(f"FAIL {name}\n{traceback.format_exc()}")+ print(f"{len(tests) - bad}/{len(tests)} passed")+ return 1 if bad else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/turn.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/turn.pynew file mode 100644index 0000000000..59c40b1944--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/turn.py@@ -0,0 +1,349 @@+"""Protocol eai-standard-turn/1.0: turns decided by the plugin (Match.to_move), one chess clock per seat (CLOCK_S of+wall time, running only on its own turn, service time excluded; out of time = the match is lost), and after every+action that does not end the match its actor reviews (ready WHY PLAN) before play goes on.++Phases: prepare (until every seat sent start; after the first, START_TIMEOUT_S: a side that has not started by then+loses, "no_show"; if none started, incomplete; a single side has START_TIMEOUT_S from the service start, else it+loses; the collect before the start decides the same at once, core 0.2.7) -> play -> over.+An action or review out of turn: 409; one action in flight per seat: 429; a seat that stops playing on its turn+(collect hook) loses ("abandoned"); a single side whose match has started loses at the collect whoever is on turn+(core 0.2.6). With more than two sides a side that loses on the clock may retire while the+others play on (Match.retire); observations may carry a query (observation parameters) that the sport validates.+Images (core 0.2.8): the observation's cameras and an action's reply images (Match.reply_views) are snapshotted under+the lock and drawn after it is released, so drawing never blocks the other seats; the seat's clock stands still+while its images are drawn. The core tells the sport whose review is due (Match.awaiting_review).+"""+from __future__ import annotations++import base64+import os+import threading+import time+import traceback++from .diaglog import jsonable, view_steps+from .service import Service+from .realtime import query_of+from .sport import FINISHED, Refused, parse_action++WAIT_MAX_S = 60.0+REVIEW_MAX_CHARS = 2000+++class TurnService(Service):+ protocol = "turn"+ protocol_id = "eai-standard-turn/1.0"++ def __init__(self, *a, **kw):+ self.clock_s = float(os.environ.get("CLOCK_S", "3600"))+ super().__init__(*a, clock_s=self.clock_s, **kw)+ self.start_deadline = self.on_turn = self.review_due = None+ if len(self.cfg.side_list()) == 1: # nobody to wait for: the start window opens now+ self.start_deadline = time.time() + self.start_window()+ for st in self.seats.values():+ st.stats.update(n_act=0, n_observe=0, n_wait=0, refused_busy=0, refused_turn=0, refused_not_model=0,+ refused_invalid=0, n_reviews=0)++ def routes(self, post):+ fns = ({"start": self.start, "observe": self.observe, "act": self.act, "ready": self.ready, "wait": self.wait}+ if post else {"spec": self.spec, "status": self.status})+ out = {ep: self.guarded(ep, fn) for ep, fn in fns.items()}+ if post:+ out["say"] = self.say+ out["team"] = self.team # read-only, never consumes (core 0.2.20)+ return out++ @property+ def review_due(self):+ return self._review_due++ @review_due.setter+ def review_due(self, seat):+ """The seat whose review is due; the sport sees it as Match.awaiting_review (core 0.2.8)."""+ self._review_due = seat+ self.m.awaiting_review = seat++ def guarded(self, ep, fn):+ """Every call runs under the lock, its service time is taken off the caller's clock, final.json follows. A+ handler may return (code, reply, job): the job (images) is drawn after the lock is released, with the+ caller's clock stopped, and attached to the reply as `observation`."""+ def run(seat, body):+ if ep == "spec":+ return fn(seat, body)+ st = self.seats[seat]+ if ep == "act" and not st.act_lock().acquire(blocking=False):+ with self.cond:+ st.count("refused_busy")+ return 429, {"refused": True, "busy": True, "error": "busy: one action at a time"}+ try:+ with self.cond:+ t = time.time()+ try:+ res = fn(seat, body)+ except Exception as exc: # noqa: BLE001+ if exc.__class__.__name__ == "Refused":+ raise+ traceback.print_exc()+ self.failure(ep, exc)+ return 500, {"error": "technical failure"} # details: the logs, never the player+ finally:+ if ep not in ("wait", "status"):+ self.busy(seat, t)+ self.write_final()+ if len(res) == 2 or res[2] is None:+ return res[:2]+ st.freeze(time.time())+ return self.finish_images(ep, seat, *res)+ finally:+ if ep == "act":+ st.act_lock().release()+ return run++ def finish_images(self, ep, seat, code, out, job):+ """Off the lock: draw `job` and attach it (observe: the camera images; act: the result of the action)."""+ st = self.seats[seat]+ try:+ obs = self.reply_images(seat, job) if ep == "act" else self.observe_images(seat, job, out["observation"])+ except Exception as exc: # noqa: BLE001+ traceback.print_exc()+ with self.cond:+ st.thaw(time.time())+ self.failure(f"{ep}_images", exc)+ with self.cond:+ self.write_final()+ return 500, {**out, "error": "technical failure"}+ with self.cond:+ st.thaw(time.time())+ self.write_final()+ out["observation"] = obs+ return code, out++ def observe_images(self, seat, job, meta) -> dict:+ out = self.draw(seat, job)+ obs = dict(meta)+ if out is not None:+ obs = {"image_png_b64": base64.b64encode(out["png"]).decode(), **meta}+ if out.get("tiles"):+ obs["tiles"] = out["tiles"]+ return obs++ def spec_core(self):+ return {"clock": {"total_s": self.clock_s, "runs": "on your turn only (your actions and your reviews); the "+ "time the service is busy does not count; out of time = you lose the match",+ "start_window_s": self.start_window()},+ "start": self.start_rule(),+ "decision_rule": ("program play: your own program may act without a new model response; one action "+ "in flight" if os.environ.get("RCB_ACT_RULE") == "program" else+ "a new model response before every action")}++ # ------------------------------------------------------------------ clock and turns+ def set_turn(self, seat):+ now = time.time()+ if self.on_turn is not None:+ self.seats[self.on_turn].stop_turn(now)+ self.on_turn = seat+ if seat is not None:+ self.seats[seat].start_turn(now)+ self.ep.write("turn", seat=seat, clock_left_s=round(self.seats[seat].clock_left(), 1))+ self.cond.notify_all()++ def busy(self, seat, t):+ st = self.seats[seat]+ if self.on_turn == seat and st.turn_t0 is not None:+ st.turn_busy += time.time() - max(t, st.turn_t0)++ def on_end(self):+ self.set_turn(None)++ def lose(self, seat, why):+ if super().lose(seat, why): # retired; the others play on+ self.review_due = None if self.review_due == seat else self.review_due+ if self.phase == "play" and (self.on_turn == seat or self.on_turn is None+ or self.seats[self.on_turn].retired):+ self.set_turn(self.m.to_move())+ return True+ return False++ # ------------------------------------------------------------------ replies+ def state(self, seat, query=None, since=None):+ others = [s for s in self.cfg.seats if s != seat]+ if self.phase == "prepare":+ turn = "start" if not self.seats[seat].joined else "waiting for the opponent to start"+ elif self.phase == "over":+ turn = "over"+ elif self.on_turn == seat:+ turn = "review" if self.review_due == seat else "you"+ else:+ turn = "opponent"+ out = {"seat": seat, "phase": self.phase, "turn": turn, "your_turn": turn in ("you", "review"),+ "awaiting_review": self.review_due == seat, "done": self.phase == "over",+ **self.observation(seat, query, since), "clock_left_s": round(self.seats[seat].clock_left(), 1)}+ if self.retired:+ out["retired"] = list(self.retired)+ if len(others) == 1:+ out["opponent_clock_left_s"] = round(self.seats[others[0]].clock_left(), 1)+ if self.phase == "over":+ o = self.outcome()+ w, side = o.winner, self.cfg.side_of(seat)+ out.update({"reason": self.reason, "won": w == side,+ "winner": None if w is None else ("you" if w == side else "opponent")})+ if len(self.cfg.side_list()) > 2:+ out["place"] = o.ranking.index(side) + 1 if side in o.ranking else None+ return out++ def status(self, seat, body=None):+ return 200, {"state": self.state(seat, since=self.team_since(body))}++ def gate(self, seat):+ if self.phase == "over": # core 0.2.26: 409 and the final state, nothing drawn+ return 409, {"error": "the match is over", "state": self.state(seat)}+ if self.phase == "prepare":+ return 409, {"error": "the match has not started (both players must send start)", "state": self.state(seat)}+ return None++ def start(self, seat, body):+ st = self.seats[seat]+ if self.phase != "prepare" or st.joined:+ return 409, {"error": "already started", "state": self.state(seat)}+ st.meter.check_ready()+ st.joined = True+ self.ep.write("start", seat=seat)+ if all(s.joined for s in self.seats.values()):+ self.begin()+ else:+ self.start_deadline = time.time() + self.start_window()+ self.cond.notify_all()+ return 200, {"started": True, "state": self.state(seat)}++ def begin(self):+ self.phase, self.start_deadline = "play", None+ self.bc.event("run")+ self.bc.frame(force=True)+ self.set_turn(self.m.to_move())++ def observe(self, seat, body):+ g = self.gate(seat)+ if g:+ return g+ query = query_of(body)+ since = self.team_since(body)+ self.seats[seat].count("n_observe")+ (job, meta), now = self.query_guard(seat, query, lambda: (self.camera_job(seat, query),+ self.state(seat, query, since)))+ obs_id = self.seats[seat].stats["n_observe"] # diagnostics (core 0.2.25): never replayed+ self.diag("observe", seat=seat, obs_id=obs_id, k=self.m.k, view_steps=view_steps(meta, job, self.m.k),+ query=query)+ self.acts.observed(seat, obs_id)+ return 200, {"state": now, "observation": dict(meta)}, job # drawn off the lock++ def act(self, seat, body):+ g = self.gate(seat)+ if g:+ return g+ st = self.seats[seat]+ if self.on_turn != seat or self.review_due == seat:+ st.count("refused_turn")+ why = "review your last action first" if self.review_due == seat else "it is not your turn"+ return 409, {"error": why, "state": self.state(seat)}+ try:+ cmd = parse_action(self.layer, seat, body, self.m, {"clock_left_s": {s: x.clock_left() for s, x in+ self.seats.items()}})+ except Refused as exc: # a malformed action: the player's own error, never a failure+ self.refused_invalid(seat, exc)+ raise+ if not st.meter.decided_by_model():+ st.count("refused_not_model")+ return 429, {"refused": True, "error": "refused: no new model response since your previous action"}+ st.count("n_act")+ if st.clock_left() < 0:+ self.lose(seat, "clock")+ return 200, {"clock_forfeit": "your clock ran out: you lose the match", "state": self.state(seat)}+ low, info = self.layer.lower(seat, cmd, None, self.m)+ act_id = self.acts.new(seat) # diagnostics (core 0.2.25): act -> observation -> effect+ self.diag("act_received", seat=seat, k=self.m.k, act_id=act_id, obs_id_last=self.acts.last_obs.get(seat),+ decision=cmd)+ self.ep.write("cmd", k=self.m.k, seat=seat, cmd=low, model_call=st.meter.last_call(),+ clock_used_s=round(st.clock_used(), 1))+ k_cmd = self.m.k+ applied = self.m.apply(seat, low) or {}+ self.diag("effect", seat=seat, act_id=act_id, k=k_cmd, info=jsonable(applied),+ **({"rejected": True} if "rejected" in applied else {}))+ job = self.reply_job(seat, low, applied) # the result's images: snapshot now, drawn off the lock+ info = {**applied, **info}+ self.bc.frame(force=True)+ self.bc.event("action", seat=seat, scores=self.m.scores())+ if self.m.phase().state == FINISHED:+ self.end("match_over")+ else:+ self.review_due = seat+ return 200, {**self.layer.reply(seat, cmd, info, self.m), "state": self.state(seat)}, job++ def ready(self, seat, body):+ g = self.gate(seat)+ if g:+ return g+ st = self.seats[seat]+ if self.review_due != seat:+ st.count("refused_turn")+ return 409, {"error": "no review is due from you now (reviews follow each of your actions)",+ "state": self.state(seat)}+ why, plan = body.get("why"), body.get("plan")+ if not (isinstance(why, str) and isinstance(plan, str) and why.strip() and plan.strip()):+ return 400, {"error": "ready needs two non-empty texts: WHY and PLAN"}+ if len(why) > REVIEW_MAX_CHARS or len(plan) > REVIEW_MAX_CHARS:+ return 400, {"error": f"WHY and PLAN are limited to {REVIEW_MAX_CHARS} characters each"}+ rv = {"seat": seat, "after_action": self.m.k, "why": why.strip(), "plan": plan.strip(),+ "clock_used_s": round(st.clock_used(), 1)}+ self.reviews.append(rv)+ st.count("n_reviews")+ self.ep.write("review", **rv)+ self.review_due = None+ if st.clock_left() < 0:+ self.lose(seat, "clock")+ return 200, {"accepted": "review recorded", "clock_forfeit": "your clock ran out: you lose the match",+ "state": self.state(seat)}+ if self.m.to_move() != seat:+ self.set_turn(self.m.to_move())+ return 200, {"accepted": "review recorded", "state": self.state(seat)}++ def wait(self, seat, body):+ try:+ timeout = min(WAIT_MAX_S, max(0.0, float(body.get("timeout_s", WAIT_MAX_S))))+ except (TypeError, ValueError, OverflowError):+ return 400, {"error": "timeout_s must be a number"}+ since = self.team_since(body)+ self.seats[seat].count("n_wait")+ deadline = time.time() + timeout+ while self.phase != "over" and self.on_turn != seat and time.time() < deadline:+ self.cond.wait(min(1.0, max(0.01, deadline - time.time())))+ return 200, {"state": self.state(seat, since=since)}++ # ------------------------------------------------------------------ watchdog, collect+ def loop(self):+ while True:+ time.sleep(0.5)+ with self.cond:+ if self.finalizing:+ return+ if self.phase == "prepare" and self.start_deadline and time.time() > self.start_deadline:+ self.start_deadline = None+ if self.close_start_window():+ self.begin()+ elif self.phase == "play" and self.on_turn and self.seats[self.on_turn].clock_left() < 0:+ self.lose(self.on_turn, "clock")++ def collect(self):+ def run():+ with self.cond:+ if self.phase == "play" and self.on_turn:+ s = self.on_turn+ self.lose(s, "clock" if self.seats[s].clock_left() < 0 else "abandoned")+ elif self.no_show_at_collect(): # before the start: a side not started loses (core 0.2.7)+ self.start_deadline = None+ elif not self.abandon_single(): # a single side off its turn also loses (core 0.2.6)+ self.end("incomplete" if self.phase == "prepare" else "collected")+ threading.Thread(target=run, daemon=True).start()++ def extra_final(self):+ return {"clock_s": self.clock_s, "clock_used_s": {s: round(st.clock_used(), 1) for s, st in self.seats.items()},+ "started": {s: st.joined for s, st in self.seats.items()}}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/workers.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/workers.pynew file mode 100644index 0000000000..a1636b44ba--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/core/workers.py@@ -0,0 +1,121 @@+"""Worker processes for slow per-seat work outside the world lock (rendering, planning): one process per (kind, seat),+one request in flight. The sport answers Sport.worker_init(kind, seat, cfg) and Sport.worker_call(obj, kind, job);+the kind "camera" is the core's own: the sport's camera definitions drawn by the task's renderer (core/observe.py)."""+from __future__ import annotations++import json+import os+import pickle+import select+import struct+import subprocess+import sys+import threading+import time+++def _send(f, obj):+ b = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)+ f.write(struct.pack("<Q", len(b)) + b)+ f.flush()+++def _read(f, n, deadline):+ buf = b""+ fd = f.fileno()+ while len(buf) < n:+ if deadline is not None:+ left = deadline - time.monotonic()+ if left <= 0 or not select.select([fd], [], [], left)[0]:+ raise TimeoutError("worker timed out")+ chunk = os.read(fd, n - len(buf))+ if not chunk:+ raise EOFError("worker closed")+ buf += chunk+ return buf+++def _recv(f, deadline=None):+ (n,) = struct.unpack("<Q", _read(f, 8, deadline))+ return pickle.loads(_read(f, n, deadline))+++def affinity(name: str):+ """Pin this process to the CPUs in environment variable `name` (e.g. "4-7,9"), if set."""+ v = os.environ.get(name, "")+ if v:+ cpus = set()+ for part in v.split(","):+ a = part.split("-")+ cpus.update(range(int(a[0]), int(a[-1]) + 1))+ os.sched_setaffinity(0, cpus)+++class ProcessWorker:+ def __init__(self, plugin: str, kind: str, seat: str, cfg: dict, timeout: float = 30.0):+ self.timeout, self.lock = timeout, threading.Lock()+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ self.proc = subprocess.Popen([sys.executable, "-m", "core.workers", plugin, kind, seat, json.dumps(cfg)],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=root)+ if _recv(self.proc.stdout, time.monotonic() + 120) != "ready":+ self.close()+ raise RuntimeError("worker startup failed")++ def call(self, job, wait: bool = False):+ """One job; a second one in flight is refused (BlockingIOError) unless `wait` (then it queues)."""+ if not self.lock.acquire(blocking=wait):+ raise BlockingIOError("one request per seat and worker may be in flight")+ try:+ _send(self.proc.stdin, job)+ ok, value = _recv(self.proc.stdout, time.monotonic() + self.timeout)+ if not ok:+ raise RuntimeError(value)+ return value+ except Exception:+ self.close()+ raise+ finally:+ self.lock.release()++ def close(self):+ if self.proc.poll() is None:+ self.proc.terminate()+ try:+ self.proc.wait(timeout=2)+ except subprocess.TimeoutExpired:+ self.proc.kill()+++def main(plugin, kind, seat, cfg_json):+ from .episode import load_plugin+ from .sport import MatchConfig+ affinity(f"RO_{kind.upper()}_{seat}_CPUS")+ sport = load_plugin(plugin)+ cfg = MatchConfig.from_json(json.loads(cfg_json))+ if kind == "camera":+ from .observe import CameraWorker, players_scene+ obj = CameraWorker(players_scene(sport, plugin, cfg), cfg.renderer)+ call = lambda o, k, job: o.draw_job(job) # noqa: E731 (observation or reply images)+ else:+ obj = sport.worker_init(kind, seat, cfg)+ call = sport.worker_call+ out = os.fdopen(os.dup(1), "wb")+ os.dup2(2, 1) # stray prints of the simulator go to stderr+ sys.stdout = sys.stderr+ _send(out, "ready")+ while True:+ try:+ job = _recv(sys.stdin.buffer)+ except EOFError:+ return+ t0 = time.monotonic()+ try:+ res = call(obj, kind, job)+ res["worker_s"] = time.monotonic() - t0+ _send(out, (True, res))+ except Exception as exc: # noqa: BLE001+ _send(out, (False, repr(exc)))+++if __name__ == "__main__":+ main(*sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/metering/think_proxy.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/metering/think_proxy.pynew file mode 100644index 0000000000..f9b84a44f4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/metering/think_proxy.py@@ -0,0 +1,894 @@+#!/usr/bin/env python3+"""Model-traffic proxy that runs in a task's sim sidecar and meters the agent's thinking.++In interactive mode ("thinking costs sim time") the agent's harness talks to this proxy instead of+the model API: Codex (OpenAI Responses via OpenRouter) or Claude Code (Anthropic Messages, on a Claude+subscription). The proxy+ * holds the real credentials (from its own environment: `OPENROUTER_API_KEY` for OpenRouter,+ `CLAUDE_CODE_OAUTH_TOKEN` for Anthropic); the agent container only has placeholders, so the agent+ cannot bypass the meter;+ * routes by request: Anthropic-style requests (an `anthropic-version` header, or a /v1/messages path)+ go to https://api.anthropic.com with the subscription token as Bearer; /backend-api/* (Codex logged in with a+ ChatGPT subscription, see harbor_agents/codex_chatgpt_think.py) goes to https://chatgpt.com with the sidecar's+ CODEX_ACCESS_TOKEN / CODEX_ACCOUNT_ID; everything else goes to OpenRouter (or Azure, THINK_OPENAI_ROUTE). A seat+ on THINK_OPENAI_ROUTE=chatgpt gets the ChatGPT backend only: any other request is refused (403);+ * follows no upstream redirect: a 30x goes back to the agent, never with the real credentials to another host;+ * forwards everything to OpenRouter unchanged, except the model-turn repair that Gemini needs+ (same rule as harbor_agents/or_proxy.py);+ * reads the `usage` of every completed response (streamed or not) and keeps cumulative counts:+ requests, input, cached input, output and reasoning tokens;+ * publishes the counts atomically to `THINK_USAGE_FILE` (default /data/think_usage.json) and on+ `GET /think/usage`, which the game service reads to turn "tokens since the last observation"+ into simulated time and to check that every decision follows a new model call (see think_clock.py);+ * logs every request to `THINK_CALLS_FILE` (default /data/think_calls.jsonl) for the cheating audit (rules 5.6):+ sequence number, start/end time, the client's address, User-Agent and harness session headers, the route, the+ model, the HTTP status, its usage, and an excerpt of what the model emitted (tool calls, text). Never the+ credentials or the request body;+ * with THINK_CLIENT_HOST set (multi-seat duels), serves only that compose service;+ * forwards only the model endpoints the harnesses use (ALLOWED_PATHS: Messages, Responses, the ChatGPT backend's+ Codex endpoints); any other path is refused (403) and logged as blocked. It locks the seat's model: THINK_MODEL+ (comma-separated names or fnmatch patterns, provider prefixes ignored; per seat RO_SEAT_ENV_THINK_MODEL_<seat>), or+ else the first model the seat used; a request for another model is refused (403). It strips server-side tools+ the provider would run on the agent's behalf (web search / fetch, code execution, remote MCP, file search,+ OpenRouter plugins and the `:online` model suffix): the model reaches nothing outside the game through the meter.++Usage (inside the sidecar): python3 think_proxy.py [port=18090]+Standard library only.+"""+from __future__ import annotations++import http.client+import json+import re+import uuid+import os+import sys+import threading+import time+import urllib.error+import urllib.request+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++UPSTREAM = os.environ.get("THINK_UPSTREAM", "https://openrouter.ai/api")+ANTHROPIC_UPSTREAM = os.environ.get("THINK_ANTHROPIC_UPSTREAM", "https://api.anthropic.com")+CHATGPT_UPSTREAM = os.environ.get("THINK_CHATGPT_UPSTREAM", "https://chatgpt.com") # Codex on a ChatGPT subscription+# THINK_CHATGPT_MODEL (per seat: RO_SEAT_ENV_THINK_CHATGPT_MODEL_<seat>, from players.toml `deployment` of a ChatGPT+# subscription player) pins the seat's ChatGPT-backend calls to that model: a request the model lock admitted is sent+# with this model (rec["model_alias"] keeps the name the agent sent). The harness can then use its own slug for the+# model family (Codex 0.158.0 has metadata for "gpt-6-sol", none for "gpt-6.1-sol") while the backend serves the pinned+# model ("gpt-6.1-sol"). Empty: no pin.+CHATGPT_MODEL = os.environ.get("THINK_CHATGPT_MODEL", "").strip()+++def chatgpt_pin(body: bytes, rec: dict) -> bytes:+ """The ChatGPT backend's pinned model (THINK_CHATGPT_MODEL) in place of the model the agent named."""+ try:+ d = json.loads(body)+ except ValueError:+ return body+ if not isinstance(d, dict) or not isinstance(d.get("model"), str) or d["model"] == CHATGPT_MODEL:+ return body+ rec["model_alias"] = d["model"]+ d["model"] = CHATGPT_MODEL+ return json.dumps(d).encode()+# OpenAI-style requests (Codex) go to OpenRouter unless THINK_OPENAI_ROUTE=azure: then to an Azure AI Foundry resource+# (AZURE_AI_ENDPOINT, e.g. https://<res>.services.ai.azure.com/models, key AZURE_AI_API_KEY), /v1/... -> /openai/v1/...,+# the model's provider prefix dropped ("openai/gpt-6-astra" -> deployment "gpt-6-astra").+# THINK_OPENAI_ROUTE=azure_sol is a second Azure resource with the same wire (an Azure OpenAI resource, e.g.+# https://<res>.openai.azure.com/): its own AZURE_SOL_ENDPOINT, AZURE_SOL_API_KEY and AZURE_SOL_DEPLOYMENTS. A seat's+# route is set per seat (THINK_OPENAI_ROUTE_<seat>, core/launch.py), and only that seat's proxy gets its variables.+# On azure_sol the deployments are pinned: a request for a model that is not one of AZURE_SOL_DEPLOYMENTS goes to them+# anyway (rec["model_alias"] keeps the name the agent sent). The agent can then use its harness's own name for the+# model family (Codex knows "gpt-6-sol" and has its metadata) while the resource serves its deployment ("gpt-6.1-sol").+# THINK_OPENAI_ROUTE=chatgpt: the seat plays on a ChatGPT subscription only. Its proxy forwards the ChatGPT backend+# (/backend-api/*) and refuses every other request (OpenRouter / Azure / Anthropic paths) before any credential is+# touched, so a program in that seat cannot reach another provider with a task-wide key (core/launch.py also drops those+# keys from the seat's proxy).+AZURE_ROUTES = {"azure": ("AZURE_AI_ENDPOINT", "AZURE_AI_API_KEY", "AZURE_DEPLOYMENTS"),+ "azure_sol": ("AZURE_SOL_ENDPOINT", "AZURE_SOL_API_KEY", "AZURE_SOL_DEPLOYMENTS")}+ROUTE = os.environ.get("THINK_OPENAI_ROUTE", "openrouter").strip().lower()+AZURE = ROUTE in AZURE_ROUTES+AZURE_ROUTE = ROUTE if AZURE else "azure"+AZURE_ENDPOINT_VAR, AZURE_KEY_VAR, AZURE_POOL_VAR = AZURE_ROUTES[AZURE_ROUTE]+AZURE_PINNED = AZURE_ROUTE == "azure_sol"+CHATGPT_ONLY = ROUTE == "chatgpt"+AZURE_BASE = os.environ.get(AZURE_ENDPOINT_VAR, "").strip().rstrip("/").removesuffix("/models")+USAGE_FILE = os.environ.get("THINK_USAGE_FILE", "/data/think_usage.json")+CALLS_FILE = os.environ.get("THINK_CALLS_FILE") or (USAGE_FILE.replace("think_usage", "think_calls").rsplit(".json", 1)[0] + ".jsonl"+ if "think_usage" in os.path.basename(USAGE_FILE)+ else os.path.join(os.path.dirname(USAGE_FILE) or ".", "think_calls.jsonl"))+SESSION_HEADERS = ("x-claude-code-session-id", "session_id", "conversation_id", "originator", "x-app", "openai-beta")+EXCERPT_MAX = 2000+ACT_RE = re.compile(os.environ.get("THINK_ACT_REGEX", r"\bgame\s+act\b"))+CONTINUE_TEXT = "Continue from where you left off."+MODEL_ITEM_TYPES = {"reasoning", "function_call", "custom_tool_call", "web_search_call", "local_shell_call",+ "computer_call", "mcp_call", "image_generation_call", "code_interpreter_call", "item_reference"}+HOP_BY_HOP = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-connection",+ "content-length", "host", "accept-encoding", "authorization", "x-api-key", "api-key", "chatgpt-account-id"}+# Azure deployment failover (program play tasks): AZURE_DEPLOYMENTS lists replicas of one model (e.g.+# "gpt-6-astra,gpt-6-astra-2,gpt-6-astra-3"; empty = no failover). Each deployment has its own per-minute token+# limit, and Azure may report an exceeded limit inside an HTTP 200 stream. The request is sent to the next deployment,+# before any byte reaches the agent, when a deployment+# * answers HTTP 408, 429, 500, 502, 503 or 504 (AZURE_FAILOVER_STATUS; Azure's own 408 "The operation was timeout."+# came ~21 s into a request in the 2026-10-14 soccer pilots),+# * times out or drops the connection (socket timeout, connection reset) before its response headers, or during the+# first events of a stream, which the proxy reads before it relays anything (azure_peek),+# * opens its stream with a rate-limit / overload / server-error failure, or closes it before any output.+# A failure after the first byte was relayed to the agent is never retried: the agent sees it as before. The last+# deployment tried answers the agent whatever it is (its error included). The proxy then stays on the deployment that+# worked. Switches are recorded (rec["azure_failovers"] with the reason, USAGE["azure_failovers"]); they are not model+# failures and do not count as rate_limit_retries. Empty AZURE_DEPLOYMENTS, and every non-Azure upstream: no failover.+AZURE_POOL = [d.strip() for d in os.environ.get(AZURE_POOL_VAR, "").split(",") if d.strip()]+AZURE_CURRENT = [0]+class _NoRedirect(urllib.request.HTTPRedirectHandler):+ """Follow no redirect: a 30x goes back to the client as it is, so the credentials this proxy adds (Authorization,+ api-key, chatgpt-account-id) never travel to a host the redirect names."""+ def redirect_request(self, *a, **kw):+ return None+++OPENER = urllib.request.build_opener(_NoRedirect) # replaces the default (following) redirect handler+AZURE_RATE_WORDS = ("rate limit", "rate_limit", "too_many_requests", "server_is_overloaded", '"429"')+# A failed stream's error object (not the whole response, which echoes the instructions) naming a server-side fault.+AZURE_SERVER_WORDS = ("server_error", "internal_error", "service_unavailable", "overloaded", "timeout", "timed out",+ '"408"', '"500"', '"502"', '"503"', '"504"')+AZURE_FAILOVER_STATUS = (408, 429, 500, 502, 503, 504)+UPSTREAM_TIMEOUT_S = float(os.environ.get("THINK_UPSTREAM_TIMEOUT_S", "") or 600) # socket timeout per upstream read+++def upstream_fault(exc) -> str | None:+ """A short reason when `exc` is a timeout or a dropped connection of the upstream (worth another deployment)."""+ if isinstance(exc, urllib.error.HTTPError):+ return None+ if isinstance(exc, urllib.error.URLError) and isinstance(exc.reason, BaseException):+ exc = exc.reason+ if isinstance(exc, (TimeoutError, ConnectionError, http.client.IncompleteRead)):+ return type(exc).__name__+ return None+++def azure_peek(resp, limit=1 << 20):+ '''Read whole SSE events until one that is not response.created / response.in_progress. Returns the bytes read+ and, if that event is a rate-limit / overload failure, a short reason (else None).'''+ buf, seen = b"", 0+ read = getattr(resp, "read1", resp.read)+ while len(buf) < limit:+ chunk = read(65536)+ if not chunk: # closed before any output: a stream always ends with an event+ head = buf.lstrip()+ return buf, ("stream closed before output" if not head or head.startswith((b"event:", b"data:")) else None)+ buf += chunk+ events = buf.replace(b"\r\n", b"\n").split(b"\n\n")[:-1]+ for ev in events[seen:]:+ seen += 1+ payload = b"\n".join(l[5:].strip() for l in ev.split(b"\n") if l.startswith(b"data:"))+ try:+ d = json.loads(payload) if payload and payload != b"[DONE]" else {}+ except ValueError:+ d = {}+ t = d.get("type", "") if isinstance(d, dict) else ""+ if t in ("response.created", "response.in_progress", ""):+ continue+ text = json.dumps(d).lower()+ if t in ("error", "response.failed"):+ err = (d.get("response") or {}).get("error") or d.get("error") or (d if t == "error" else {})+ if any(k in text for k in AZURE_RATE_WORDS):+ return buf, f"{t} ({(err.get('code') if isinstance(err, dict) else '') or 'rate limit'})"+ if any(k in json.dumps(err).lower() for k in AZURE_SERVER_WORDS):+ return buf, f"{t} ({(err.get('code') if isinstance(err, dict) else '') or 'server error'})"+ return buf, None+ return buf, None+++class PrefixedResponse:+ '''A response whose first bytes were already read by azure_peek.'''+ def __init__(self, resp, head):+ self.resp, self.head = resp, head+ self.status, self.headers = resp.status, resp.headers++ def read1(self, n=-1):+ if self.head:+ out, self.head = self.head, b""+ return out+ return getattr(self.resp, "read1", self.resp.read)(n)++ read = read1++ def close(self):+ self.resp.close()+++RATE_LIMIT_WAITS_S = tuple(float(x) for x in os.environ.get("THINK_RETRY_WAITS_S", "").split(",") if x.strip())++LOCK = threading.Lock()+USAGE = {"requests": 0, "responses_with_usage": 0, "input_tokens": 0, "cached_input_tokens": 0,+ "output_tokens": 0, "reasoning_tokens": 0, "updated_at": 0.0,+ "model_calls_completed": 0, "in_flight": 0, "last_completed_at": 0.0,+ "epoch": uuid.uuid4().hex, "failed_model_calls": 0,+ "rate_limit_retries": 0, "last_response_seq": None, "blocked_requests": 0,+ "act_calls_completed": 0, "last_act_call_at": 0.0, "last_act_response_seq": None, "last_act_started_at": 0.0}+++def publish() -> None:+ tmp = USAGE_FILE + ".tmp"+ os.makedirs(os.path.dirname(USAGE_FILE) or ".", exist_ok=True)+ with open(tmp, "w") as f:+ json.dump(USAGE, f)+ os.replace(tmp, USAGE_FILE)+++def azure_model(body: bytes) -> bytes:+ """Azure deployments are named without the provider prefix the agent uses for OpenRouter."""+ try:+ d = json.loads(body)+ except ValueError:+ return body+ if isinstance(d, dict) and isinstance(d.get("model"), str) and "/" in d["model"]:+ d["model"] = d["model"].rsplit("/", 1)[1]+ return json.dumps(d).encode()+ return body+++def is_model_call(method: str, path: str) -> bool:+ """A model turn: Anthropic Messages (not count_tokens), OpenAI Responses / Chat Completions (OpenRouter or the+ ChatGPT backend). Model listings, token counting and telemetry are not."""+ if method != "POST":+ return False+ p = path.split("?")[0]+ if "count_tokens" in p:+ return False+ return p.endswith(("/v1/messages", "/responses", "/chat/completions"))+++# Anti-cheat (audit 2026-10-08, G4): the proxy is no open forwarder with the real credentials.+ALLOWED_PATHS = {("POST", "/v1/messages"), ("POST", "/v1/messages/count_tokens"), ("POST", "/v1/responses"),+ ("POST", "/v1/chat/completions"), ("POST", "/openai/v1/responses"),+ ("POST", "/backend-api/codex/responses"), ("GET", "/backend-api/codex/models"), ("GET", "/v1/models"),+ ("POST", "/v1/responses/compact"), ("POST", "/backend-api/codex/responses/compact")} # Codex compaction+SERVER_TOOL_PREFIXES = ("web_search", "web_fetch", "code_execution", "bash_code_execution",+ "text_editor_code_execution", "code_interpreter", "file_search", "mcp") # tool "type"s+STRIP_KEYS = ("mcp_servers", "plugins", "web_search_options", "container", "tool_resources")+MODEL_LOCK = [m.strip() for m in os.environ.get("THINK_MODEL", "").split(",") if m.strip()]+FIRST_MODEL: list = [] # without THINK_MODEL: the first model this seat used+++def path_allowed(method: str, path: str) -> bool:+ return (method, path.split("?")[0].rstrip("/") or "/") in ALLOWED_PATHS+++def bare_model(name) -> str:+ """'openrouter/openai/gpt-x:online' -> 'gpt-x' (provider prefixes and OpenRouter variants dropped)."""+ return str(name or "").rsplit("/", 1)[-1].split(":", 1)[0].strip().lower()+++def model_allowed(name) -> bool:+ import fnmatch+ m = bare_model(name)+ if not m:+ return True # no model named (listings): nothing to lock+ if MODEL_LOCK:+ return any(fnmatch.fnmatchcase(m, bare_model(p)) for p in MODEL_LOCK)+ with LOCK:+ if not FIRST_MODEL:+ FIRST_MODEL.append(m)+ return m == FIRST_MODEL[0]+++def strip_server_tools(payload: dict) -> list:+ """Remove the provider-run tools and options from a request (in place); returns what was removed."""+ gone = []+ tools = payload.get("tools")+ if isinstance(tools, list):+ keep = []+ for t in tools:+ kind = str(t.get("type", "")) if isinstance(t, dict) else ""+ if kind.lower().startswith(SERVER_TOOL_PREFIXES): # client tools (function, custom) stay+ gone.append(kind)+ else:+ keep.append(t)+ if len(keep) != len(tools):+ payload["tools"] = keep+ if not keep:+ payload.pop("tools", None)+ payload.pop("tool_choice", None)+ for k in STRIP_KEYS:+ if k in payload:+ gone.append(k)+ payload.pop(k)+ model = payload.get("model")+ if isinstance(model, str) and ":online" in model:+ payload["model"] = model.replace(":online", "")+ gone.append(":online")+ if isinstance(payload.get("models"), list): # OpenRouter fallback models: another model+ gone.append("models")+ payload.pop("models")+ return gone+++def screen(method: str, path: str, body: bytes | None, rec: dict) -> tuple[int, str, bytes | None]:+ """Before anything is forwarded: (0, "", body to send) or (http status, reason, None) for a refusal."""+ if not path_allowed(method, path):+ return 403, "path not allowed (only the model endpoints of the harnesses)", None+ if not body:+ return 0, "", body+ try:+ payload = json.loads(body)+ except ValueError:+ return 400, "request body is not JSON", None+ if not isinstance(payload, dict):+ return 400, "request body is not a JSON object", None+ if not model_allowed(payload.get("model")):+ return 403, "model not allowed for this seat", None+ gone = strip_server_tools(payload)+ if gone:+ rec["stripped"] = gone+ return 0, "", json.dumps(payload).encode()+ return 0, "", body+++def log_call(rec: dict) -> None:+ line = json.dumps(rec, default=str)+ with LOCK:+ with open(CALLS_FILE, "a") as f:+ f.write(line + "\n")+++def _allowed_client(addr: str) -> bool:+ """Multi-seat duels: THINK_CLIENT_HOST names the only compose service allowed to use this proxy, so one seat+ cannot think on (or hide its thinking behind) the other seat's meter. Unset: anyone (single-player tasks)."""+ host = os.environ.get("THINK_CLIENT_HOST")+ if not host:+ return True+ try:+ import socket+ return addr in {ai[4][0] for ai in socket.getaddrinfo(host, None)}+ except OSError:+ return False+++class Excerpt:+ """What the model emitted in one response, from its stream or JSON body: tool calls and text, truncated."""+ def __init__(self):+ self.parts: list[str] = []+ self.n = 0++ def add(self, s) -> None:+ if not s or self.n >= EXCERPT_MAX:+ return+ s = str(s)[: EXCERPT_MAX - self.n]+ self.parts.append(s); self.n += len(s)++ def feed_event(self, ev: dict) -> None:+ t = ev.get("type", "")+ if t == "content_block_start": # Anthropic+ cb = ev.get("content_block") or {}+ if cb.get("type") in ("tool_use", "server_tool_use"):+ self.add(f"[tool {cb.get('name')}] ")+ elif t == "content_block_delta":+ d = ev.get("delta") or {}+ self.add(d.get("partial_json") or d.get("text"))+ elif t == "response.output_item.done": # OpenAI Responses+ it = ev.get("item") or {}+ if it.get("type") in ("function_call", "custom_tool_call"):+ self.add(f"[tool {it.get('name')}] {it.get('arguments') or it.get('input') or ''} ")+ elif it.get("type") == "local_shell_call":+ self.add(f"[shell] {json.dumps(it.get('action'))} ")+ elif t == "response.output_text.delta":+ self.add(ev.get("delta"))++ def feed_body(self, obj: dict) -> None:+ for cb in obj.get("content") or []: # Anthropic, non-streamed+ if cb.get("type") == "tool_use":+ self.add(f"[tool {cb.get('name')}] {json.dumps(cb.get('input'))} ")+ elif cb.get("type") == "text":+ self.add(cb.get("text"))+ for it in obj.get("output") or []: # Responses, non-streamed+ self.feed_event({"type": "response.output_item.done", "item": it})++ def text(self) -> str:+ return "".join(self.parts)+++def account(usage: dict) -> None:+ """Add one response's usage (Responses API or Chat Completions shape)."""+ if not isinstance(usage, dict):+ return 0+ inp = int(usage.get("input_tokens", usage.get("prompt_tokens", 0)) or 0)+ out = int(usage.get("output_tokens", usage.get("completion_tokens", 0)) or 0)+ det_in = usage.get("input_tokens_details") or usage.get("prompt_tokens_details") or {}+ det_out = usage.get("output_tokens_details") or usage.get("completion_tokens_details") or {}+ cached = int(det_in.get("cached_tokens", 0) or 0)+ if "cache_read_input_tokens" in usage or "cache_creation_input_tokens" in usage: # Anthropic shape+ cached = int(usage.get("cache_read_input_tokens", 0) or 0)+ inp += cached + int(usage.get("cache_creation_input_tokens", 0) or 0)+ with LOCK:+ USAGE["responses_with_usage"] += 1+ USAGE["input_tokens"] += inp+ USAGE["cached_input_tokens"] += cached+ USAGE["output_tokens"] += out+ USAGE["reasoning_tokens"] += int(det_out.get("reasoning_tokens", 0) or 0)+ USAGE["updated_at"] = time.time()+ publish()+ return out+++class AnthropicStream:+ """Collects one Messages stream's usage: input from message_start, final output from message_delta."""+ def __init__(self):+ self.usage: dict = {}++ def feed(self, line: bytes, excerpt: "Excerpt | None" = None) -> None:+ if not line.startswith(b"data:"):+ return+ try:+ ev = json.loads(line[5:].strip() or b"{}")+ except ValueError:+ return+ if excerpt is not None:+ excerpt.feed_event(ev)+ if ev.get("type") == "message_start":+ self.usage.update((ev.get("message") or {}).get("usage") or {})+ elif ev.get("type") == "message_delta" and ev.get("usage"):+ self.usage.update(ev["usage"])+++def is_anthropic(path: str, headers) -> bool:+ """Codex (OpenRouter) only uses /v1/responses (and /v1/models); Claude Code uses /v1/messages*, /api/*+ and always sends anthropic-version."""+ if path.startswith("/v1/responses") or path.startswith("/v1/chat"):+ return False+ return bool(headers.get("anthropic-version")) or path.startswith(("/v1/messages", "/v1/complete", "/api/"))+++def usage_from_sse_line(line: bytes) -> dict | None:+ if not line.startswith(b"data:"):+ return None+ data = line[5:].strip()+ if not data or data == b"[DONE]":+ return None+ try:+ ev = json.loads(data)+ except ValueError:+ return None+ if ev.get("type") in ("response.completed", "response.done", "response.incomplete"):+ return (ev.get("response") or {}).get("usage")+ if "usage" in ev and ev.get("object", "").startswith("chat.completion"):+ return ev.get("usage")+ return None+++def repair(body: bytes, path: str) -> bytes:+ if "/responses" not in path:+ return body+ try:+ payload = json.loads(body)+ except ValueError:+ return body+ items = payload.get("input")+ if isinstance(items, list) and items and isinstance(items[-1], dict) and (+ items[-1].get("role") == "assistant" or items[-1].get("type") in MODEL_ITEM_TYPES):+ items.append({"type": "message", "role": "user", "content": [{"type": "input_text", "text": CONTINUE_TEXT}]})+ return json.dumps(payload).encode()+ return body+++class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, fmt, *args):+ sys.stderr.write("think_proxy: %s\n" % (fmt % args))++ def _json(self, code: int, obj: dict) -> None:+ b = json.dumps(obj).encode()+ self.send_response(code); self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)++ def do_GET(self):+ if not _allowed_client(self.client_address[0]):+ self.send_error(403, "not your seat's proxy"); return+ if self.path.rstrip("/") == "/think/usage":+ with LOCK:+ return self._json(200, dict(USAGE))+ return self._forward(None)++ def do_POST(self):+ if not _allowed_client(self.client_address[0]):+ self.send_error(403, "not your seat's proxy"); return+ n = int(self.headers.get("Content-Length") or 0)+ return self._forward(self.rfile.read(n) if n else b"")++ def _forward(self, body: bytes | None) -> None:+ pre = {}+ code, why, body = screen(self.command, self.path, body, pre)+ if not code and CHATGPT_ONLY and not self.path.startswith("/backend-api/"):+ code, why = 403, "route chatgpt: only the ChatGPT backend (/backend-api/*) is forwarded for this seat"+ if code: # refused before any credential is touched+ rec = {"t0": round(time.time(), 3), "client": self.client_address[0], "method": self.command,+ "path": self.path.split("?")[0][:200], "user_agent": self.headers.get("User-Agent", ""),+ "model_call": False, "status": code, "blocked": why, "t1": round(time.time(), 3)}+ with LOCK:+ USAGE["blocked_requests"] = USAGE.get("blocked_requests", 0) + 1+ rec["epoch"] = USAGE["epoch"]+ publish()+ log_call(rec)+ return self._json(code, {"error": {"type": "think_proxy_refused", "message": f"think_proxy: {why}"}})+ chatgpt = self.path.startswith("/backend-api/") # Codex logged in with a ChatGPT subscription+ anthropic = not chatgpt and is_anthropic(self.path, self.headers)+ azure = AZURE and not chatgpt and not anthropic+ name = "CODEX_ACCESS_TOKEN" if chatgpt else ("CLAUDE_CODE_OAUTH_TOKEN" if anthropic else+ (AZURE_KEY_VAR if azure else "OPENROUTER_API_KEY"))+ key = os.environ.get(name, "")+ if body and azure:+ body = azure_model(body)+ elif body and chatgpt and CHATGPT_MODEL: # after the model lock admitted the agent's name+ body = chatgpt_pin(body, pre)+ elif body and not anthropic and not chatgpt:+ body = repair(body, self.path)+ model_call = is_model_call(self.command, self.path)+ rec = {"t0": round(time.time(), 3), "client": self.client_address[0], "method": self.command,+ "path": self.path.split("?")[0], "route": "chatgpt" if chatgpt else ("anthropic" if anthropic else (AZURE_ROUTE if azure else "openrouter")),+ "user_agent": self.headers.get("User-Agent", ""), "model_call": model_call,+ "session": {h: self.headers.get(h) for h in SESSION_HEADERS if self.headers.get(h)}, **pre}+ try:+ rec["model"] = (json.loads(body) or {}).get("model") if body else None+ except (ValueError, AttributeError):+ rec["model"] = None+ with LOCK:+ USAGE["requests"] += 1+ rec["seq"] = USAGE["requests"]+ rec["epoch"] = USAGE["epoch"]+ if model_call:+ USAGE["in_flight"] += 1+ publish() # publish in-flight and request count before the carrying response can trigger a tool+ try:+ if not key or (azure and not AZURE_BASE):+ rec["status"] = 500+ rec["error"] = "missing_upstream_credentials"+ return self._json(500, {"error": {"message": f"think_proxy: {name} (and {AZURE_ENDPOINT_VAR}) not set in the sidecar"}})+ self._forward_upstream(body, chatgpt, anthropic, key, rec, azure)+ except Exception as exc:+ rec["error"] = type(exc).__name__+ rec["completed"] = False+ self.close_connection = True+ finally:+ with LOCK:+ if model_call:+ USAGE["in_flight"] -= 1+ if rec.get("status") == 200 and rec.get("completed"):+ USAGE["model_calls_completed"] += 1+ USAGE["last_completed_at"] = time.time()+ USAGE["last_response_seq"] = rec["seq"]+ if rec.get("has_act"):+ USAGE["act_calls_completed"] += 1+ USAGE["last_act_call_at"] = time.time()+ USAGE["last_act_response_seq"] = rec["seq"]+ USAGE["last_act_started_at"] = rec["t0"]+ else:+ USAGE["failed_model_calls"] += 1+ publish()+ rec["t1"] = round(time.time(), 6)+ rec["epoch"] = USAGE["epoch"]+ log_call(rec)++ def _forward_upstream(self, body, chatgpt: bool, anthropic: bool, key: str, rec: dict, azure: bool = False) -> None:+ headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_BY_HOP}+ if azure: # Azure AI Foundry: api-key header, no bearer+ headers["api-key"] = key+ else:+ headers["Authorization"] = f"Bearer {key}" # the agent's placeholder credential is dropped above+ headers["Accept-Encoding"] = "identity"+ if anthropic: # subscription (OAuth) auth needs its beta flag+ betas = [b.strip() for b in headers.pop("anthropic-beta", headers.pop("Anthropic-Beta", "")).split(",") if b.strip()]+ if "oauth-2025-04-20" not in betas:+ betas.append("oauth-2025-04-20")+ headers["anthropic-beta"] = ",".join(betas)+ if chatgpt: # the subscription's account, not the agent's placeholder+ headers["chatgpt-account-id"] = os.environ.get("CODEX_ACCOUNT_ID", "")+ base = CHATGPT_UPSTREAM if chatgpt else (ANTHROPIC_UPSTREAM if anthropic else UPSTREAM)+ url = base.rstrip("/") + self.path # /v1/responses -> OpenRouter, /v1/messages -> Anthropic+ if azure: # /v1/responses -> <resource>/openai/v1/responses+ url = AZURE_BASE + "/openai" + (self.path if self.path.startswith("/v1") else "/v1" + self.path)+ req = urllib.request.Request(url, data=body, method=self.command, headers=headers)+ resp = None+ if azure and AZURE_POOL and self.command == "POST" and body:+ try:+ resp = self._azure_failover(url, body, headers, rec)+ except Exception as exc: # noqa: BLE001+ rec["status"] = 502; rec["error"] = repr(exc)[:200]+ return self._json(502, {"error": {"message": f"think_proxy upstream failure: {exc!r}"}})+ try:+ for attempt in (range(len(RATE_LIMIT_WAITS_S) + 1) if resp is None else ()):+ try:+ resp = OPENER.open(req, timeout=UPSTREAM_TIMEOUT_S); break+ except urllib.error.HTTPError as err:+ resp = err+ if err.code != 429 or attempt >= len(RATE_LIMIT_WAITS_S):+ break+ with LOCK:+ USAGE["rate_limit_retries"] += 1+ publish()+ rec.setdefault("retries", []).append({"status": 429, "at": time.time(),+ "wait_s": RATE_LIMIT_WAITS_S[attempt]})+ err.close()+ time.sleep(RATE_LIMIT_WAITS_S[attempt])+ except Exception as exc: # noqa: BLE001+ rec["status"] = 502; rec["error"] = repr(exc)[:200]+ return self._json(502, {"error": {"message": f"think_proxy upstream failure: {exc!r}"}})+ rec["status"] = resp.status+ if chatgpt: # subscription usage (x-codex-primary-used-percent, ...)+ limits = {k.lower(): v for k, v in resp.headers.items() if k.lower().startswith("x-codex-")}+ if limits:+ rec["codex_limits"] = limits+ with LOCK:+ USAGE["codex_limits"] = limits+ publish()+ self.send_response(resp.status)+ ctype = resp.headers.get("Content-Type", "")+ for k, v in resp.headers.items():+ if k.lower() not in HOP_BY_HOP:+ self.send_header(k, v)+ self.send_header("Connection", "close"); self.end_headers()+ audit = ResponseAudit(self.path, anthropic)+ streamed = "event-stream" in ctype+ whole = bytearray()+ read = getattr(resp, "read1", resp.read)+ rec["completed"] = False+ try:+ while True:+ chunk = read(4096) # never wait for a full 4 KB while SSE bytes are already available+ if not chunk:+ break+ rec.setdefault("upstream_first_byte_at", time.time())+ self.wfile.write(chunk); self.wfile.flush()+ rec.setdefault("downstream_first_byte_at", time.time())+ if streamed:+ audit.feed(chunk)+ else:+ whole.extend(chunk)+ if whole.lstrip().startswith((b"event:", b"data:")):+ streamed = True+ audit.feed(bytes(whole))+ whole.clear()+ if audit.terminal:+ rec["upstream_terminal_at"] = time.time()+ break+ if streamed:+ audit.finish()+ else:+ try:+ audit.body(json.loads(whole))+ except (ValueError, TypeError):+ audit.failed = True+ rec["completed"] = bool(resp.status == 200 and audit.success and not audit.failed)+ finally:+ resp.close()+ rec["output_tokens"] = account(audit.usage) if audit.usage else 0+ rec["excerpt"] = audit.excerpt.text()+ rec["response_id"] = audit.response_id+ rec["tool_calls"] = audit.tools+ rec["has_act"] = bool(rec.get("completed") and audit.has_act())+ rec["stream_error"] = audit.failed or not audit.success+ self.close_connection = True+++ def _azure_failover(self, url, body, headers, rec):+ '''Send to the current deployment; on a transient failure before any byte was relayed (HTTP 408/429/5xx, a+ timeout or dropped connection, an in-stream rate-limit / server failure or an empty stream), try the next one.+ The last deployment's answer, or its exception, goes to the agent as it is.'''+ try:+ data = json.loads(body)+ except ValueError:+ data = None+ if not isinstance(data, dict):+ return None+ if data.get("model") not in AZURE_POOL:+ if not AZURE_PINNED:+ return None # not a pooled model: the ordinary path+ rec["model_alias"] = data.get("model") # pinned route: served by the pool's deployment+ n = len(AZURE_POOL)+ start = AZURE_CURRENT[0]+ resp = None+ for i in range(n):+ idx = (start + i) % n+ data["model"] = AZURE_POOL[idx]+ payload = json.dumps(data).encode()+ h = dict(headers); h["Content-Length"] = str(len(payload))+ req = urllib.request.Request(url, data=payload, method="POST", headers=h)+ last = i == n - 1+ try:+ resp = OPENER.open(req, timeout=UPSTREAM_TIMEOUT_S)+ except urllib.error.HTTPError as err:+ resp = err+ if err.code in AZURE_FAILOVER_STATUS and not last:+ err.close()+ self._azure_switch(rec, idx, f"HTTP {err.code}")+ continue+ break+ except Exception as exc: # noqa: BLE001+ fault = upstream_fault(exc)+ if fault is None or last:+ raise+ self._azure_switch(rec, idx, fault)+ continue+ if data.get("stream") and not last:+ try:+ head, failed = azure_peek(resp) # nothing has been relayed to the agent yet+ except Exception as exc: # noqa: BLE001+ failed = upstream_fault(exc)+ if failed is None:+ resp.close()+ raise+ if failed:+ resp.close()+ self._azure_switch(rec, idx, failed)+ continue+ resp = PrefixedResponse(resp, head)+ break+ AZURE_CURRENT[0] = AZURE_POOL.index(data["model"])+ rec["azure_deployment"] = data["model"]+ return resp++ def _azure_switch(self, rec, idx, reason):+ rec.setdefault("azure_failovers", []).append({"from": AZURE_POOL[idx], "reason": reason, "at": time.time()})+ with LOCK:+ USAGE["azure_failovers"] = USAGE.get("azure_failovers", 0) + 1+ publish()+++class ResponseAudit:+ """Parse SSE boundaries independently of network chunks; count only a successful terminal event."""+ def __init__(self, path, anthropic=False):+ self.path, self.anthropic = path, anthropic+ self.buf = b""+ self.data = []+ self.success = self.failed = self.terminal = False+ self.usage = {}+ self.response_id = None+ self.excerpt = Excerpt()+ self.tools = []+ self.chat_choices = {}+ self.chat_tools = {}+ self.anthropic_tools = {}+ self.anthropic_stop = None++ def has_act(self):+ # Intent is read only from emitted tool arguments, never ordinary assistant text.+ # This is an operational gate, not authentication of which harness made the request.+ return self.success and not self.failed and any(+ ACT_RE.search(json.dumps(tool.get("arguments") or tool.get("input") or tool.get("action")+ or (tool.get("function") or {}).get("arguments") or "",+ ensure_ascii=False)) for tool in self.tools)++ def body(self, obj):+ if not isinstance(obj, dict):+ self.failed = True+ return+ self.response_id = obj.get("id", self.response_id)+ self.usage.update(obj.get("usage") or {})+ self.excerpt.feed_body(obj)+ if "output" in obj:+ self.tools = [it for it in obj["output"] if it.get("type") in ("function_call", "custom_tool_call", "local_shell_call")]+ self.tools += [it for it in obj.get("content", []) if it.get("type") == "tool_use"]+ self.tools += [it for ch in obj.get("choices", []) for it in (ch.get("message") or {}).get("tool_calls", [])]+ self.tools += [{"function": ch["message"]["function_call"]} for ch in obj.get("choices", [])+ if (ch.get("message") or {}).get("function_call")]+ if self.anthropic:+ self.success = obj.get("stop_reason") in ("end_turn", "tool_use", "stop_sequence") and obj.get("type") == "message"+ elif "/chat/completions" in self.path:+ self.success = bool(obj.get("choices")) and all(c.get("finish_reason") in ("stop", "tool_calls", "function_call") for c in obj["choices"])+ else:+ self.success = obj.get("status") == "completed"+ self.failed |= bool(obj.get("error"))+ self.terminal = True++ def event(self, data):+ if data == b"[DONE]":+ self.terminal = True+ self.success |= ("/chat/completions" in self.path and bool(self.chat_choices)+ and all(self.chat_choices.values()))+ self.tools += list(self.chat_tools.values())+ return+ try:+ ev = json.loads(data)+ except ValueError:+ self.failed = True+ return+ if not isinstance(ev, dict):+ self.failed = True+ return+ t = ev.get("type", "")+ self.excerpt.feed_event(ev)+ if t == "message_start":+ message = ev.get("message") or {}+ self.response_id = message.get("id")+ self.usage.update(message.get("usage") or {})+ elif t == "message_delta":+ self.usage.update(ev.get("usage") or {})+ self.anthropic_stop = (ev.get("delta") or {}).get("stop_reason", self.anthropic_stop)+ elif t == "content_block_start":+ cb = ev.get("content_block") or {}+ if cb.get("type") == "tool_use":+ self.anthropic_tools[ev.get("index", 0)] = dict(cb)+ elif t == "content_block_delta":+ tool = self.anthropic_tools.get(ev.get("index", 0))+ delta = ev.get("delta") or {}+ if tool is not None and delta.get("type") == "input_json_delta":+ tool["_json"] = tool.get("_json", "") + delta.get("partial_json", "")+ elif t == "message_stop":+ self.terminal = True+ self.success = self.anthropic_stop in ("end_turn", "tool_use", "stop_sequence")+ for tool in self.anthropic_tools.values():+ if "_json" in tool:+ try:+ tool["input"] = json.loads(tool.pop("_json"))+ except ValueError:+ self.failed = True+ self.tools.append(tool)+ elif t in ("response.completed", "response.done"):+ response = ev.get("response") or {}+ self.body(response)+ elif t in ("error", "response.failed", "response.incomplete") or ev.get("error"):+ self.failed = self.terminal = True+ self.usage.update((ev.get("response") or {}).get("usage") or {})+ elif t == "response.output_item.done":+ it = ev.get("item") or {}+ if it.get("type") in ("function_call", "custom_tool_call", "local_shell_call"):+ self.tools.append(it)+ if ev.get("object", "").startswith("chat.completion"):+ self.response_id = ev.get("id", self.response_id)+ self.usage.update(ev.get("usage") or {})+ for choice in ev.get("choices", []):+ ci = choice.get("index", 0)+ self.chat_choices.setdefault(ci, False)+ reason = choice.get("finish_reason")+ if reason is not None:+ self.chat_choices[ci] = reason in ("stop", "tool_calls", "function_call")+ self.failed |= not self.chat_choices[ci]+ delta = choice.get("delta") or {}+ self.excerpt.add(delta.get("content"))+ calls = delta.get("tool_calls") or []+ if delta.get("function_call"):+ calls = calls + [{"index": 0, "function": delta["function_call"]}]+ for fragment in calls:+ tool = self.chat_tools.setdefault((ci, fragment.get("index", 0)),+ {"type": "function", "function": {"name": "", "arguments": ""}})+ if fragment.get("id"):+ tool["id"] = fragment["id"]+ for field in ("name", "arguments"):+ tool["function"][field] += (fragment.get("function") or {}).get(field, "")+ self.excerpt.add(json.dumps(fragment))++ def feed(self, chunk):+ self.buf += chunk+ while b"\n" in self.buf:+ line, self.buf = self.buf.split(b"\n", 1)+ self.line(line.rstrip(b"\r"))++ def line(self, line):+ if not line:+ if self.data:+ self.event(b"\n".join(self.data))+ self.data = []+ elif line.startswith(b"data:"):+ self.data.append(line[5:].lstrip(b" "))++ def finish(self):+ if self.buf:+ self.line(self.buf.rstrip(b"\r"))+ self.buf = b""+ self.line(b"")++++def main() -> int:+ port = int(sys.argv[1]) if len(sys.argv) > 1 else 18090+ publish()+ srv = ThreadingHTTPServer(("0.0.0.0", port), Handler)+ srv.daemon_threads = True+ sys.stderr.write(f"think_proxy: listening on :{port} -> {UPSTREAM}; usage -> {USAGE_FILE}\n")+ srv.serve_forever()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/__init__.pynew file mode 100644index 0000000000..9a55e841d4--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/__init__.py@@ -0,0 +1,40 @@+"""Renderer plugins (docs/framework_zh.md §3.1): a renderer draws a sport's scene, from its camera definitions, for+one world state. Sports never import a renderer; the core calls the task's observation renderer (task parameter+`renderer`, default DEFAULT) and the viewing tools any renderer for re-renders.++ from renderers import load, Scene, CameraDef+ R = load("mujoco")(Scene.from_file("scene.xml"))+ images = R.render({"qpos": qpos}, [CameraDef("behind", pos, lookat)])+"""+from __future__ import annotations++import importlib++from .base import CameraDef, Renderer, RendererUnavailable, Scene # noqa: F401++DEFAULT = "mujoco"+REGISTRY = { # name -> (module, realtime, needs_gpu, requires)+ "mujoco": ("renderers.mujoco", True, False, "mujoco; MUJOCO_GL=osmesa (CPU) or egl (GPU)"),+ "mujoco-showcase": ("renderers.mujoco_showcase", True, False, "as mujoco"),+ "cycles": ("renderers.cycles", False, True, "Docker, the rcb-showcase-blender image, an NVIDIA GPU (or device=CPU)"),+ "isaac": ("renderers.isaac", False, True, "Docker, the Isaac Sim 4.5 image, an NVIDIA RTX GPU"),+}+++def load(name: str = DEFAULT):+ """The Renderer subclass registered under `name`."""+ if name not in REGISTRY:+ raise KeyError(f"unknown renderer {name!r}; have {sorted(REGISTRY)}")+ return importlib.import_module(REGISTRY[name][0]).RENDERER+++def available() -> dict:+ return {n: {"realtime": rt, "needs_gpu": gpu, "requires": req} for n, (_, rt, gpu, req) in REGISTRY.items()}+++def players_model(sport_dir, match: Scene):+ """For a sport that draws its own images (the renderers' interface for sports): the compiled MjModel of the+ players' presentation scene its presentation.toml declares (`players`, renderer rule 6; the same kinematics as+ `match` checked), or None when it declares none (draw the match model). See renderers/presentation."""+ from .presentation import players_model as _players_model+ return _players_model(sport_dir, match)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/base.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/base.pynew file mode 100644index 0000000000..7cf75e40ba--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/base.py@@ -0,0 +1,156 @@+"""The renderer plugin interface (docs/framework_zh.md §3.1, renderer rules §9): a renderer turns a sport's scene,+camera definitions and one world state into images. It never changes physics or the match state: it draws on its own+copy of the model.++ scene = Scene(engine="mujoco", xml=MJCF text, assets={relative path: bytes}, look=None or a presentation look)+ a presentation scene (renderers/presentation.py, spectators only) also carries `match`, the match scene+ it dresses: same kinematics, extra visual-only geoms (scene_check.same_kinematics)+ cameras = [CameraDef(name, pos, lookat, up, fovy_deg, width, height), ...] (what Match.cameras(seat) returns)+ state = {"qpos": [...], optional "mocap_pos": [...], "mocap_quat": [...]}+ images = Renderer(scene).render(state, cameras) -> one H x W x 3 uint8 array per camera++The camera model is a pinhole that every renderer must reproduce (CameraDef.project): pixel (u, v) from the image's+top-left corner, u to the right, v down, vertical field of view fovy_deg. Only numpy is needed here; engines import+their own libraries inside their backend packages. Never put the renderers/ directory itself on sys.path (its+`mujoco` backend package would shadow the mujoco library); import it as the package `renderers`.+"""+from __future__ import annotations++import math+from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np+++class RendererUnavailable(RuntimeError):+ """The renderer cannot run here; `requirements` says what it needs (GPU, image, library ...)."""++ def __init__(self, name: str, why: str, requirements: str = ""):+ super().__init__(f"renderer {name!r} unavailable: {why}" + (f" (requires: {requirements})" if requirements else ""))+ self.name, self.why, self.requirements = name, why, requirements+++def _unit(v):+ v = np.asarray(v, dtype=float)+ n = np.linalg.norm(v)+ if not np.isfinite(n) or n < 1e-12:+ raise ValueError("degenerate camera direction")+ return v / n+++@dataclass+class CameraDef:+ name: str+ pos: tuple+ lookat: tuple+ up: tuple = (0.0, 0.0, 1.0)+ fovy_deg: float = 45.0+ width: int = 320+ height: int = 240++ def __post_init__(self):+ self.pos = tuple(float(x) for x in self.pos)+ self.lookat = tuple(float(x) for x in self.lookat)+ self.up = tuple(float(x) for x in self.up)+ self.fovy_deg, self.width, self.height = float(self.fovy_deg), int(self.width), int(self.height)+ if len(self.pos) != 3 or len(self.lookat) != 3 or len(self.up) != 3:+ raise ValueError("pos, lookat and up are 3-vectors")+ if not 0 < self.fovy_deg < 180 or self.width <= 0 or self.height <= 0:+ raise ValueError("fovy_deg in (0, 180), positive width and height")+ self.basis() # raises on a degenerate pose++ @staticmethod+ def from_dict(d: dict) -> "CameraDef":+ keys = ("name", "pos", "lookat", "up", "fovy_deg", "width", "height")+ return CameraDef(**{k: d[k] for k in keys if k in d})++ def to_dict(self) -> dict:+ return {"name": self.name, "pos": list(self.pos), "lookat": list(self.lookat), "up": list(self.up),+ "fovy_deg": self.fovy_deg, "width": self.width, "height": self.height}++ def focal_px(self) -> float:+ return (self.height / 2) / math.tan(math.radians(self.fovy_deg) / 2)++ def intrinsics(self) -> dict:+ return {"focal_px": self.focal_px(), "principal_point_px": [self.width / 2, self.height / 2],+ "width": self.width, "height": self.height}++ def basis(self):+ """(right, up, forward) unit vectors in the world frame."""+ fwd = _unit(np.subtract(self.lookat, self.pos))+ right = _unit(np.cross(fwd, self.up))+ up = np.cross(right, fwd)+ return right, up, fwd++ def project(self, point):+ """Pixel (u, v) of a world point (u right, v down, from the top-left corner; continuous coordinates, so the+ centre of pixel column i is u = i + 0.5). None if the point is behind the camera."""+ right, up, fwd = self.basis()+ d = np.subtract(point, self.pos)+ depth = float(d @ fwd)+ if depth <= 1e-9:+ return None+ f = self.focal_px()+ return (self.width / 2 + f * float(d @ right) / depth, self.height / 2 - f * float(d @ up) / depth)++ def spherical(self):+ """(lookat, distance, azimuth_deg, elevation_deg): the free-camera form the showcase exporters use."""+ d = np.subtract(self.lookat, self.pos)+ dist = float(np.linalg.norm(d))+ az = math.degrees(math.atan2(d[1], d[0]))+ el = math.degrees(math.asin(max(-1.0, min(1.0, d[2] / dist))))+ return list(self.lookat), dist, az, el+++@dataclass+class Scene:+ engine: str = "mujoco" # the physics engine whose scene format `xml` is in+ xml: str = "" # MJCF text (engine "mujoco")+ assets: dict = field(default_factory=dict) # {path as referenced by the xml (with meshdir/texturedir): bytes}+ look: dict | None = None # optional presentation appearance (showcase renderers only)+ match: "Scene | None" = None # set on a presentation scene only: the match scene it dresses+ credits: tuple = () # presentation scene: what was added, with its source and licence+ players: bool = False # a presentation scene the sport declares for its players' images too++ @property+ def is_presentation(self) -> bool:+ """A presentation scene (renderers/presentation): drawn for the players' images only when `players` is set+ (the sport declares it, renderer rule 6), else for spectators only."""+ return self.match is not None++ @staticmethod+ def from_file(path, look=None) -> "Scene":+ """A scene file plus every other file below its directory as an asset (paths relative to that directory)."""+ p = Path(path)+ assets = {str(f.relative_to(p.parent)): f.read_bytes() for f in sorted(p.parent.rglob("*"))+ if f.is_file() and f != p and "__pycache__" not in f.parts}+ return Scene(engine="mujoco", xml=p.read_text(), assets=assets, look=look)+++class Renderer(ABC):+ name: str = ""+ realtime: bool = True # fast enough for player images (still subject to the task's frame budget)+ needs_gpu: bool = False+ label: str | None = None # the tag a re-rendered frame carries ("re-rendered: <engine>"); None = default++ def __init__(self, scene: Scene, **opts):+ self.scene, self.opts = scene, opts++ @abstractmethod+ def render(self, state: dict, cameras: list) -> list:+ """One H x W x 3 uint8 image per camera (CameraDef or its dict form), for the given world state."""++ def close(self):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()+++def as_cameras(cameras) -> list:+ return [c if isinstance(c, CameraDef) else CameraDef.from_dict(c) for c in cameras]diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/budget.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/budget.pynew file mode 100644index 0000000000..a84e245e2e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/budget.py@@ -0,0 +1,31 @@+"""Frame-time budget of a player-image renderer (renderer rule 3): an observation (all of a seat's cameras) must be+drawn within the task's `frame_budget_ms`. tools/check measures it for the task's `renderer` parameter."""+from __future__ import annotations++import time++from .base import as_cameras+++def frame_ms(renderer_cls, scene, state, cameras, n: int = 5, warmup: int = 1, **opts) -> float:+ """Median wall milliseconds per observation (every camera once), after `warmup` untimed observations."""+ cams = as_cameras(cameras)+ r = renderer_cls(scene, **opts)+ try:+ for _ in range(warmup):+ r.render(state, cams)+ times = []+ for _ in range(max(1, n)):+ t = time.perf_counter()+ r.render(state, cams)+ times.append((time.perf_counter() - t) * 1000.0)+ finally:+ r.close()+ times.sort()+ return times[len(times) // 2]+++def check_budget(renderer_cls, scene, state, cameras, budget_ms: float, n: int = 5, **opts):+ """(ok, ms): ok when the renderer is real time and its median observation time is within budget_ms."""+ ms = frame_ms(renderer_cls, scene, state, cameras, n=n, **opts)+ return bool(getattr(renderer_cls, "realtime", False) and ms <= float(budget_ms)), msdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/cycles/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/cycles/__init__.pynew file mode 100644index 0000000000..d38cf96c01--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/cycles/__init__.py@@ -0,0 +1,38 @@+"""Blender 4.2 Cycles path tracing (offline, for re-rendering): the export of renderers/export.py traced by+scripts/olympiad/showcase/blender/cycles_render.py in the rcb-showcase-blender image. device = OPTIX (default) or+CUDA (GPU), or CPU (slow, no GPU needed)."""+from __future__ import annotations++import os++from ..export import SHOWCASE_TOOLS+from ..pathtrace import PathTracer++IMAGE = os.environ.get("SHOWCASE_BLENDER_IMAGE", "rcb-showcase-blender:4.2.23")+++class CyclesRenderer(PathTracer):+ name = "cycles"+ title = "Blender Cycles"+ image = IMAGE+ requirements = (f"Docker, the image {IMAGE} (docker build -t {IMAGE} scripts/olympiad/showcase/blender; 1.8 GB) "+ "and an NVIDIA GPU with the NVIDIA Container Toolkit (device=CPU works without one, slowly); "+ "mujoco in the calling process for the scene export")++ def __init__(self, scene, device: str = "OPTIX", **opts):+ self.device = device+ super().__init__(scene, **opts)+ if device == "CPU":+ self.needs_gpu = False++ def gpu_optional(self):+ return self.device == "CPU"++ def trace(self, work, size):+ self.docker(["-v", f"{work}:/s", "-v", f"{SHOWCASE_TOOLS}:/w:ro", self.image, "blender", "-b",+ "--factory-startup", "-P", "/w/blender/cycles_render.py", "--", "/s/export", "/s/out",+ "--samples", str(self.samples), "--size", size, "--device", self.device],+ gpu=self.device != "CPU")+++RENDERER = CyclesRendererdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/export.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/export.pynew file mode 100644index 0000000000..34e42323f6--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/export.py@@ -0,0 +1,104 @@+"""Scene export for the path-traced renderers (cycles, isaac): the format of scripts/olympiad/showcase/blender/+export_scene.py (scene.json, meshes.npz, poses.npz), written from a renderer's own MuJoCo model, a list of world+states and one camera per state. Geometry = the model's own meshes and tessellated primitives; materials and lights+= the showcase model's; the camera of each frame = its CameraDef (as lookat / distance / azimuth / elevation; the+path tracers keep the world z axis up, so a camera's `up` must be +z)."""+from __future__ import annotations++import json+import os+import sys++import numpy as np++from .base import CameraDef+from .scene_check import DEFAULT_RGBA, effective_rgba++SHOWCASE_TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts", "olympiad",+ "showcase")+++def _geom_mesh():+ sys.path[:0] = [p for p in (SHOWCASE_TOOLS, os.path.join(SHOWCASE_TOOLS, "blender")) if p not in sys.path]+ from export_scene import geom_mesh+ return geom_mesh+++def export(m, frames: list, outdir: str, title: str = "renderer") -> dict:+ """frames = [(state, CameraDef)], all cameras with the same size and field of view. Returns the scene summary."""+ import mujoco as mj+ from .mujoco import MujocoRenderer # noqa: F401 (same state handling)+ cams = [c for _, c in frames]+ if len({(c.width, c.height, c.fovy_deg) for c in cams}) != 1:+ raise ValueError("one export holds cameras of one size and field of view")+ for c in cams:+ if abs(abs(float(np.dot(c.up, (0, 0, 1)))) - float(np.linalg.norm(c.up))) > 1e-9 or c.up[2] <= 0:+ raise ValueError(f"camera {c.name}: the path tracers support up = +z only")+ geom_mesh = _geom_mesh()+ os.makedirs(outdir, exist_ok=True)+ d = mj.MjData(m)+ geoms, meshes = [], {}+ for g in range(m.ngeom):+ if m.geom_group[g] not in (0, 1, 2):+ continue+ rgba = np.asarray(effective_rgba(m, g), float)+ if rgba[3] <= 0.01:+ continue+ gm = geom_mesh(m, g)+ if gm is None:+ continue+ v, f, shade = gm+ meshes[f"v{g}"], meshes[f"f{g}"] = v.astype(np.float32), f.astype(np.int32)+ mid = int(m.geom_matid[g])+ mat = dict(specular=0.5, shininess=0.5, reflectance=0.0, emission=0.0, tex=None, texrepeat=[1, 1])+ if mid >= 0:+ mat.update(specular=float(m.mat_specular[mid]), shininess=float(m.mat_shininess[mid]),+ emission=float(m.mat_emission[mid]), reflectance=float(m.mat_reflectance[mid]),+ texrepeat=[float(x) for x in m.mat_texrepeat[mid]])+ tid = int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB])+ if tid >= 0 and m.tex_type[tid] == mj.mjtTexture.mjTEXTURE_2D:+ from PIL import Image+ h, w, c = m.tex_height[tid], m.tex_width[tid], m.tex_nchannel[tid]+ px = m.tex_data[m.tex_adr[tid]:m.tex_adr[tid] + h * w * c].reshape(h, w, c)[..., :3]+ name = f"tex{tid}.png"+ if not os.path.exists(os.path.join(outdir, name)):+ Image.fromarray(px).save(os.path.join(outdir, name))+ mat["tex"] = name+ rgba = m.mat_rgba[mid].astype(float) if np.allclose(m.geom_rgba[g], DEFAULT_RGBA) else rgba+ geoms.append(dict(id=g, name=m.geom(g).name or f"geom{g}", type=int(m.geom_type[g]),+ size=[float(x) for x in m.geom_size[g]], rgba=[float(x) for x in rgba], shade=shade,+ static=bool(m.body_weldid[m.geom_bodyid[g]] == 0), mat=mat))+ np.savez_compressed(os.path.join(outdir, "meshes.npz"), **meshes)+ ids = [gg["id"] for gg in geoms]+ pos = np.zeros((len(frames), len(ids), 3), np.float32)+ rot = np.zeros((len(frames), len(ids), 9), np.float32)+ for j, (state, _) in enumerate(frames):+ d.qpos[:] = np.asarray(state["qpos"], float)+ if m.nmocap and "mocap_pos" in state:+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(-1, 3)+ if m.nmocap and "mocap_quat" in state:+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(-1, 4)+ mj.mj_kinematics(m, d)+ mj.mj_comPos(m, d)+ mj.mj_camlight(m, d)+ pos[j], rot[j] = d.geom_xpos[ids], d.geom_xmat[ids]+ np.savez_compressed(os.path.join(outdir, "poses.npz"), pos=pos, rot=rot, step=np.arange(len(frames)))+ lights = [dict(name=m.light(i).name or f"light{i}", type=int(m.light_type[i]) if hasattr(m, "light_type") else 0,+ pos=[float(x) for x in d.light_xpos[i]], dir=[float(x) for x in d.light_xdir[i]],+ diffuse=[float(x) for x in m.light_diffuse[i]], cutoff=float(m.light_cutoff[i]),+ exponent=float(m.light_exponent[i]), castshadow=bool(m.light_castshadow[i]),+ bulbradius=float(m.light_bulbradius[i])) for i in range(m.nlight)]+ sky = None+ for t in range(m.ntex):+ if m.tex_type[t] == mj.mjtTexture.mjTEXTURE_SKYBOX:+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, w, c)+ sky = dict(top=(px[:h // 6].reshape(-1, c)[:, :3].mean(0) / 255).tolist(),+ horizon=(px[h * 5 // 6 - h // 12: h * 5 // 6].reshape(-1, c)[:, :3].mean(0) / 255).tolist())+ scene = dict(sport=title, decor=None, fps=1.0, fovy=float(cams[0].fovy_deg), geoms=geoms, lights=lights,+ headlight=dict(ambient=[float(x) for x in m.vis.headlight.ambient],+ diffuse=[float(x) for x in m.vis.headlight.diffuse]),+ sky=sky, cameras=[CameraDef.spherical(c) for c in cams], steps=list(range(len(frames))))+ with open(os.path.join(outdir, "scene.json"), "w") as f:+ json.dump(scene, f)+ return dict(geoms=len(geoms), frames=len(frames), lights=len(lights))diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/isaac/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/isaac/__init__.pynew file mode 100644index 0000000000..1b1d6d9402--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/isaac/__init__.py@@ -0,0 +1,49 @@+"""NVIDIA Isaac Sim 4.5 RTX path tracing (offline, for re-rendering): the export of renderers/export.py rendered by+scripts/olympiad/showcase/isaac/isaac_render.py in nvcr.io/nvidia/isaac-sim:4.5.0 (as root, as rerender.py runs it;+shader caches in SHOWCASE_ISAAC_CACHE, the first start compiles shaders for ~10 min)."""+from __future__ import annotations++import os+import subprocess++from ..export import SHOWCASE_TOOLS+from ..pathtrace import PathTracer++IMAGE = os.environ.get("SHOWCASE_ISAAC_IMAGE", "nvcr.io/nvidia/isaac-sim:4.5.0")+CACHE = os.environ.get("SHOWCASE_ISAAC_CACHE", os.path.expanduser("~/.cache/rcb-showcase-isaac"))+CACHES = (("kit", "/isaac-sim/kit/cache"), ("ov", "/root/.cache/ov"), ("glcache", "/root/.cache/nvidia/GLCache"),+ ("computecache", "/root/.nv/ComputeCache"), ("logs", "/root/.nvidia-omniverse/logs"),+ ("data", "/root/.local/share/ov/data"))+++class IsaacRenderer(PathTracer):+ name = "isaac"+ title = "Isaac Sim RTX"+ image = IMAGE+ requirements = (f"Docker, an NVIDIA RTX GPU (driver >= 535.129) with the NVIDIA Container Toolkit, the image "+ f"{IMAGE} (15 GB), ~20 GB free disk for caches, the NVIDIA Omniverse EULA (ACCEPT_EULA=Y); "+ "mujoco in the calling process for the scene export")++ def __init__(self, scene, mode: str = "PathTracing", **opts):+ self.mode = mode+ super().__init__(scene, **opts)++ def trace(self, work, size):+ args = ["-e", "ACCEPT_EULA=Y", "-e", "PRIVACY_CONSENT=Y", "-e", "OMNI_KIT_ACCEPT_EULA=YES"]+ for sub, dst in CACHES:+ os.makedirs(os.path.join(CACHE, sub), exist_ok=True)+ args += ["-v", f"{os.path.join(CACHE, sub)}:{dst}:rw"]+ if os.path.exists("/usr/share/nvidia/nvoptix.bin"):+ args += ["-v", "/usr/share/nvidia/nvoptix.bin:/usr/share/nvidia/nvoptix.bin:ro"]+ args += ["-v", f"{work}:/s", "-v", f"{SHOWCASE_TOOLS}:/w:ro", "--entrypoint", "/isaac-sim/python.sh", self.image,+ "/w/isaac/isaac_render.py", "/s/export", "/s/out", "--spp", str(self.samples), "--size", size,+ "--mode", self.mode]+ try:+ self.docker(args, gpu=True, root=True)+ finally: # Isaac writes as root+ subprocess.run(["docker", "run", "--rm", "--name", f"ro-renderer-isaac-chown-{os.getpid()}", "-v",+ f"{work}:/s", "--entrypoint", "chown", self.image, "-R",+ f"{os.getuid()}:{os.getgid()}", "/s"], capture_output=True)+++RENDERER = IsaacRendererdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/label.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/label.pynew file mode 100644index 0000000000..8dda2059eb--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/label.py@@ -0,0 +1,40 @@+"""The tag on every re-rendered frame (renderer rule 5): which renderer drew it, bottom right, and whether the scene was+a presentation scene (renderer rule 6)."""+from __future__ import annotations++import numpy as np+++PRESENTATION = "presentation meshes, spectators only"+++def label_text(engine_title: str, decor: bool = False, presentation: bool = False) -> str:+ return (f"re-rendered: {engine_title}" + (" | surroundings for presentation only" if decor else "")+ + (f" | {PRESENTATION}" if presentation else ""))+++def frame_label(renderer, scene) -> str | None:+ """The tag of a spectator frame drawn by `renderer` (a Renderer instance or class) from `scene`: the renderer's+ own label, with the presentation-scene note when the scene is one; None = the competition picture (the default+ renderer on the match scene, or on the presentation scene a sport declares for its players' images), which+ carries no tag."""+ title = getattr(renderer, "title", None) or getattr(renderer, "name", "renderer")+ if getattr(scene, "match", None) is not None and not getattr(scene, "players", False):+ return label_text(title, presentation=True)+ return getattr(renderer, "label", None)+++def stamp(img: np.ndarray, text: str) -> np.ndarray:+ from PIL import Image, ImageDraw, ImageFont+ im = Image.fromarray(np.ascontiguousarray(img))+ d = ImageDraw.Draw(im, "RGBA")+ s = max(10, im.size[1] // 40)+ try:+ f = ImageFont.truetype("DejaVuSans.ttf", s)+ except OSError:+ f = ImageFont.load_default()+ w = d.textlength(text, font=f)+ W, H = im.size+ d.rectangle([W - w - 16, H - s - 14, W - 4, H - 4], fill=(0, 0, 0, 150))+ d.text((W - w - 10, H - s - 10), text, font=f, fill=(255, 255, 255, 235))+ return np.asarray(im)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/mujoco/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/mujoco/__init__.pynew file mode 100644index 0000000000..1f52d6a69d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/mujoco/__init__.py@@ -0,0 +1,144 @@+"""The default renderer: MuJoCo's own rasterizer (CPU with MUJOCO_GL=osmesa, GPU with egl), real time.++The scene is compiled once from its MJCF text with spare world-body cameras added; each CameraDef is drawn by+setting one spare camera's pose and vertical field of view exactly (cam_pos / cam_quat / cam_fovy), so the picture+follows CameraDef.project to the pixel. The renderer keeps its own MjModel / MjData: the match's world is never+touched. A presentation scene (Scene.match set; spectators only) is drawn only when its kinematics equal the match+scene's (scene_check.same_kinematics); every renderer built on this one inherits the check."""+from __future__ import annotations++import numpy as np++from ..base import CameraDef, Renderer, RendererUnavailable, Scene, as_cameras++SPARE = "_ro_cam"+++def camera_quat(cam: CameraDef):+ """MuJoCo camera frame: x = image right, y = image up, looking along -z."""+ import mujoco as mj+ right, up, fwd = cam.basis()+ R = np.column_stack([right, up, -fwd])+ q = np.zeros(4)+ mj.mju_mat2Quat(q, R.reshape(-1))+ return q+++def compile_spec(spec, n_cams: int, size):+ """Add n spare cameras and make the off-screen buffer at least `size` (w, h); returns the compiled model."""+ g = spec.visual.global_+ g.offwidth, g.offheight = max(int(g.offwidth), int(size[0])), max(int(g.offheight), int(size[1]))+ for i in range(n_cams):+ spec.worldbody.add_camera(name=f"{SPARE}{i}", pos=[0, 0, 0], quat=[1, 0, 0, 0], fovy=45)+ return spec.compile()+++def load_spec(scene: Scene):+ import mujoco as mj+ if scene.engine != "mujoco":+ raise RendererUnavailable("mujoco", f"scene engine {scene.engine!r} is not MJCF")+ return mj.MjSpec.from_string(scene.xml, assets=dict(scene.assets or {}))+++class MujocoRenderer(Renderer):+ name = "mujoco"+ title = "MuJoCo"+ realtime = True+ needs_gpu = False+ label = None # the competition picture: no tag++ def __init__(self, scene: Scene, n_cams: int = 8, size=(640, 480), **opts):+ super().__init__(scene, **opts)+ try:+ import mujoco # noqa: F401+ except ImportError as exc: # pragma: no cover - the sim images have it+ raise RendererUnavailable(self.name, "the mujoco Python package is missing", "mujoco") from exc+ self._n, self._size = int(n_cams), tuple(size)+ self._build()++ # ---------------------------------------------------------------- model+ def make_spec(self):+ """The MjSpec to draw (subclasses change only visual properties)."""+ return load_spec(self.scene)++ def _build(self):+ import mujoco as mj+ self.close()+ self.m = compile_spec(self.make_spec(), self._n, self._size)+ if self.scene.match is not None: # a presentation scene: same kinematics as the match scene+ from ..scene_check import same_kinematics+ bad = same_kinematics(compile_spec(load_spec(self.scene.match), self._n, self._size), self.m)+ if bad:+ raise RuntimeError(f"{self.name}: the presentation scene's kinematics differ from the match scene: "+ f"{bad[:8]}")+ self.d = mj.MjData(self.m)+ self.cam_ids = [self.m.camera(f"{SPARE}{i}").id for i in range(self._n)]+ self._r = {}++ def _renderer(self, w, h):+ import mujoco as mj+ if (w, h) not in self._r:+ self._r[w, h] = mj.Renderer(self.m, height=h, width=w)+ return self._r[w, h]++ def set_state(self, state: dict):+ import mujoco as mj+ m, d = self.m, self.d+ q = np.asarray(state.get("qpos", d.qpos), dtype=float)+ if q.shape != (m.nq,):+ raise ValueError(f"state qpos has {q.size} values, the scene has nq={m.nq}")+ d.qpos[:] = q+ if m.nmocap:+ if "mocap_pos" in state:+ d.mocap_pos[:] = np.asarray(state["mocap_pos"], float).reshape(m.nmocap, 3)+ if "mocap_quat" in state:+ d.mocap_quat[:] = np.asarray(state["mocap_quat"], float).reshape(m.nmocap, 4)+ mj.mj_kinematics(m, d)+ mj.mj_comPos(m, d)+ mj.mj_camlight(m, d)++ # ---------------------------------------------------------------- drawing+ def render(self, state: dict, cameras: list) -> list:+ import mujoco as mj+ cams = as_cameras(cameras)+ w_max, h_max = max([c.width for c in cams] + [1]), max([c.height for c in cams] + [1])+ if len(cams) > self._n or w_max > self.m.vis.global_.offwidth or h_max > self.m.vis.global_.offheight:+ self._n = max(self._n, len(cams))+ self._size = (max(self._size[0], w_max), max(self._size[1], h_max))+ self._build()+ self.set_state(state)+ for cam, cid in zip(cams, self.cam_ids):+ self.m.cam_pos[cid] = cam.pos+ self.m.cam_quat[cid] = camera_quat(cam)+ self.m.cam_fovy[cid] = cam.fovy_deg+ mj.mj_camlight(self.m, self.d) # camera world poses from the new cam_pos / cam_quat+ self._clip(cams)+ out = []+ for cam, cid in zip(cams, self.cam_ids):+ r = self._renderer(cam.width, cam.height)+ r.update_scene(self.d, camera=cid)+ out.append(self.post(np.array(r.render(), dtype=np.uint8, copy=True), cam))+ return out++ def _clip(self, cams):+ """MuJoCo clips at zfar * stat.extent: keep every geom of the current state inside every camera's far plane+ (a small scene seen from afar, or a body far from the scene centre, would otherwise vanish). Visualization+ only, on our own model copy."""+ m, d = self.m, self.d+ ext = max(float(m.stat.extent), 1e-6)+ pts = np.asarray(d.geom_xpos) if m.ngeom else np.zeros((1, 3))+ rb = float(np.max(m.geom_rbound)) if m.ngeom else 0.0+ reach = max(float(np.max(np.linalg.norm(pts - np.asarray(c.pos), axis=1))) for c in cams) + rb+ if m.vis.map.zfar * ext < 1.05 * reach:+ m.vis.map.zfar = 1.05 * reach / ext++ def post(self, img, cam):+ return img++ def close(self):+ for r in getattr(self, "_r", {}).values():+ r.close()+ self._r = {}+++RENDERER = MujocoRendererdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/mujoco_showcase/__init__.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/mujoco_showcase/__init__.pynew file mode 100644index 0000000000..79543dd381--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/mujoco_showcase/__init__.py@@ -0,0 +1,121 @@+"""MuJoCo showcase: the same rasterizer with better lights, materials and anti-aliasing (real time; CPU with osmesa,+GPU optional). The scene is the default renderer's scene with visual changes only, checked by scene_check.same_scene+before the first frame (the renderer refuses to draw otherwise).++Look (Scene.look): None or {} = the generic showcase look below (shadow-casting key light, soft fill, satin materials+that keep every geom's colour, MSAA); {"preset": <name>} = a sport's look from scripts/olympiad/showcase/looks.py+(SHOWCASE[name], e.g. "tabletennis"), available when this checkout's showcase tools are present.+Options: ssaa (supersampling factor, default 1; 2 for re-renders), stamp (tag every frame with `label`, default False:+the tag is for re-rendered outputs, not for player images).++A presentation scene (Scene.match set, renderers/presentation.py): its added visual geoms keep their own materials+under any look, the kinematics check of the default renderer applies, and `label` says it is a presentation scene."""+from __future__ import annotations++import os+import sys++import numpy as np++from ..base import RendererUnavailable, Scene+from ..label import label_text, stamp+from ..mujoco import MujocoRenderer, compile_spec, load_spec+from ..scene_check import DEFAULT_RGBA, VISUAL_PREFIX, same_scene++SHOWCASE_TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),+ "scripts", "olympiad", "showcase")+++def _material(spec, name, **kw):+ mt = spec.add_material(name=name)+ for k, v in kw.items():+ setattr(mt, k, v)+ return mt+++def generic_look(spec, size):+ import mujoco as mj+ v = spec.visual+ v.global_.offwidth, v.global_.offheight = max(v.global_.offwidth, size[0]), max(v.global_.offheight, size[1])+ v.quality.offsamples = 8+ v.quality.shadowsize = 4096+ v.headlight.ambient = [0.18, 0.18, 0.2]+ v.headlight.diffuse = [0.25, 0.25, 0.25]+ v.headlight.specular = [0.1, 0.1, 0.1]+ for li in spec.lights:+ li.castshadow = True+ key = spec.worldbody.add_light(name="_showcase_key", pos=[4, -4, 8], dir=[-0.45, 0.45, -0.77],+ diffuse=[0.55, 0.53, 0.5], specular=[0.3, 0.3, 0.3], castshadow=True)+ fill = spec.worldbody.add_light(name="_showcase_fill", pos=[-4, 4, 6], dir=[0.5, -0.5, -0.7],+ diffuse=[0.22, 0.24, 0.28], specular=[0, 0, 0], castshadow=False)+ for li in (key, fill):+ if hasattr(li, "type"): # MuJoCo >= 3.3: light type enum+ li.type = mj.mjtLightType.mjLIGHT_DIRECTIONAL+ else: # pragma: no cover+ li.directional = True+ _material(spec, "_showcase_satin", specular=0.45, shininess=0.55, reflectance=0.0)+ _material(spec, "_showcase_satin_default", specular=0.45, shininess=0.55, reflectance=0.0, rgba=list(DEFAULT_RGBA))+ for g in spec.geoms:+ if g.material:+ continue # textured or already styled: keep it+ g.material = "_showcase_satin" if tuple(np.round(g.rgba, 6)) != DEFAULT_RGBA else "_showcase_satin_default"+++def preset_look(name):+ if not os.path.isdir(SHOWCASE_TOOLS):+ raise RendererUnavailable("mujoco-showcase", f"look preset {name!r} needs scripts/olympiad/showcase/looks.py")+ if SHOWCASE_TOOLS not in sys.path:+ sys.path.insert(0, SHOWCASE_TOOLS)+ import looks+ if name not in looks.SHOWCASE:+ raise ValueError(f"unknown showcase look {name!r}; have {sorted(looks.SHOWCASE)}")+ return looks.SHOWCASE[name]+++class ShowcaseRenderer(MujocoRenderer):+ name = "mujoco-showcase"+ title = "MuJoCo showcase"+ realtime = True+ needs_gpu = False+ label = label_text(title)++ def __init__(self, scene: Scene, ssaa: int = 1, stamp: bool = False, **opts):+ self.ssaa, self.stamp = max(1, int(ssaa)), bool(stamp)+ self.label = label_text(self.title, presentation=scene.match is not None and not scene.players)+ super().__init__(scene, **opts)++ def make_spec(self):+ spec = load_spec(self.scene)+ size = (self._size[0] * self.ssaa, self._size[1] * self.ssaa)+ look = self.scene.look or {}+ added = {g.name: g.material for g in spec.geoms if (g.name or "").startswith(VISUAL_PREFIX)}+ (preset_look(look["preset"]) if look.get("preset") else generic_look)(spec, size)+ for g in spec.geoms: # a presentation scene's own materials win over the look+ if g.name in added:+ g.material = added[g.name]+ return spec++ def _build(self):+ self._size = (max(self._size[0], 1), max(self._size[1], 1))+ super()._build()+ ref = compile_spec(load_spec(self.scene), self._n, self._size) # what the default renderer draws+ bad = same_scene(ref, self.m)+ if bad:+ raise RuntimeError(f"{self.name}: not the same scene as the default renderer: {bad[:8]}")+ self.scene_diffs = bad++ def render(self, state, cameras):+ from ..base import as_cameras+ cams = as_cameras(cameras)+ s = self.ssaa+ big = [type(c)(c.name, c.pos, c.lookat, c.up, c.fovy_deg, c.width * s, c.height * s) for c in cams]+ imgs = super().render(state, big)+ out = []+ for img, c in zip(imgs, cams):+ if s > 1: # box filter: same projection, anti-aliased+ img = img.reshape(c.height, s, c.width, s, 3).mean(axis=(1, 3)).round().astype(np.uint8)+ out.append(stamp(img, self.label) if self.stamp else img)+ return out+++RENDERER = ShowcaseRendererdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/pathtrace.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/pathtrace.pynew file mode 100644index 0000000000..1e1847773d--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/pathtrace.py@@ -0,0 +1,98 @@+"""Shared part of the offline path-traced renderers (cycles, isaac): preflight (Docker, image, GPU), the showcase+model with its same-scene check, export (export.py), one container run per camera group, PNG read-back and the+re-render tag on every frame. These renderers are for re-rendering recorded matches (realtime = False); they run on+a host with Docker and an NVIDIA GPU, and need mujoco in the calling process for the export."""+from __future__ import annotations++import glob+import os+import shutil+import subprocess+import tempfile++import numpy as np++from .base import Renderer, RendererUnavailable, Scene, as_cameras+from .export import SHOWCASE_TOOLS, export+from .label import label_text, stamp+++def image_present(image: str) -> bool:+ return subprocess.run(["docker", "image", "inspect", image], capture_output=True).returncode == 0+++def gpu_present(gpu) -> bool:+ if gpu is None or shutil.which("nvidia-smi") is None:+ return False+ r = subprocess.run(["nvidia-smi", "-i", str(gpu), "--query-gpu=name", "--format=csv,noheader"],+ capture_output=True, text=True)+ return r.returncode == 0 and bool(r.stdout.strip())+++class PathTracer(Renderer):+ realtime = False+ needs_gpu = True+ image = ""+ requirements = ""+ title = ""++ def __init__(self, scene: Scene, gpu="0", samples: int = 64, stamp: bool = True, **opts):+ super().__init__(scene, **opts)+ self.gpu = None if gpu in (None, "none") else str(gpu)+ self.samples, self.stamp = int(samples), bool(stamp)+ self.label = label_text(self.title, presentation=scene.match is not None and not scene.players)+ self.preflight()+ from .mujoco_showcase import ShowcaseRenderer+ self._model = ShowcaseRenderer(scene, n_cams=1).m # raises unless it is the same scene++ def needs(self):+ return [] if self.gpu_optional() else [("gpu", gpu_present(self.gpu), "an NVIDIA GPU (gpu=<index>)")]++ def gpu_optional(self) -> bool:+ return False++ def preflight(self):+ if os.environ.get("RO_RENDERER_OFFLINE") == "1":+ raise RendererUnavailable(self.name, "disabled on this host (RO_RENDERER_OFFLINE=1)", self.requirements)+ if shutil.which("docker") is None or subprocess.run(["docker", "version"], capture_output=True).returncode:+ raise RendererUnavailable(self.name, "Docker is not available here", self.requirements)+ if not image_present(self.image):+ raise RendererUnavailable(self.name, f"missing image {self.image}", self.requirements)+ for what, ok, text in self.needs():+ if not ok:+ raise RendererUnavailable(self.name, f"no {text}", self.requirements)+ if not os.path.isdir(SHOWCASE_TOOLS):+ raise RendererUnavailable(self.name, "scripts/olympiad/showcase is missing", self.requirements)++ def render(self, state, cameras):+ cams = as_cameras(cameras)+ out = [None] * len(cams)+ groups = {}+ for i, c in enumerate(cams):+ groups.setdefault((c.width, c.height, c.fovy_deg), []).append(i)+ for (w, h, _), idx in groups.items():+ work = tempfile.mkdtemp(prefix=f"ro-{self.name}-")+ try:+ export(self._model, [(state, cams[i]) for i in idx], os.path.join(work, "export"), self.name)+ self.trace(work, f"{w}x{h}")+ files = sorted(glob.glob(os.path.join(work, "out", "frame_*.png")))+ if len(files) != len(idx):+ raise RuntimeError(f"{self.name}: {len(files)} frames for {len(idx)} cameras")+ from PIL import Image+ for i, f in zip(idx, files):+ img = np.asarray(Image.open(f).convert("RGB"))+ out[i] = stamp(img, self.label) if self.stamp else img+ finally:+ shutil.rmtree(work, ignore_errors=True)+ return out++ def trace(self, work: str, size: str):+ raise NotImplementedError++ def docker(self, args, gpu=True, root=False):+ c = ["docker", "run", "--rm", "--name", f"ro-renderer-{self.name}-{os.getpid()}", "--network", "none"]+ if not root:+ c += ["--user", f"{os.getuid()}:{os.getgid()}", "-e", "HOME=/tmp"]+ if gpu and self.gpu is not None:+ c += ["--gpus", f"device={self.gpu}", "-e", "NVIDIA_DRIVER_CAPABILITIES=all"]+ subprocess.run(c + args, check=True, capture_output=True)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/scene_check.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/scene_check.pynew file mode 100644index 0000000000..5713371f35--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/renderers/scene_check.py@@ -0,0 +1,164 @@+"""Same scene (renderer rule 2): a non-default renderer draws the default renderer's scene. The geometry, kinematics,+cameras and the colour a viewer sees of every untextured geom must be identical; a re-textured surface keeps its mean+colour within TEXTURE_TOL. Only lights, materials (specular, shininess, reflectance, textures with the same mean+colour) and image quality may differ. The same rule as scripts/olympiad/showcase/looks.same_scene, without the+sport-specific decor exception (decor is presentation-only and never part of a renderer's player picture).++Same kinematics (renderer rule 6): a presentation scene (renderers/presentation.py, spectators only) may differ from+the match scene in appearance and by added visual-only geoms, never in bodies, joints, frames, inertias or cameras;+same_kinematics() checks it before a renderer draws one, pose_diff() compares body poses over recorded states."""+from __future__ import annotations++import numpy as np++SAME = ("nq", "nv", "nbody", "njnt", "ngeom", "nmesh", "ncam", "nmocap",+ "body_parentid", "body_pos", "body_quat", "body_mass", "jnt_type", "jnt_qposadr", "jnt_pos", "jnt_axis",+ "geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_group", "geom_dataid",+ "mesh_vertnum", "mesh_vert", "mesh_face",+ "cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")+DEFAULT_RGBA = (0.5, 0.5, 0.5, 1.0)+TEXTURE_TOL = 0.02+MESH = 7 # mjtGeom.mjGEOM_MESH+++def effective_rgba(m, g):+ rgba = m.geom_rgba[g]+ if m.geom_matid[g] >= 0 and np.allclose(rgba, DEFAULT_RGBA):+ return m.mat_rgba[m.geom_matid[g]]+ return rgba+++def _texid(m, g):+ import mujoco as mj+ mid = m.geom_matid[g]+ return int(m.mat_texid[mid, mj.mjtTextureRole.mjTEXROLE_RGB]) if mid >= 0 else -1+++def _mean_colour(m, g):+ """Mean drawn colour of a geom (texture mean x material/geom colour), 0..1 RGB."""+ rgba = np.asarray(effective_rgba(m, g)[:3], float)+ t = _texid(m, g)+ if t < 0:+ return rgba+ h, w, c = m.tex_height[t], m.tex_width[t], m.tex_nchannel[t]+ px = m.tex_data[m.tex_adr[t]:m.tex_adr[t] + h * w * c].reshape(-1, c)[:, :3]+ return rgba * (px.mean(0) / 255.0)+++SPARE = "_ro_cam" # the renderers' own spare cameras (renderers/mujoco), posed per frame: not scene cameras+++def _scene_cams(m):+ return [i for i in range(m.ncam) if not (m.camera(i).name or "").startswith(SPARE)]+++def same_scene(m0, m1) -> list:+ """Differences between the default model m0 and the renderer's model m1 (empty list = the same scene)."""+ bad = []+ c0, c1 = _scene_cams(m0), _scene_cams(m1)+ for name in SAME:+ a, b = np.asarray(getattr(m0, name)), np.asarray(getattr(m1, name))+ if name.startswith("cam_"):+ a, b = a[c0], b[c1]+ elif name == "ncam":+ a, b = np.asarray(len(c0)), np.asarray(len(c1))+ if np.shape(a) != np.shape(b) or not np.array_equal(a, b):+ bad.append(name)+ if bad:+ return bad+ if m0.vis.global_.fovy != m1.vis.global_.fovy:+ bad.append("vis.global.fovy")+ for g in range(m0.ngeom):+ t0, t1 = _texid(m0, g) >= 0, _texid(m1, g) >= 0+ if not t0 and not t1:+ if not np.allclose(effective_rgba(m0, g), effective_rgba(m1, g)):+ bad.append(f"colour of geom {m0.geom(g).name or g}")+ elif float(np.abs(_mean_colour(m0, g) - _mean_colour(m1, g)).max()) > TEXTURE_TOL:+ bad.append(f"mean colour of textured geom {m0.geom(g).name or g}")+ return bad+++# ------------------------------------------------------------------------------------- presentation scenes (spectators)+VISUAL_PREFIX = "_vis:" # the name prefix of a presentation scene's added geoms (renderers/presentation.py)+KINEMATICS = ("nq", "nv", "nu", "nbody", "njnt", "nmocap", "nsite", "qpos0",+ "body_parentid", "body_rootid", "body_weldid", "body_mocapid", "body_jntnum", "body_jntadr",+ "body_dofnum", "body_dofadr", "body_pos", "body_quat", "body_ipos", "body_iquat", "body_mass",+ "body_inertia", "jnt_type", "jnt_bodyid", "jnt_qposadr", "jnt_dofadr", "jnt_pos", "jnt_axis",+ "jnt_range", "dof_bodyid", "dof_jntid", "dof_armature", "dof_damping", "actuator_trnid",+ "site_bodyid", "site_pos", "site_quat", "opt.timestep", "opt.gravity")+MATCH_GEOM = ("geom_type", "geom_bodyid", "geom_size", "geom_pos", "geom_quat", "geom_contype", "geom_conaffinity",+ "geom_condim", "geom_priority", "geom_friction", "geom_solref", "geom_solimp", "geom_margin", "geom_gap")+CAMERA = ("cam_mode", "cam_bodyid", "cam_pos", "cam_quat", "cam_fovy")+++def _arr(m, name):+ o = m+ for part in name.split("."):+ o = getattr(o, part)+ return np.asarray(o)+++def visual_geoms(m) -> list:+ return [g for g in range(m.ngeom) if (m.geom(g).name or "").startswith(VISUAL_PREFIX)]+++def _mesh_verts(m, g):+ i = m.geom_dataid[g]+ return m.mesh_vert[m.mesh_vertadr[i]:m.mesh_vertadr[i] + m.mesh_vertnum[i]]+++def same_kinematics(m0, m1) -> list:+ """Differences between the match model m0 and a presentation model m1 (empty list = the same kinematics):+ every body, joint, dof, frame, inertia, site, mocap body and scene camera is identical; m0's geoms are all in m1,+ in the same order, with the same geometry, pose and contact properties (only their appearance may change:+ group, colour, material, e.g. a collision mesh moved to the hidden group 3); every other geom of m1 is an added+ visual geom (name prefix VISUAL_PREFIX) that never collides (contype = conaffinity = 0) and is drawn (group+ 0..2). Body masses and inertias being equal, the added geoms carry no mass. So the same qpos puts every body at+ the same pose in both models: a presentation scene changes only what a spectator sees."""+ bad = []+ for name in KINEMATICS:+ a, b = _arr(m0, name), _arr(m1, name)+ if a.shape != b.shape or not np.array_equal(a, b):+ bad.append(name)+ c0, c1 = _scene_cams(m0), _scene_cams(m1)+ if len(c0) != len(c1):+ bad.append("ncam")+ else:+ bad += [n for n in CAMERA if not np.array_equal(_arr(m0, n)[c0], _arr(m1, n)[c1])]+ if bad:+ return bad+ extra = visual_geoms(m1)+ keep = [g for g in range(m1.ngeom) if g not in set(extra)]+ if len(keep) != m0.ngeom:+ return [f"{len(keep)} match geoms in the presentation scene for {m0.ngeom}"]+ bad += [n for n in MATCH_GEOM if not np.array_equal(_arr(m0, n), _arr(m1, n)[keep])]+ for g0, g1 in enumerate(keep):+ if (m0.geom(g0).name or "") != (m1.geom(g1).name or ""):+ bad.append(f"name of geom {g0}")+ elif m0.geom_dataid[g0] >= 0 and m0.geom_type[g0] == MESH and not np.array_equal(_mesh_verts(m0, g0),+ _mesh_verts(m1, g1)):+ bad.append(f"mesh of geom {m0.geom(g0).name or g0}")+ for g in extra:+ if m1.geom_contype[g] or m1.geom_conaffinity[g] or not 0 <= m1.geom_group[g] <= 2:+ bad.append(f"added geom {m1.geom(g).name} collides or is not drawn")+ return bad+++def pose_diff(m0, m1, states) -> float:+ """The largest difference of any body's (and site's) world position or orientation between the two models over+ the given states ({"qpos", optional "mocap_pos", "mocap_quat"}); 0.0 = bit-identical poses."""+ import mujoco as mj+ d0, d1 = mj.MjData(m0), mj.MjData(m1)+ worst = 0.0+ for st in states:+ for m, d in ((m0, d0), (m1, d1)):+ d.qpos[:] = np.asarray(st["qpos"], float)+ if m.nmocap and "mocap_pos" in st:+ d.mocap_pos[:] = np.asarray(st["mocap_pos"], float).reshape(m.nmocap, 3)+ if m.nmocap and "mocap_quat" in st:+ d.mocap_quat[:] = np.asarray(st["mocap_quat"], float).reshape(m.nmocap, 4)+ mj.mj_kinematics(m, d)+ for a, b in ((d0.xpos, d1.xpos), (d0.xquat, d1.xquat), (d0.xmat, d1.xmat), (d0.site_xpos, d1.site_xpos)):+ if np.asarray(a).size:+ worst = max(worst, float(np.abs(np.asarray(a) - np.asarray(b)).max()))+ return worstdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/spectator/broadcast_log.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/spectator/broadcast_log.pynew file mode 100644index 0000000000..879da02402--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/spectator/broadcast_log.py@@ -0,0 +1,140 @@+"""Spectator broadcast log: an append-only, compact record of what a broadcast camera needs to draw the match.++The sim service appends one line per drawn frame (every EVERY control steps of game time, plus the last state of every+point) and one line per match event (start, run, point, review pause, end) to /data/broadcast.jsonl. A renderer OUTSIDE+the sim (scripts/olympiad/broadcast.py) tails the file, rebuilds the MuJoCo state from the same scene and draws the+broadcast camera. Nothing in the sim reads this file back: the replay, the grader and the match result do not depend on+it, and any failure here only switches the log off (`RCB_BROADCAST=0` switches it off from the start).++Lines (JSON, one per line):+ {"ev": "hdr", "sport": ..., "mode": "single"|"duel", "slowdown": S, "dt": control step s, "every": n, ...}+ {"k": step, "q": [qpos ...], ...extra} a frame (extra: per-sport fields the drawing needs, e.g. "o")+ {"ev": "point"|"run"|"pause"|"end"|..., "k": step, ...}+"""+from __future__ import annotations++import json+import os+import time++PATH = os.path.join(os.environ.get("RCB_DATA", "/data"), "broadcast.jsonl")+++class BroadcastLog:+ def __init__(self, every: int = 2, digits: int = 5, path: str = PATH, **header):+ self.every = max(1, int(every))+ self.fmt = f"{{:.{int(digits)}f}}"+ self.f = None+ self.last_k = None+ if os.environ.get("RCB_BROADCAST", "1") != "1":+ return+ try:+ self.f = open(path, "a", buffering=1 << 16)+ self._write(json.dumps({"ev": "hdr", "ts": round(time.time(), 3), "every": self.every, **header}))+ except Exception: # noqa: BLE001 (spectator output only: never disturb the match)+ self.f = None++ def _write(self, line: str) -> None:+ if self.f is None:+ return+ try:+ self.f.write(line + "\n")+ self.f.flush()+ except Exception: # noqa: BLE001+ self.f = None++ def frame(self, k: int, q, force: bool = False, **extra) -> None:+ """One drawn frame at control step k (only every `every` steps unless forced; never twice for one step)."""+ if self.f is None or k == self.last_k or (not force and k % self.every):+ return+ self.last_k = k+ try:+ fmt = self.fmt.format+ s = '{"k":%d,"q":[%s]' % (k, ",".join(fmt(float(x)) for x in q))+ for key, v in extra.items():+ s += ',"%s":%s' % (key, json.dumps(v if not isinstance(v, float) else round(v, 5)))+ self._write(s + "}")+ except Exception: # noqa: BLE001+ self.f = None++ SKIP = ("k", "t", "leg_id", "wall_mono", "qpos", "point", "played_k", "flight")++ def snapshot(self, sn: dict, force: bool = False) -> None:+ """A frame from one of the sim's own camera snapshots (the dict its Match.step() keeps for the views: k,+ qpos and whatever else the sport draws, e.g. the ball "b" and the opponent "opp")."""+ if self.f is None or sn is None:+ return+ try:+ extra = {}+ for key, v in sn.items():+ if key in self.SKIP or v is None:+ continue+ if hasattr(v, "tolist"):+ v = v.tolist()+ if isinstance(v, (list, tuple)):+ v = [round(float(x), 5) if isinstance(x, float) else x for x in v]+ elif isinstance(v, float):+ v = round(v, 5)+ extra[key] = v+ self.frame(int(sn["k"]), sn["qpos"] if sn.get("qpos") is not None else (), force=force, **extra)+ except Exception: # noqa: BLE001+ self.f = None++ def after_step(self, game, point_ended: bool = False) -> None:+ """After a control step of a match object that keeps camera snapshots in `hist` (and the ended point's in+ `review_hist`): log the newest snapshot; when a point just ended, the point's last snapshot (the new point's+ reset state is not shown as the end of the old one)."""+ if self.f is None:+ return+ try:+ if point_ended:+ rh = getattr(game, "review_hist", None)+ if rh:+ self.snapshot(rh[-1], force=True)+ return+ h = game.hist[-1] if game.hist else None+ if h is not None and h["k"] == game.k:+ self.snapshot(h)+ except Exception: # noqa: BLE001+ self.f = None++ def event(self, ev: str, k: int, **fields) -> None:+ if self.f is None:+ return+ try:+ self._write(json.dumps({"ev": ev, "k": int(k), "ts": round(time.time(), 3), **fields}, default=_plain))+ except Exception: # noqa: BLE001+ self.f = None+++def pitch_frame(bc, rt) -> None:+ """Baseball (bbrt.RT / bbduel.Duel): a frame from the pitch clock's own display data (its newest camera snapshot:+ the ball, the swing's parameters and the time since release), every `every` steps of the pitch."""+ if bc is None or bc.f is None or rt.n % bc.every:+ return+ try:+ sn = rt.snapshots()[-1]+ bc.frame(int(sn["k"]), (), force=True, ball=[round(float(x), 4) for x in sn["ball"]],+ sw=None if sn["swing"] is None else [round(float(x), 5) for x in sn["swing"]], t=round(sn["t"], 4),+ p=int(sn["pitch"]))+ except Exception: # noqa: BLE001+ bc.f = None+++def flight(samples, step: float = 0.04, t_max: float = 8.0) -> list:+ """A batted ball's flight (bb.judge_batted samples: (t, x, y, z, ...)) every `step` s, for the replay."""+ out, nxt = [], 0.0+ for sm in samples or ():+ if sm[0] >= nxt - 1e-9 and sm[0] <= t_max:+ out.append([round(float(sm[0]), 3)] + [round(float(x), 3) for x in sm[1:4]])+ nxt = sm[0] + step+ if samples and (not out or out[-1][0] < samples[-1][0]) and samples[-1][0] <= t_max:+ out.append([round(float(samples[-1][0]), 3)] + [round(float(x), 3) for x in samples[-1][1:4]])+ return out+++def _plain(x):+ try:+ return x.tolist()+ except AttributeError:+ return str(x)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/bout.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/bout.pynew file mode 100644index 0000000000..2fae72600e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/bout.py@@ -0,0 +1,141 @@+"""The referee of an epee direct-elimination bout fenced phrase by phrase (FIE Technical Rules, August 2026: t.22,+t.37, t.38, t.44, t.92, t.124), the phrase-level sport since fencing-7.++The bout is 15 touches or 9 minutes of fencing time (t.38.2: three periods of 3 minutes; deviation: one period of 9+minutes, no breaks). Each phrase (phrases.py) gives a touch for one fencer, a double or none, and takes its fencing time+(the time to the halt; 3 s for a phrase without a touch). A double scores for both (t.92), except at 14-14, where it is+not counted. When the clock ends during a phrase, the phrase ends without a touch (t.44.1). At time the fencer ahead+wins; at equal scores one more minute for a deciding touch, the priority drawn by lot before it; still equal after the+minute, the fencer with priority wins. Every phrase starts on guard (t.22).++Unwillingness to fight (t.124): one minute of fencing time without a hit -> 'Halt!'. The first time both fencers get a+P-red card, a penalty hit each; the second time the fencer with the lower score gets the P-black card and loses the+bout, at equal scores the one who loses a lot. No P-card at 14-14 (the minute restarts). The minute restarts after each+hit, double, annulled double and penalty hit, not after a phrase without a touch; t.124 does not apply in the extra+minute.++The lots are drawn from the seed for the first fencer (seat A in format bout, the first player in format duel), so a+duel with the seats and the first player swapped is the mirror image. The rules are the same as the step-4 model of+the screening (docs/screening/fencing/phrase/game.py, play_bout)."""+from __future__ import annotations++import hashlib+import json+import math++import numpy as np++BOUT_S, EXTRA_S, PASSIVE_S, TOUCHES = 180.0, 60.0, 60.0, 15+++def regulation_s(touches):+ """3 minutes of fencing time per 5 touches: a pool bout (5) 3 minutes, a direct-elimination bout (15) 9"""+ return BOUT_S * math.ceil(touches / 5)+++class Bout:+ def __init__(self, seed, first, second, touches=TOUCHES):+ self.seed, self.T = int(seed), int(touches)+ self.first, self.second = first, second+ self.reg_s = regulation_s(self.T)+ self.score = {first: 0, second: 0}+ self.t = 0.0 # fencing time (s)+ self.minute0 = 0.0 # t.124: the fencing time of the last hit+ self.extra = False+ self.priority = None+ self.p_calls = 0 # 1: the P-red cards given, 2: the P-black card+ self.winner = self.how = None+ self.log: list[dict] = []++ @property+ def over(self):+ return self.winner is not None++ def limit_s(self):+ return self.reg_s + (EXTRA_S if self.extra else 0.0)++ def time_left_s(self):+ return round(max(0.0, self.limit_s() - self.t), 2)++ def no_hit_s(self):+ return None if self.extra else round(self.t - self.minute0, 2)++ def _lot(self, salt):+ """the first fencer wins a lot drawn from the seed (salt 38: the priority, 124: the P-black card)"""+ return self.first if np.random.default_rng([self.seed, salt]).random() < 0.5 else self.second++ def phrase(self, res, dur, info=None):+ """one phrase: res = the side that touched alone, 'double' or 'none'; dur = its fencing time (s); info: the+ phrase's own fields for the log. Returns the log record."""+ if self.over:+ raise RuntimeError("the bout is over")+ a, b = self.first, self.second+ rec = dict(n=len(self.log) + 1, **(info or {}), res=res, s=dur, t0=round(self.t, 2))+ if self.t + dur > self.limit_s() + 1e-9: # t.44.1: the clock ends the phrase before its touch+ rec.update(cut_by_clock=True, res="none", res_phrase=res)+ res, self.t = "none", self.limit_s()+ else:+ self.t += dur+ awarded, annulled, card = [], False, None+ if res in (a, b):+ awarded = [res]+ elif res == "double":+ if self.score[a] == self.score[b] == self.T - 1:+ annulled = True # 14-14: the double is not counted+ else:+ awarded = [a, b] # t.92+ for s in awarded:+ self.score[s] += 1+ hit = bool(awarded or annulled)+ black = None+ if hit:+ self.minute0 = self.t # t.124.3.d+ elif not self.extra and self.t - self.minute0 >= PASSIVE_S - 1e-9:+ self.minute0 = self.t+ if self.score[a] == self.score[b] == self.T - 1:+ card = "none at 14-14" # t.124.3.a+ elif self.p_calls == 0:+ self.p_calls, card = 1, "P-red to both" # a penalty hit each+ self.score[a] += 1+ self.score[b] += 1+ hit = True+ else:+ self.p_calls, card = 2, "P-black"+ if self.score[a] != self.score[b]:+ black = a if self.score[a] < self.score[b] else b+ else:+ black = self._lot(124)+ sa, sb = self.score[a], self.score[b]+ starts_extra = False+ time_up = self.t >= self.limit_s() - 1e-9+ if black is not None:+ self.winner, self.how = (b if black == a else a), "passivity"+ elif self.extra and sa != sb:+ self.winner, self.how = (a if sa > sb else b), "deciding_touch"+ elif not self.extra and max(sa, sb) >= self.T and sa != sb:+ self.winner, self.how = (a if sa > sb else b), "touches"+ elif time_up and not self.extra:+ if sa != sb:+ self.winner, self.how = (a if sa > sb else b), "time"+ else:+ self.extra, self.priority = True, self._lot(38) # the extra minute, on guard (t.22.8)+ starts_extra = True+ elif time_up and self.extra:+ self.winner, self.how = self.priority, "priority"+ rec.update(awarded=awarded, annulled=annulled, card=card, black=black, t=round(self.t, 2),+ score={a: sa, b: sb}, extra_minute_starts=starts_extra)+ self.log.append(rec)+ return rec++ def forfeit(self, side, why):+ """the core's decision (a chess clock run out, a session abandoned): `side` loses"""+ if not self.over:+ self.winner, self.how = (self.second if side == self.first else self.first), why++ def state(self):+ return dict(seed=self.seed, T=self.T, first=self.first, score=self.score, t=round(self.t, 6),+ minute0=round(self.minute0, 6), extra=self.extra, priority=self.priority, p_calls=self.p_calls,+ winner=self.winner, how=self.how, log=self.log)++ def state_sha(self):+ return hashlib.sha256(json.dumps(self.state(), sort_keys=True, default=str).encode()).hexdigest()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/builtin_players.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/builtin_players.pynew file mode 100644index 0000000000..9b95f8886e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/builtin_players.py@@ -0,0 +1,245 @@+"""fencing's built-in players (fencing-7, the phrase-level sport; the same action interface as a model's program:+core/client.py plays them over HTTP).++ Reference a reader of the opponent (since 2026-10-14; screening report, section 6 "fencing-7"): ten hypotheses+ about the opponent's next intention, each scored by how well it predicted the opponent's past choices+ (decayed log-score); the best one is answered with the logit answer (20 per net touch) by the phrase+ table of `game spec`, and in 10 % of the phrases a draw from the table's equilibrium mix. Five are the+ pattern reader of step 4 (2026-10-13): the opponent's mix; after its last intention; after its last two;+ after my last one; after the last pair (tables of decayed counts). Five model how the opponent reads me:+ it predicts MY next intention from my mix, after my last one, after my last two, after its last one or+ after the last pair, and answers that prediction (logit 40, 5 % spread). The pattern reader alone is+ the weak form of the capability-sensitivity check, the equilibrium mix the strong form. It reads only+ `game spec` and the state (the phrases so far), and draws from its own stream (the seed).+ Rival the reference drawing from a stream of the seed and its seat (the fairness policy: two references with+ the same seed would draw alike).+ Random a uniform intention every phrase (generic tests).+No simulator import: this file runs in the player's container as the task's oracle (numpy only)."""+from __future__ import annotations++import math++import numpy as np++PRIOR = 1.0+RESULT = {"you": 1, "opponent": -1, "double": 2, "double, not counted at 14-14": 2, "none": 0}+++def solve_zero_sum(M, max_iter=10000):+ """(value, x, y) of the zero-sum game where the row player maximises x' M y (simplex, Bland's rule)"""+ M = np.asarray(M, float)+ m, n = M.shape+ c = 1.0 - M.min()+ T = np.zeros((m + 1, n + m + 1))+ T[:m, :n] = M + c+ T[:m, n:n + m] = np.eye(m)+ T[:m, -1] = 1.0+ T[m, :n] = -1.0+ basis = list(range(n, n + m))+ for _ in range(max_iter):+ neg = np.flatnonzero(T[m, :-1] < -1e-12)+ if len(neg) == 0:+ break+ col = int(neg[0])+ colv = T[:m, col]+ pos = colv > 1e-12+ ratios = np.full(m, np.inf)+ ratios[pos] = T[:m, -1][pos] / colv[pos]+ ties = np.flatnonzero(ratios <= ratios.min() + 1e-12)+ r = int(min(ties, key=lambda k: basis[k]))+ T[r] /= T[r, col]+ for k in range(m + 1):+ if k != r and T[k, col] != 0.0:+ T[k] -= T[k, col] * T[r]+ basis[r] = col+ else:+ raise RuntimeError("simplex did not converge")+ z = T[m, -1]+ yp = np.zeros(n)+ for r, b in enumerate(basis):+ if b < n:+ yp[b] = T[r, -1]+ xp = np.clip(T[m, n:n + m], 0.0, None)+ return float(1.0 / z - c), xp / xp.sum(), yp / yp.sum()+++def table_from_spec(spec):+ """(intention names, my expected net touches per phrase T[mine, theirs], the equilibrium mix) from `game spec`"""+ names = list(spec["intentions"])+ pt = spec["phrase_table"]+ C = np.array([[pt["counts"][f"{a}|{b}"] for b in names] for a in names], float)+ P = (C + PRIOR) / (C.sum(-1, keepdims=True) + 4 * PRIOR)+ T = P[..., 0] - P[..., 1]+ _, x, _ = solve_zero_sum(T)+ return names, T, x+++class Reader:+ """the pattern reader (screening: game.py Context, beta 20, eps_eq 0.1)"""+ CONTEXTS = ("m", "o1", "o2", "me1", "pair")++ def __init__(self, T, eq, rng, beta=20.0, eps_eq=0.1, decay=0.9, prior=0.3, score_decay=0.8):+ self.P, self.eq, self.rng, self.n = T, eq, rng, len(eq)+ self.beta, self.eps_eq, self.decay, self.prior, self.score_decay = beta, eps_eq, decay, prior, score_decay+ self.hist = []+ self.tabs = {c: {} for c in self.CONTEXTS}+ self.score = {c: 0.0 for c in self.CONTEXTS}+ self._keys, self._preds = {}, {}+ self.used = "m"++ def _key(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "o1":+ return h[-1][1]+ if c == "o2":+ return (h[-2][1], h[-1][1]) if len(h) >= 2 else None+ if c == "me1":+ return h[-1][0]+ return (h[-1][1], h[-1][0])++ def _pred(self, c, key):+ t = self.tabs[c].get(key) if key is not None else None+ if t is None:+ return None+ p = t + self.prior+ return p / p.sum()++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ best, bs = "m", self.score["m"]+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ if p is not None and self.score[c] > bs + 1e-12:+ best, bs = c, self.score[c]+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def choose(self):+ p = self.dist()+ return int(min(np.searchsorted(np.cumsum(p), self.rng.random(), side="right"), len(p) - 1))++ def observe(self, mine, other, res):+ for c, p in self._preds.items():+ self.score[c] = self.score_decay * self.score[c] + math.log(p[other])+ self.hist.append((mine, other, res))+ for c, key in self._keys.items():+ if key is None:+ continue+ t = self.tabs[c].get(key)+ if t is None:+ t = self.tabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[other] += 1.0+++class MindReader(Reader):+ """the pattern reader plus five hypotheses that the opponent predicts my next intention (from the contexts MINE of+ my own play) and answers it"""+ MINE = ("m", "me1", "me2", "o1", "pair")++ def __init__(self, *a, beta_o=40.0, eps_o=0.05, **k):+ super().__init__(*a, **k)+ self.beta_o, self.eps_o = beta_o, eps_o+ self.mtabs = {c: {} for c in self.MINE}+ for c in self.MINE:+ self.score["tom_" + c] = 0.0+ self._mkeys = {}++ def _mkey(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "me1":+ return h[-1][0]+ if c == "me2":+ return (h[-2][0], h[-1][0]) if len(h) >= 2 else None+ if c == "o1":+ return h[-1][1]+ return (h[-1][0], h[-1][1])++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ self._mkeys = {c: self._mkey(c) for c in self.MINE}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ mmarg = self.mtabs["m"].get(0)+ for c in self.MINE:+ t = self.mtabs[c].get(self._mkeys[c]) if self._mkeys[c] is not None else None+ if t is None:+ t = mmarg+ q = np.full(self.n, 1.0 / self.n) if t is None else (t + self.prior) / (t + self.prior).sum()+ v = -self.P.T @ q # the opponent's net per intention against my predicted mix+ a = np.exp(self.beta_o * (v - v.max()))+ a /= a.sum()+ self._preds["tom_" + c] = self.eps_o / self.n + (1 - self.eps_o) * a+ best = max(self._preds, key=lambda c: (self.score[c], c == "m"))+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def observe(self, mine, other, res):+ for c, key in self._mkeys.items():+ if key is None:+ continue+ t = self.mtabs[c].get(key)+ if t is None:+ t = self.mtabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[mine] += 1.0+ super().observe(mine, other, res)+++class Reference:+ def __init__(self, spec, seat, seed=0):+ self.names, T, eq = table_from_spec(spec)+ self.idx = {s: i for i, s in enumerate(self.names)}+ self.r = MindReader(T, eq, self._rng(seed, seat))+ self.seen = 0++ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12]) # by seed, not by seat: mirror runs match++ def act(self, view):+ ph = view["state"].get("phrases") or []+ for p in ph[self.seen:]:+ self.r.observe(self.idx[p["you"]], self.idx[p["opponent"]], RESULT[p["result"]])+ self.seen = len(ph)+ return {"type": "phrase", "intention": self.names[self.r.choose()]}++ def review(self, reply):+ return ("read the phrase's result", f"answer the opponent's next intention as predicted by '{self.r.used}'")+++class Rival(Reference):+ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12, sum(map(ord, str(seat)))])+++class Random:+ def __init__(self, spec, seat, seed=0):+ self.names = list(spec["intentions"])+ self.g = np.random.default_rng(int(seed) * 7919 + 17) # by seed, not by seat: mirror runs match++ def act(self, view):+ return {"type": "phrase", "intention": self.names[int(self.g.integers(len(self.names)))]}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/cameras.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/cameras.pynew file mode 100644index 0000000000..53bc7173e7--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/cameras.py@@ -0,0 +1,140 @@+"""The seats' cameras (each in its own frame) and the observation image (drawn in the seat's render worker of the v0.2+core), fencing-7.++Each seat has two fixed cameras, placed the same way in its own frame (fencing.py: the seat stands at x < 0 and faces++x): `side` beside the piste (y = -7 m) looking across it, the seat's robot on the left and the opponent on the right;+`top` above and beside the piste looking down at it. The observation image shows the last phrase (phrases.py): 2 rows+(side, top) x 2 columns (the phrase half-way, at its end) of 800 x 360 pixel tiles; before the first phrase both+fencers on guard. Every seat sees its own robot red and the opponent's blue, the points yellow+(fencing.scene_xml(view=seat): the same scene, other colours).++The frames were kept from the measured phrases (phrases/frames.npz) on the table's ends; when a fencer fenced the+phrase from the table's other end (phrases.py: the ends are drawn for each phrase), the picture is turned by half a+turn about the centre of the piste (half_turn), so that each fencer is always drawn at its own end.++A Renderer keeps the tiles it drew (by camera and the frame's joint positions) and its last image.+"""+from __future__ import annotations++import hashlib+import math+from collections import OrderedDict++import numpy as np++import fencing as F++TILE = (800, 360) # width, height (as the legacy views.py)+FOVY = 45.0+FOCAL = TILE[1] / 2 / math.tan(math.radians(FOVY / 2)) # 434.6 px+CAMS = { # own frame: lookat, distance, azimuth (deg), elevation (deg) [MuJoCo free camera] (as the legacy views.py)+ "side": ((0.0, 0.0, 0.75), 7.0, 90.0, -5.0),+ "top": ((0.0, 0.0, 0.8), 7.5, 90.0, -70.0),+}+N_FRAMES = 2 # columns of the observation image: the last phrase half-way and at its end+IMAGE_LAYOUT = ("2 rows x 2 columns of 800 x 360 tiles. Row 1: the side camera, row 2: the top camera (poses in `game "+ "spec`). Columns: the last phrase half-way (left) and at its end (right); before the first phrase "+ "both fencers on guard. Your robot is red, the opponent's blue; the points are yellow.")+++def cam_info():+ """camera pose (own frame) and intrinsics, for /spec"""+ out = []+ for name, (la, dist, az, el) in CAMS.items():+ a, e = math.radians(az), math.radians(el)+ fwd = np.array([math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)])+ pos = np.asarray(la) - dist * fwd+ right = np.cross(fwd, [0.0, 0.0, 1.0])+ right /= np.linalg.norm(right)+ up = np.cross(right, fwd)+ out.append(dict(name=name, pos=[round(float(x), 4) for x in pos], forward=[round(float(x), 5) for x in fwd],+ right=[round(float(x), 5) for x in right], up=[round(float(x), 5) for x in up],+ fovy_deg=FOVY, tile_px=list(TILE), focal_px=round(FOCAL, 2),+ principal_point_px=[TILE[0] / 2, TILE[1] / 2],+ model="pinhole: pixel u = cx + f (d.right)/(d.forward), v = cy - f (d.up)/(d.forward) for a "+ "point at offset d from pos (u to the right, v down)"))+ return out+++class Renderer:+ """Draws one seat's observation image from camera frames (qpos); owns its own MjData and GL context."""++ def __init__(self, seat: str, cache: int = 32):+ import mujoco as mj+ self.mj, self.seat = mj, seat+ self.m = m = mj.MjModel.from_xml_string(F.scene_xml(view=seat))+ self.d = mj.MjData(m)+ self.r = mj.Renderer(m, height=TILE[1], width=TILE[0])+ self.cams = []+ sg = F.SIGN[seat]+ for la, dist, az, el in CAMS.values():+ c = mj.MjvCamera()+ c.lookat[:] = (sg * la[0], sg * la[1], la[2])+ c.distance, c.azimuth, c.elevation = dist, az + (0.0 if seat == "A" else 180.0), el+ self.cams.append(c)+ self.cache: OrderedDict = OrderedDict()+ self.size = cache+ self.drawn = 0 # tiles actually rendered (the rest came from the cache)+ self.last = (None, None) # (the frames' keys, the PNG) of the last image++ def tile(self, ci, snap):+ from PIL import Image, ImageDraw+ q = np.ascontiguousarray(snap["qpos"], dtype=np.float64)+ key = (ci, snap["label"], hashlib.sha1(q.tobytes()).hexdigest())+ if key in self.cache:+ self.cache.move_to_end(key)+ return self.cache[key]+ self.d.qpos[:] = q+ self.mj.mj_kinematics(self.m, self.d)+ self.r.update_scene(self.d, camera=self.cams[ci])+ im = Image.fromarray(self.r.render())+ ImageDraw.Draw(im).text((6, 4), snap["label"], fill=(255, 255, 255))+ img = np.asarray(im)+ self.drawn += 1+ self.cache[key] = img+ while len(self.cache) > self.size:+ self.cache.popitem(last=False)+ return img++ def render(self, snaps):+ """snaps: [{label, qpos}], oldest first -> PNG bytes"""+ from core.observe import png+ keys = tuple((sn["label"], hashlib.sha1(np.ascontiguousarray(sn["qpos"], dtype=np.float64).tobytes()).hexdigest())+ for sn in snaps)+ if self.last[0] == keys:+ return self.last[1]+ rows = [np.concatenate([self.tile(ci, sn) for sn in snaps], axis=1) for ci in range(len(self.cams))]+ out = png(np.concatenate(rows, axis=0))+ self.last = (keys, out)+ return out+++_HALF = {}+++def half_turn(m, qpos):+ """the same pose turned by half a turn about the vertical through the centre of the piste: fencer A's joints become+ B's and B's A's, each floating base at (-x, -y, z) and turned by pi about z"""+ import mujoco as mj+ key = id(m)+ if key not in _HALF:+ pairs = []+ for j in range(m.njnt):+ nm = mj.mj_id2name(m, mj.mjtObj.mjOBJ_JOINT, j)+ if nm.startswith("A_"):+ jb = mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, "B_" + nm[2:])+ pairs.append((int(m.jnt_type[j]), int(m.jnt_qposadr[j]), int(m.jnt_qposadr[jb])))+ _HALF[key] = pairs+ q = np.asarray(qpos, float)+ out = q.copy()+ zpi = np.array([0.0, 0.0, 0.0, 1.0])+ for typ, a, b in _HALF[key]:+ for src, dst in ((a, b), (b, a)):+ if typ == mj.mjtJoint.mjJNT_FREE:+ out[dst:dst + 3] = (-q[src], -q[src + 1], q[src + 2])+ qq = np.zeros(4)+ mj.mju_mulQuat(qq, zpi, q[src + 3:src + 7])+ out[dst + 3:dst + 7] = qq+ else:+ out[dst] = q[src]+ return outdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/fencing.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/fencing.pynew file mode 100644index 0000000000..1b7d536a9e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/fencing.py@@ -0,0 +1,80 @@+"""The scene of robot epee fencing (fencing-7, the phrase-level sport): the piste and two Unitree G1 humanoids of the+robot library, each holding an epee on its right wrist mount, for the cameras. The phrases themselves were measured in+the fencing-6 world (this file's World and Phrase referee up to revision fencing-6, with NVIDIA's SONIC policy on the+robots: docs/screening/fencing/phrase/) and are replayed from phrases/table.json (phrases.py); the cameras draw the+joint positions kept from them (phrases/frames.npz) in this scene, which is the scene they were measured in.++World (metres): piste surface z = 0, long axis x, centre line x = 0, on-guard lines x = +-2, rear limits x = +-7,+lateral limits y = +-0.75 (t.18-t.19). Fencer A stands at x < 0 facing +x, fencer B at x > 0 facing -x (both+right-handed). Each seat sees everything in its OWN frame: x' = s x, y' = s y, z' = z with s = +1 for A and -1 for B,+so in its own frame every fencer stands at x' < 0 and faces +x'.+"""+from __future__ import annotations++import math+import sys+import xml.etree.ElementTree as ET+from pathlib import Path++HERE = Path(__file__).resolve().parent+_ROOT = HERE.parent # sim/ in a task (bodies/ next to sport/); sports/ in a checkout+sys.path.insert(0, str(_ROOT if (_ROOT / "bodies").is_dir() else _ROOT.parent))+from bodies import load_body # noqa: E402++CONTROL_DT, SUBSTEPS, PHYS_DT = 0.01, 10, 0.001+SEATS = ("A", "B")+SIGN = {"A": 1.0, "B": -1.0}+OTHER = {"A": "B", "B": "A"}+# ---- piste (t.18, t.19)+PISTE_HALF, ON_GUARD, PISTE_HALF_W = 7.0, 2.0, 0.75+# ---- the fencer+BODY, HAND, WALKER = "unitree_g1", "epee", "falcon_legs"+SETTLE_STEPS = 100 # after the referee places the robots: 1 s standing on guard (frozen fencing time)+FALL_Z, FALL_TILT = 0.45, 1.0 # pelvis height (m), pelvis tilt (rad): down+ARM_PARTS = ("shoulder", "elbow", "wrist", "hand", "mount") # arm on arm is close quarters (t.24), not corps-a-corps+# ---- the apparatus+F_TOUCH = 7.35 # N: 750 g on the point+T_TOUCH_SAMPLES = 3 # >= 2 ms: three consecutive 1 ms samples above F_TOUCH+DOUBLE_MS = 45 # lockout: a touch by the other within 45 ms is a double (40-50 ms, Appendix B)+ACCENT = {"A": (0.1, 0.35, 0.85, 1), "B": (0.85, 0.15, 0.12, 1)}+RED, BLUE, YELLOW = (0.85, 0.15, 0.12, 1), (0.1, 0.35, 0.85, 1), (1.0, 0.85, 0.1, 1)+TINT = {"own": (0.9, 0.45, 0.4, 1), "opponent": (0.35, 0.5, 0.95, 1)} # the robots' shells in a seat's images+REVISION = "fencing-7"++WORLD_XML = f"""<mujoco model="piste"><compiler angle="radian" autolimits="true"/>+<option timestep="{PHYS_DT}" integrator="implicitfast"/>+<visual><global offwidth="1280" offheight="720"/></visual>+<worldbody><light pos="0 0 4" dir="0 0 -1"/><light directional="true" pos="0 -6 4" dir="0 1 -0.6" diffuse="0.5 0.5 0.5"/>+<geom name="floor" type="plane" size="10 4 0.1" conaffinity="5" rgba="0.55 0.55 0.6 1"/>+<geom name="piste" type="box" size="{PISTE_HALF} {PISTE_HALF_W} 0.0005" pos="0 0 0.0005" contype="0" conaffinity="0"+ rgba="0.35 0.38 0.45 1"/>+<geom name="centre_line" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="0 0 0.0006" contype="0" conaffinity="0" rgba="1 1 1 1"/>+<geom name="guard_A" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{-ON_GUARD} 0 0.0006" contype="0" conaffinity="0" rgba="1 1 1 1"/>+<geom name="guard_B" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{ON_GUARD} 0 0.0006" contype="0" conaffinity="0" rgba="1 1 1 1"/>+<geom name="rear_A" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{-PISTE_HALF} 0 0.0006" contype="0" conaffinity="0" rgba="1 0.2 0.2 1"/>+<geom name="rear_B" type="box" size="0.01 {PISTE_HALF_W} 0.0006" pos="{PISTE_HALF} 0 0.0006" contype="0" conaffinity="0" rgba="1 0.2 0.2 1"/>+</worldbody></mujoco>"""+++def scene_xml(view: str | None = None) -> str:+ """the piste and both fencers (the library's mount: the robot, its epee, its self-collision pairs). view: the seat+ whose camera images it draws (its robot red, the opponent blue, the points yellow; the physics is the same)"""+ B = load_body(BODY)+ root = ET.fromstring(WORLD_XML)+ for s in SEATS:+ acc = ACCENT[s] if view is None else (RED if s == view else BLUE)+ B.mount(root, f"{s}_", (-SIGN[s] * ON_GUARD, 0.0, 0.0), 0.0 if s == "A" else math.pi, hand=HAND, accent=acc)+ if view is not None: # the images only: own robot light red, the opponent light blue, points yellow+ for body in root.find("worldbody").iter("body"):+ nm = body.get("name") or ""+ if nm[:2] not in ("A_", "B_") or nm.endswith("hand"):+ continue+ tint = TINT["own" if nm[0] == view else "opponent"]+ for g in body.findall("geom"):+ if g.get("contype", None) == "0" or g.get("class", "").endswith("visual") or g.get("group") in ("1", "2"):+ g.attrib.pop("material", None)+ g.set("rgba", " ".join(str(c) for c in tint))+ for g in root.iter("geom"):+ if (g.get("name") or "").endswith("hand_tip"):+ g.set("rgba", " ".join(str(c) for c in YELLOW))+ return ET.tostring(root, encoding="unicode")diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/grade.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/grade.pynew file mode 100644index 0000000000..a6c7b75098--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/grade.py@@ -0,0 +1,77 @@+"""fencing's part of reward.json (the common part is core/grading.py: success, valid_trial, technical_failure,+deterministic, seed, official_config, video_rendered, <seat>_won, <seat>_transient/unrecovered_api_errors, ...):+numbers only, from final.json (and the seat's metering summary think_usage_<seat>.json, a declared artifact of the+sim). fencing-7 (the phrase-level sport): the bout's phrases instead of fencing-6's halts; the legacy reward names+of both tasks are kept where they still mean something (README.md)."""+import json+import os+from collections import Counter+from pathlib import Path++DATA = Path(os.environ.get("RCB_DATA", "/data"))+COUNTS = ("n_act", "n_observe", "n_reviews", "refused_busy", "refused_turn", "refused_not_model")+++def _usage(seat):+ try:+ return json.loads((DATA / f"think_usage_{seat}.json").read_text())+ except (OSError, ValueError):+ return {}+++def _bout(f):+ ph = f.get("phrases") or []+ return {"bout_over": int(f.get("how") in ("touches", "passivity", "time", "deciding_touch", "priority")),+ "extra_minute": int(bool(f.get("extra_minute"))), "phrases": len(ph),+ "doubles": sum(1 for r in ph if r.get("res") == "double"),+ "doubles_not_counted": sum(1 for r in ph if r.get("annulled")),+ "no_touch_phrases": sum(1 for r in ph if r.get("res") == "none"),+ "p_cards": int(f.get("p_cards") or 0), "fencing_time_s": float(f.get("fencing_time_s") or 0.0)}+++def _intentions(f, side, prefix):+ c = Counter((r.get("intentions") or {}).get(side) for r in f.get("phrases") or [])+ names = ("lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw")+ return {f"{prefix}intention_{n}": int(c.get(n, 0)) for n in names}+++def evaluate(d):+ f = d.get("sport_fields") or {}+ seats = d["cfg"]["seats"]+ scores = d.get("scores") or {}+ stats = d.get("seats") or {}+ out = _bout(f)+ if len(seats) == 1: # the bout against the scripted fencer (side B)+ s = seats[0]+ st, u = stats.get(s, {}), _usage(s)+ errs = d.get("errors") or []+ won = d.get("match_winner") == s and out["bout_over"] == 1+ rp = d.get("replay_scores") or {}+ pf, pa = int(scores.get(s, 0)), int(scores.get("B", 0))+ out.update(+ won=int(won), level=int(f.get("level") or 0), won_on_priority=int(won and f.get("how") == "priority"),+ sim_error=int(d.get("reason") == "technical_error" or any(e.get("where") != "replay" for e in errs)),+ replay_error=int(not d.get("deterministic") or any(e.get("where") == "replay" for e in errs)),+ meter_error=int(bool((d.get("meter_error") or {}).get(s))),+ proxy_error=int(bool((d.get("proxy_error") or {}).get(s))), finalized=int(bool(d.get("finalized"))),+ touches_for=pf, touches_against=pa, points_for=pf, points_against=pa,+ replay_touches_for=int(rp.get(s, -1)), replay_touches_against=int(rp.get("B", -1)),+ clock_forfeit=int(f.get("how") == "clock"), clock_used_s=float((d.get("clock_used_s") or {}).get(s, 0.0)),+ elapsed_s=float(d.get("elapsed_s") or 0.0), metered_requests=int(u.get("requests", 0)),+ metered_output_tokens=int(u.get("output_tokens", 0)), metered_input_tokens=int(u.get("input_tokens", 0)),+ rate_limit_retries=int(u.get("rate_limit_retries", 0)),+ transient_api_errors=int((d.get("transient_api_errors") or {}).get(s, 0)),+ unrecovered_api_errors=int((d.get("unrecovered_api_errors") or {}).get(s, 0)),+ **{k: int(st.get(k, 0)) for k in COUNTS}, **_intentions(f, s, ""), **_intentions(f, "B", "opponent_"))+ return out+ out.update(won_on_priority=int(bool(d.get("valid_trial")) and f.get("how") == "priority"),+ clock_forfeit=int(f.get("how") == "clock"), abandoned=int(f.get("how") == "abandoned"),+ first_player_A=int(f.get("first_player") == "A"), elapsed_s=float(d.get("elapsed_s") or 0.0))+ for s in seats:+ st = stats.get(s, {})+ out[s + "_points"] = int(scores.get(s, 0))+ out[s + "_clock_used_s"] = float((d.get("clock_used_s") or {}).get(s, 0.0))+ for k in COUNTS:+ out[s + "_" + k] = int(st.get(k, 0))+ out.update(_intentions(f, s, s + "_"))+ return outdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/opponent.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/opponent.pynew file mode 100644index 0000000000..436ee20472--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/opponent.py@@ -0,0 +1,370 @@+"""The scripted fencer of format bout (fencing-7, the phrase-level sport): before each phrase it chooses its intention+from what it has seen of the bout (the intentions both fencers played and the results), never from the agent's choice+for this phrase. It knows the phrase table (phrases.Table.counts, the same counts as `game spec` phrase_table).++Two levels (docs/screening/fencing.md, section 6 "Phrase-level construction" and "fencing-7"): level 1 chosen in step 4+of the screening on tables measured before it was frozen and checked on a table measured after (the design and the+check: docs/screening/fencing/phrase/game.py, the same classes); level 2 redesigned on the exact table on 2026-10-14,+because the first level 2 was beaten far more often than level 1 by a reader that models how it reads, then set to the+option the maintainers chose (Chi, 2026-10-14): checked on fresh seeds against the reference, the pattern reader, the+equilibrium mix and the simple programs (docs/screening/fencing/phrase/levels/):+ level 1 a reader with a fixed library of simple models of the agent (its whole-bout mix, its recent mix, it repeats+ its last intention, it answers my last one, it copies my last one, it plays what just won, it goes round the+ menu); it believes the model with the best recent prediction score and plays the best answer to it, but+ in 70 % of the phrases it plays its habit instead (the best answer to the agent's whole-bout mix, with a+ prior of 3 per intention): a slow, readable tendency+ level 2 a reader of the agent that also models how the agent reads it (class Mind): five predictors of the agent's+ next intention (its mix; after its last one; after its last two; after my last one; after the last pair)+ and five hypotheses that the agent predicts MY next intention from my patterns and answers it; the+ hypothesis with the best recent prediction score is answered (logit 20 per net touch), and in 10 % of the+ phrases a draw from the table's equilibrium mix+Its random draws come from its own stream (the seed), so a bout replays exactly."""+from __future__ import annotations++import math++import numpy as np++PRIOR = 1.0 # the table's counts + PRIOR per outcome: the expected net touches the players use+LEVELS = {+ 1: dict(family="models", h=0.7, habit_prior=3.0,+ desc="model reader, 70% habit (whole-bout best answer, prior 3)"),+ 2: dict(family="mind", beta=20.0, eps_eq=0.1,+ desc="reads your patterns and how you read it (logit 20), 10% equilibrium"),+}+++def solve_zero_sum(M, max_iter=10000):+ """Equilibrium of the zero-sum game where the row player maximises x' M y. Simplex on the column player's LP+ (max 1'y' s.t. (M + c) y' <= 1, y' >= 0, with M + c > 0), Bland's rule; the row player's mix from the duals.+ Returns (value, x, y)."""+ M = np.asarray(M, float)+ m, n = M.shape+ c = 1.0 - M.min()+ A = M + c+ T = np.zeros((m + 1, n + m + 1))+ T[:m, :n] = A+ T[:m, n:n + m] = np.eye(m)+ T[:m, -1] = 1.0+ T[m, :n] = -1.0+ basis = list(range(n, n + m))+ for _ in range(max_iter):+ neg = np.flatnonzero(T[m, :-1] < -1e-12)+ if len(neg) == 0:+ break+ col = int(neg[0])+ colv = T[:m, col]+ pos = colv > 1e-12+ ratios = np.full(m, np.inf)+ ratios[pos] = T[:m, -1][pos] / colv[pos]+ rmin = ratios.min()+ ties = np.flatnonzero(ratios <= rmin + 1e-12)+ r = int(min(ties, key=lambda k: basis[k]))+ T[r] /= T[r, col]+ for k in range(m + 1):+ if k != r and T[k, col] != 0.0:+ T[k] -= T[k, col] * T[r]+ basis[r] = col+ else:+ raise RuntimeError("simplex did not converge")+ z = T[m, -1]+ yp = np.zeros(n)+ for r, b in enumerate(basis):+ if b < n:+ yp[b] = T[r, -1]+ xp = np.clip(T[m, n:n + m], 0.0, None)+ x, y = xp / xp.sum(), yp / yp.sum()+ return float(1.0 / z - c), x, y+++class Knowledge:+ """the table as the players use it: P[i, j] = (counts + PRIOR) / (total + 4 PRIOR) over [me, other, double, none];+ T[i, j] = P(I touch alone) - P(the other touches alone): my expected net touches per phrase; x, y: its equilibrium"""++ def __init__(self, counts, prior=PRIOR):+ C = np.asarray(counts, float)+ self.n = C.shape[0]+ self.P = (C + prior) / (C.sum(-1, keepdims=True) + 4 * prior)+ self.T = self.P[..., 0] - self.P[..., 1]+ self.v, self.x, self.y = solve_zero_sum(self.T)+++def sample(p, rng):+ return int(min(np.searchsorted(np.cumsum(p), rng.random(), side="right"), len(p) - 1))+++class Policy:+ """one fencer's decision program from its own seat: P[mine, other] = its expected net touches per phrase.+ observe(mine, other, res): res 1 = I scored alone, -1 = the other alone, 2 = double (also annulled), 0 = nothing"""++ def __init__(self, name, desc=""):+ self.name, self.desc = name, desc++ def reset(self, kn, side, rng):+ self.side, self.rng = side, rng+ self.P = kn.T if side == 0 else -kn.T.T+ self.eq = kn.x if side == 0 else kn.y+ self.n = kn.n+ self.hist = []+ self.t = 0++ def observe(self, mine, other, res):+ self.hist.append((mine, other, res))+ self.t += 1+++class Context(Policy):+ """pattern prediction: five predictors of the other's next intention (its overall mix; after its last one; after+ its last two; after my last one; after the last pair), each a table of decayed counts; the predictor with the best+ recent log-score is used; then the best answer to the prediction (logit beta), and with probability eps_eq a draw+ from the equilibrium mix instead (so it cannot be read in turn)"""+ CONTEXTS = ("m", "o1", "o2", "me1", "pair")++ def __init__(self, name, desc="", beta=20.0, eps_eq=0.25, decay=0.9, prior=0.3, score_decay=0.8):+ super().__init__(name, desc)+ self.beta, self.eps_eq, self.decay, self.prior, self.score_decay = beta, eps_eq, decay, prior, score_decay++ def reset(self, kn, side, rng):+ super().reset(kn, side, rng)+ self.tabs = {c: {} for c in self.CONTEXTS}+ self.score = {c: 0.0 for c in self.CONTEXTS}+ self._keys, self._preds = {}, {}++ def _key(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "o1":+ return h[-1][1]+ if c == "o2":+ return (h[-2][1], h[-1][1]) if len(h) >= 2 else None+ if c == "me1":+ return h[-1][0]+ return (h[-1][1], h[-1][0])++ def _pred(self, c, key):+ t = self.tabs[c].get(key) if key is not None else None+ if t is None:+ return None+ p = t + self.prior+ return p / p.sum()++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ best, bs = "m", self.score["m"]+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ if p is not None and self.score[c] > bs + 1e-12:+ best, bs = c, self.score[c]+ v = self.P @ self._preds[best]+ if self.beta is None:+ core = (v >= v.max() - 1e-9).astype(float)+ else:+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def choose(self, score):+ return sample(self.dist(), self.rng)++ def observe(self, mine, other, res):+ for c, p in self._preds.items():+ self.score[c] = self.score_decay * self.score[c] + math.log(p[other])+ super().observe(mine, other, res)+ for c, key in self._keys.items():+ if key is None:+ continue+ t = self.tabs[c].get(key)+ if t is None:+ t = self.tabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[other] += 1.0+++class Mind(Context):+ """pattern prediction (Context) plus five hypotheses that the other reads ME: it predicts my next intention from my+ patterns (my mix; after my last one; after my last two; after its last one; after the last pair) and answers that+ prediction (logit beta_o, eps_o spread); every hypothesis is scored by how well it predicted the other's choices,+ the best one is answered (logit beta), and with probability eps_eq a draw from the equilibrium mix instead. The+ same reader as the reference (builtin_players.MindReader), from this fencer's seat."""+ MINE = ("m", "me1", "me2", "o1", "pair")++ def __init__(self, name, desc="", beta=20.0, eps_eq=0.1, beta_o=40.0, eps_o=0.05, **k):+ super().__init__(name, desc, beta=beta, eps_eq=eps_eq, **k)+ self.beta_o, self.eps_o = beta_o, eps_o++ def reset(self, kn, side, rng):+ super().reset(kn, side, rng)+ self.mtabs = {c: {} for c in self.MINE}+ for c in self.MINE:+ self.score["tom_" + c] = 0.0+ self._mkeys = {}++ def _mkey(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "me1":+ return h[-1][0]+ if c == "me2":+ return (h[-2][0], h[-1][0]) if len(h) >= 2 else None+ if c == "o1":+ return h[-1][1]+ return (h[-1][0], h[-1][1])++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ self._mkeys = {c: self._mkey(c) for c in self.MINE}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ mmarg = self.mtabs["m"].get(0)+ for c in self.MINE:+ t = self.mtabs[c].get(self._mkeys[c]) if self._mkeys[c] is not None else None+ if t is None:+ t = mmarg+ q = np.full(self.n, 1.0 / self.n) if t is None else (t + self.prior) / (t + self.prior).sum()+ v = -self.P.T @ q # the other's net per intention against my predicted mix+ a = np.exp(self.beta_o * (v - v.max()))+ a /= a.sum()+ self._preds["tom_" + c] = self.eps_o / self.n + (1 - self.eps_o) * a+ best = max(self._preds, key=lambda c: (self.score[c], c == "m"))+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def observe(self, mine, other, res):+ for c, key in self._mkeys.items():+ if key is None:+ continue+ t = self.mtabs[c].get(key)+ if t is None:+ t = self.mtabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[mine] += 1.0+ super().observe(mine, other, res)+++class Models(Policy):+ """a reader with a fixed library of simple models of the other fencer, each predicting its next intention:+ marg its whole-bout mix recent its recency-weighted mix (0.7)+ repeat it repeats its last intention counter it answers my last intention with the table's best answer+ copy it copies my last intention winner it plays what won the last phrase (whoever played it)+ seq it continues its last step through the menu (a cycle)+ each model's prediction is 80 % its guess, 20 % spread (marg and recent as they are); the model with the best+ recent log-score (decay `score_decay`) is believed; the answer is the best (or logit beta) against it.+ habit: with probability h it plays its habit instead, the best answer to the other's whole-bout mix with a strong+ prior (`habit_prior` per intention): a slow, readable tendency. eps_eq: a draw from the equilibrium mix."""+ ALL = ("marg", "recent", "repeat", "counter", "copy", "winner", "seq")++ def __init__(self, name, desc="", models=ALL, h=0.0, habit_prior=3.0, eps_eq=0.0, beta=None, score_decay=0.7):+ super().__init__(name, desc)+ self.models, self.h, self.habit_prior, self.eps_eq, self.beta = tuple(models), h, habit_prior, eps_eq, beta+ self.score_decay = score_decay++ def reset(self, kn, side, rng):+ super().reset(kn, side, rng)+ self.wall = np.zeros(self.n)+ self.wrec = np.zeros(self.n)+ self.score = {m: 0.0 for m in self.models}+ self._preds = {}+ Q = -self.P.T # Q[a, k]: the other's net when it plays a against my k+ self.other_brs = [np.flatnonzero(Q[:, k] >= Q[:, k].max() - 1e-9) for k in range(self.n)]++ def _point(self, k):+ """80 % on k (or spread over the tied set k), 20 % spread"""+ p = np.full(self.n, 0.2 / self.n)+ if np.ndim(k):+ p[k] += 0.8 / len(k)+ else:+ p[k] += 0.8+ return p++ def _predict(self):+ h, n = self.hist, self.n+ out = {}+ for m in self.models:+ if m == "marg":+ p = self.wall + 0.5+ out[m] = p / p.sum()+ elif m == "recent":+ p = self.wrec + 0.3+ out[m] = p / p.sum()+ elif not h:+ continue+ elif m == "repeat":+ out[m] = self._point(h[-1][1])+ elif m == "counter":+ out[m] = self._point(self.other_brs[h[-1][0]])+ elif m == "copy":+ out[m] = self._point(h[-1][0])+ elif m == "winner":+ mine, other, res = h[-1]+ out[m] = self._point(mine if res == -1 else other)+ elif m == "seq" and len(h) >= 2:+ out[m] = self._point((2 * h[-1][1] - h[-2][1]) % n)+ return out++ def dist(self):+ self._preds = self._predict()+ best = max(self._preds, key=lambda m: (self.score[m], m == "marg"))+ v = self.P @ self._preds[best]+ if self.beta is None:+ core = (v >= v.max() - 1e-9).astype(float)+ else:+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ hp = self.wall + self.habit_prior+ hv = self.P @ (hp / hp.sum())+ habit = (hv >= hv.max() - 1e-9).astype(float)+ habit /= habit.sum()+ return self.h * habit + self.eps_eq * self.eq + (1.0 - self.h - self.eps_eq) * core++ def choose(self, score):+ return sample(self.dist(), self.rng)++ def observe(self, mine, other, res):+ for m, p in self._preds.items():+ self.score[m] = self.score_decay * self.score[m] + math.log(p[other])+ super().observe(mine, other, res)+ self.wall[other] += 1.0+ self.wrec *= 0.7+ self.wrec[other] += 1.0+++def make_level(level):+ s = dict(LEVELS[level])+ fam, desc = s.pop("family"), s.pop("desc")+ return {"models": Models, "ctx": Context, "mind": Mind}[fam](f"level {level}", desc, **s)+++class Opponent:+ """the scripted fencer at a level, the second fencer (side 1) of the bout"""++ def __init__(self, level, seed, kn):+ self.level = int(level)+ self.p = make_level(self.level)+ self.p.reset(kn, 1, np.random.default_rng([int(seed), 13]))++ def choose(self, score):+ return self.p.choose(score)++ def observe(self, mine, other, res):+ self.p.observe(mine, other, res)++ def state(self):+ return dict(level=self.level, hist=self.p.hist, rng=self.p.rng.bit_generator.state)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases.pynew file mode 100644index 0000000000..c54080437a--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases.py@@ -0,0 +1,120 @@+"""The world of the phrase-level sport (fencing-7): every phrase of the bout is one of the phrases measured in the+fencing-6 world, looked up in a table.++A phrase starts with both fencers on guard GAP_M apart (pelvis to pelvis). Each fencer has chosen one intention+(INTENTIONS), a fixed skill on the robot: the Unitree G1 of the robot library with its epee, its legs, waist and+left arm driven by NVIDIA's SONIC whole-body policy tracking our own fencing motions (en garde, steps, lunge), its+sword arm by the point skill. Each fencer starts its intention after a delay of 0, 10, ... 50 ms (JITTER_STEPS control+steps, drawn for each phrase from the seed); the phrase ends at the first touch (the electric apparatus and the+45 ms lockout of fencing-6's phrase referee) or after MAX_S without one. In that world a phrase's outcome is a function+of the two intentions and the two delays alone (every phrase measured more than once gave the same result at the same+step), so the 9 x 9 x 6 x 6 = 2916 phrases were each played once (docs/screening/fencing/phrase/: the generator, the+determinism check) and the bout replays them from phrases/table.json.++The two ends of the piste are not exactly alike in the simulation (the same phrase fenced from the other end ends+differently in about one case in seven), so each phrase also draws the end each fencer fences from: the first fencer+(seat A in format bout, the first player in format duel) is on the table's end A with probability 1/2. Both fencers+therefore meet the same chances, and a fencer's chances against an intention are the table's counts over both ends+(Table.counts: out of 2 x 36 phrases).++phrases/frames.npz keeps two frames of every phrase (the joint positions half-way and at the end) for the cameras."""+from __future__ import annotations++import hashlib+import json+import os++import numpy as np++HERE = os.path.dirname(os.path.abspath(__file__))+DATA = os.path.join(HERE, "phrases")+INTENTIONS = ("lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw")+OUTCOMES = ("A", "B", "AB", "none") # the table's ends: a touch for A alone, for B alone, a double, none+STEP_S = 0.01 # the control step: a delay step, the halt step k+++class Table:+ """phrases/table.json: {"intentions", "gap_m", "jitter_steps", "max_s", "source", "phrases": [[a, b, dA, dB, res,+ k, why], ...]} (k: the control step of the halt, null for a phrase cut at max_s)"""++ def __init__(self, path=DATA):+ with open(os.path.join(path, "table.json"), "rb") as f:+ raw = f.read()+ self.sha = hashlib.sha256(raw).hexdigest()+ d = json.loads(raw)+ self.names = tuple(d["intentions"])+ if self.names != INTENTIONS:+ raise ValueError(f"table intentions {self.names} != {INTENTIONS}")+ self.idx = {s: i for i, s in enumerate(self.names)}+ self.J = int(d["jitter_steps"])+ self.gap_m, self.max_s = float(d["gap_m"]), float(d["max_s"])+ self.meta = {k: d[k] for k in ("gap_m", "jitter_steps", "max_s", "source") if k in d}+ self.row: dict = {}+ for n, (a, b, dA, dB, res, k, why) in enumerate(d["phrases"]):+ self.row[(a, b, int(dA), int(dB))] = (n, res, k, why)+ want = len(self.names) ** 2 * self.J ** 2+ if len(self.row) != want or any(r[1] not in OUTCOMES for r in self.row.values()):+ raise ValueError(f"table has {len(self.row)} phrases, needs {want} with outcomes in {OUTCOMES}")+ self.path = path+ self._frames = None++ def seconds(self, k):+ return self.max_s if k is None else (k + 1) * STEP_S++ def get(self, a, b, dA, dB):+ """the phrase with A's intention a after dA steps and B's b after dB: {res, k, why, s, row}"""+ n, res, k, why = self.row[(a, b, dA, dB)]+ return dict(res=res, k=k, why=why, s=round(self.seconds(k), 2), row=n)++ def counts(self):+ """C[i, j] = [touches for me alone, for the other alone, doubles, none] when I play i and the other j, over+ both ends and all delays (2 J^2 phrases)"""+ n = len(self.names)+ C = np.zeros((n, n, 4))+ for (a, b, _, _), (_, res, _, _) in self.row.items():+ i, j, o = self.idx[a], self.idx[b], OUTCOMES.index(res)+ C[i, j, o] += 1 # I am on end A+ C[j, i, (1, 0, 2, 3)[o]] += 1 # I am on end B: A's touch is the other's+ return C++ def frames(self, row):+ """(steps [2], qpos [2, nq]) of the phrase's two frames (half-way, the end), on the table's ends"""+ if self._frames is None:+ z = np.load(os.path.join(self.path, "frames.npz"))+ self._frames = (z["steps"], z["qpos"], z["guard"])+ return self._frames[0][row], self._frames[1][row]++ def guard_qpos(self):+ """both fencers on guard GAP_M apart, before the first phrase"""+ self.frames(0)+ return self._frames[2]+++_TABLE: dict = {}+++def table(path=DATA) -> Table:+ if path not in _TABLE:+ _TABLE[path] = Table(path)+ return _TABLE[path]+++def draw(seed, n, J):+ """phrase n's chance: (the first fencer's delay, the second's, the first on the table's end A)"""+ g = np.random.default_rng([int(seed), 21, int(n)])+ d = g.integers(0, J, 2)+ return int(d[0]), int(d[1]), bool(g.random() < 0.5)+++def play(t: Table, i_first, i_second, seed, n):+ """phrase n with the first fencer's intention i_first and the second's i_second (names): the table's phrase with+ this phrase's delays and ends; res from the first fencer's view: 'first' | 'second' | 'double' | 'none'"""+ d1, d2, first_on_a = draw(seed, n, t.J)+ if first_on_a:+ p = t.get(i_first, i_second, d1, d2)+ res = {"A": "first", "B": "second", "AB": "double", "none": "none"}[p["res"]]+ else:+ p = t.get(i_second, i_first, d2, d1)+ res = {"A": "second", "B": "first", "AB": "double", "none": "none"}[p["res"]]+ return dict(res=res, k=p["k"], why=p["why"], s=p["s"], row=p["row"], first_delay_ms=10 * d1,+ second_delay_ms=10 * d2, first_end="A" if first_on_a else "B")diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases/frames.npz b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases/frames.npznew file mode 100644index 0000000000..19eee9e93cBinary files /dev/null and b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases/frames.npz differdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases/table.json b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases/table.jsonnew file mode 100644index 0000000000..ec54ddb263--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/phrases/table.json@@ -0,0 +1,2918 @@+{"source": "exact.py: every phrase played once in the fencing-6 world (frozen copy of fencing-screen 6711a4f4), SONIC skills (tactic.py), gap 1.95 m", "gap_m": 1.95, "jitter_steps": 6, "max_s": 3.0, "intentions": ["lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw"], "phrases": [+["lunge", "lunge", 0, 0, "none", null, "time"],+["lunge", "lunge", 0, 1, "A", 168, "touch"],+["lunge", "lunge", 0, 2, "AB", 181, "touch"],+["lunge", "lunge", 0, 3, "A", 182, "touch"],+["lunge", "lunge", 0, 4, "none", null, "time"],+["lunge", "lunge", 0, 5, "B", 185, "touch"],+["lunge", "lunge", 1, 0, "none", null, "time"],+["lunge", "lunge", 1, 1, "none", null, "time"],+["lunge", "lunge", 1, 2, "none", null, "time"],+["lunge", "lunge", 1, 3, "none", null, "time"],+["lunge", "lunge", 1, 4, "none", null, "time"],+["lunge", "lunge", 1, 5, "none", null, "time"],+["lunge", "lunge", 2, 0, "none", null, "time"],+["lunge", "lunge", 2, 1, "none", null, "time"],+["lunge", "lunge", 2, 2, "B", 246, "touch"],+["lunge", "lunge", 2, 3, "none", null, "time"],+["lunge", "lunge", 2, 4, "B", 218, "touch"],+["lunge", "lunge", 2, 5, "A", 171, "touch"],+["lunge", "lunge", 3, 0, "A", 47, "touch"],+["lunge", "lunge", 3, 1, "B", 166, "touch"],+["lunge", "lunge", 3, 2, "A", 186, "touch"],+["lunge", "lunge", 3, 3, "A", 170, "touch"],+["lunge", "lunge", 3, 4, "none", null, "time"],+["lunge", "lunge", 3, 5, "none", null, "time"],+["lunge", "lunge", 4, 0, "none", null, "time"],+["lunge", "lunge", 4, 1, "none", null, "time"],+["lunge", "lunge", 4, 2, "B", 239, "touch"],+["lunge", "lunge", 4, 3, "none", null, "time"],+["lunge", "lunge", 4, 4, "none", null, "time"],+["lunge", "lunge", 4, 5, "none", null, "time"],+["lunge", "lunge", 5, 0, "A", 47, "touch"],+["lunge", "lunge", 5, 1, "none", null, "time"],+["lunge", "lunge", 5, 2, "B", 170, "touch"],+["lunge", "lunge", 5, 3, "none", null, "time"],+["lunge", "lunge", 5, 4, "none", null, "time"],+["lunge", "lunge", 5, 5, "A", 169, "touch"],+["lunge", "low", 0, 0, "AB", 39, "touch"],+["lunge", "low", 0, 1, "AB", 39, "touch"],+["lunge", "low", 0, 2, "AB", 40, "touch"],+["lunge", "low", 0, 3, "AB", 41, "touch"],+["lunge", "low", 0, 4, "AB", 42, "touch"],+["lunge", "low", 0, 5, "AB", 42, "touch"],+["lunge", "low", 1, 0, "AB", 39, "touch"],+["lunge", "low", 1, 1, "AB", 40, "touch"],+["lunge", "low", 1, 2, "AB", 41, "touch"],+["lunge", "low", 1, 3, "AB", 41, "touch"],+["lunge", "low", 1, 4, "AB", 42, "touch"],+["lunge", "low", 1, 5, "AB", 43, "touch"],+["lunge", "low", 2, 0, "AB", 39, "touch"],+["lunge", "low", 2, 1, "AB", 40, "touch"],+["lunge", "low", 2, 2, "AB", 41, "touch"],+["lunge", "low", 2, 3, "AB", 41, "touch"],+["lunge", "low", 2, 4, "AB", 42, "touch"],+["lunge", "low", 2, 5, "AB", 43, "touch"],+["lunge", "low", 3, 0, "AB", 41, "touch"],+["lunge", "low", 3, 1, "AB", 42, "touch"],+["lunge", "low", 3, 2, "AB", 41, "touch"],+["lunge", "low", 3, 3, "AB", 42, "touch"],+["lunge", "low", 3, 4, "AB", 43, "touch"],+["lunge", "low", 3, 5, "AB", 43, "touch"],+["lunge", "low", 4, 0, "AB", 40, "touch"],+["lunge", "low", 4, 1, "AB", 40, "touch"],+["lunge", "low", 4, 2, "AB", 41, "touch"],+["lunge", "low", 4, 3, "AB", 42, "touch"],+["lunge", "low", 4, 4, "AB", 43, "touch"],+["lunge", "low", 4, 5, "AB", 43, "touch"],+["lunge", "low", 5, 0, "A", 45, "touch"],+["lunge", "low", 5, 1, "AB", 42, "touch"],+["lunge", "low", 5, 2, "AB", 42, "touch"],+["lunge", "low", 5, 3, "AB", 43, "touch"],+["lunge", "low", 5, 4, "AB", 44, "touch"],+["lunge", "low", 5, 5, "AB", 44, "touch"],+["lunge", "line", 0, 0, "B", 31, "touch"],+["lunge", "line", 0, 1, "A", 154, "touch"],+["lunge", "line", 0, 2, "A", 136, "touch"],+["lunge", "line", 0, 3, "none", null, "time"],+["lunge", "line", 0, 4, "A", 31, "touch"],+["lunge", "line", 0, 5, "A", 31, "touch"],+["lunge", "line", 1, 0, "A", 71, "touch"],+["lunge", "line", 1, 1, "A", 69, "touch"],+["lunge", "line", 1, 2, "B", 33, "touch"],+["lunge", "line", 1, 3, "A", 69, "touch"],+["lunge", "line", 1, 4, "A", 70, "touch"],+["lunge", "line", 1, 5, "A", 70, "touch"],+["lunge", "line", 2, 0, "B", 32, "touch"],+["lunge", "line", 2, 1, "A", 77, "touch"],+["lunge", "line", 2, 2, "B", 33, "touch"],+["lunge", "line", 2, 3, "A", 135, "touch"],+["lunge", "line", 2, 4, "A", 136, "touch"],+["lunge", "line", 2, 5, "A", 138, "touch"],+["lunge", "line", 3, 0, "A", 73, "touch"],+["lunge", "line", 3, 1, "A", 72, "touch"],+["lunge", "line", 3, 2, "A", 73, "touch"],+["lunge", "line", 3, 3, "A", 72, "touch"],+["lunge", "line", 3, 4, "A", 72, "touch"],+["lunge", "line", 3, 5, "A", 72, "touch"],+["lunge", "line", 4, 0, "A", 82, "touch"],+["lunge", "line", 4, 1, "none", null, "time"],+["lunge", "line", 4, 2, "B", 34, "touch"],+["lunge", "line", 4, 3, "B", 34, "touch"],+["lunge", "line", 4, 4, "B", 35, "touch"],+["lunge", "line", 4, 5, "A", 140, "touch"],+["lunge", "line", 5, 0, "A", 75, "touch"],+["lunge", "line", 5, 1, "A", 74, "touch"],+["lunge", "line", 5, 2, "A", 75, "touch"],+["lunge", "line", 5, 3, "A", 74, "touch"],+["lunge", "line", 5, 4, "A", 74, "touch"],+["lunge", "line", 5, 5, "A", 74, "touch"],+["lunge", "rline", 0, 0, "B", 124, "touch"],+["lunge", "rline", 0, 1, "B", 124, "touch"],+["lunge", "rline", 0, 2, "B", 124, "touch"],+["lunge", "rline", 0, 3, "B", 124, "touch"],+["lunge", "rline", 0, 4, "B", 124, "touch"],+["lunge", "rline", 0, 5, "B", 124, "touch"],+["lunge", "rline", 1, 0, "none", null, "time"],+["lunge", "rline", 1, 1, "none", null, "time"],+["lunge", "rline", 1, 2, "none", null, "time"],+["lunge", "rline", 1, 3, "none", null, "time"],+["lunge", "rline", 1, 4, "none", null, "time"],+["lunge", "rline", 1, 5, "none", null, "time"],+["lunge", "rline", 2, 0, "none", null, "time"],+["lunge", "rline", 2, 1, "none", null, "time"],+["lunge", "rline", 2, 2, "none", null, "time"],+["lunge", "rline", 2, 3, "none", null, "time"],+["lunge", "rline", 2, 4, "none", null, "time"],+["lunge", "rline", 2, 5, "none", null, "time"],+["lunge", "rline", 3, 0, "A", 80, "touch"],+["lunge", "rline", 3, 1, "A", 80, "touch"],+["lunge", "rline", 3, 2, "A", 80, "touch"],+["lunge", "rline", 3, 3, "A", 80, "touch"],+["lunge", "rline", 3, 4, "A", 80, "touch"],+["lunge", "rline", 3, 5, "A", 80, "touch"],+["lunge", "rline", 4, 0, "B", 98, "touch"],+["lunge", "rline", 4, 1, "B", 98, "touch"],+["lunge", "rline", 4, 2, "B", 98, "touch"],+["lunge", "rline", 4, 3, "B", 98, "touch"],+["lunge", "rline", 4, 4, "B", 98, "touch"],+["lunge", "rline", 4, 5, "B", 98, "touch"],+["lunge", "rline", 5, 0, "A", 81, "touch"],+["lunge", "rline", 5, 1, "A", 81, "touch"],+["lunge", "rline", 5, 2, "A", 81, "touch"],+["lunge", "rline", 5, 3, "A", 81, "touch"],+["lunge", "rline", 5, 4, "A", 81, "touch"],+["lunge", "rline", 5, 5, "A", 81, "touch"],+["lunge", "stop", 0, 0, "A", 75, "touch"],+["lunge", "stop", 0, 1, "A", 75, "touch"],+["lunge", "stop", 0, 2, "A", 75, "touch"],+["lunge", "stop", 0, 3, "A", 75, "touch"],+["lunge", "stop", 0, 4, "A", 75, "touch"],+["lunge", "stop", 0, 5, "A", 75, "touch"],+["lunge", "stop", 1, 0, "A", 71, "touch"],+["lunge", "stop", 1, 1, "A", 71, "touch"],+["lunge", "stop", 1, 2, "A", 71, "touch"],+["lunge", "stop", 1, 3, "A", 71, "touch"],+["lunge", "stop", 1, 4, "A", 71, "touch"],+["lunge", "stop", 1, 5, "A", 71, "touch"],+["lunge", "stop", 2, 0, "A", 76, "touch"],+["lunge", "stop", 2, 1, "A", 76, "touch"],+["lunge", "stop", 2, 2, "A", 76, "touch"],+["lunge", "stop", 2, 3, "A", 76, "touch"],+["lunge", "stop", 2, 4, "A", 76, "touch"],+["lunge", "stop", 2, 5, "A", 76, "touch"],+["lunge", "stop", 3, 0, "A", 73, "touch"],+["lunge", "stop", 3, 1, "A", 73, "touch"],+["lunge", "stop", 3, 2, "A", 73, "touch"],+["lunge", "stop", 3, 3, "A", 73, "touch"],+["lunge", "stop", 3, 4, "A", 73, "touch"],+["lunge", "stop", 3, 5, "A", 73, "touch"],+["lunge", "stop", 4, 0, "A", 79, "touch"],+["lunge", "stop", 4, 1, "A", 79, "touch"],+["lunge", "stop", 4, 2, "A", 79, "touch"],+["lunge", "stop", 4, 3, "A", 79, "touch"],+["lunge", "stop", 4, 4, "A", 79, "touch"],+["lunge", "stop", 4, 5, "A", 79, "touch"],+["lunge", "stop", 5, 0, "A", 75, "touch"],+["lunge", "stop", 5, 1, "A", 75, "touch"],+["lunge", "stop", 5, 2, "A", 75, "touch"],+["lunge", "stop", 5, 3, "A", 75, "touch"],+["lunge", "stop", 5, 4, "A", 75, "touch"],+["lunge", "stop", 5, 5, "A", 75, "touch"],+["lunge", "counter", 0, 0, "B", 55, "touch"],+["lunge", "counter", 0, 1, "B", 55, "touch"],+["lunge", "counter", 0, 2, "B", 55, "touch"],+["lunge", "counter", 0, 3, "B", 55, "touch"],+["lunge", "counter", 0, 4, "B", 55, "touch"],+["lunge", "counter", 0, 5, "B", 55, "touch"],+["lunge", "counter", 1, 0, "B", 54, "touch"],+["lunge", "counter", 1, 1, "B", 54, "touch"],+["lunge", "counter", 1, 2, "B", 54, "touch"],+["lunge", "counter", 1, 3, "B", 54, "touch"],+["lunge", "counter", 1, 4, "B", 54, "touch"],+["lunge", "counter", 1, 5, "B", 54, "touch"],+["lunge", "counter", 2, 0, "B", 57, "touch"],+["lunge", "counter", 2, 1, "B", 57, "touch"],+["lunge", "counter", 2, 2, "B", 57, "touch"],+["lunge", "counter", 2, 3, "B", 57, "touch"],+["lunge", "counter", 2, 4, "B", 57, "touch"],+["lunge", "counter", 2, 5, "B", 57, "touch"],+["lunge", "counter", 3, 0, "B", 55, "touch"],+["lunge", "counter", 3, 1, "B", 55, "touch"],+["lunge", "counter", 3, 2, "B", 55, "touch"],+["lunge", "counter", 3, 3, "B", 55, "touch"],+["lunge", "counter", 3, 4, "B", 55, "touch"],+["lunge", "counter", 3, 5, "B", 55, "touch"],+["lunge", "counter", 4, 0, "B", 57, "touch"],+["lunge", "counter", 4, 1, "B", 57, "touch"],+["lunge", "counter", 4, 2, "B", 57, "touch"],+["lunge", "counter", 4, 3, "B", 57, "touch"],+["lunge", "counter", 4, 4, "B", 57, "touch"],+["lunge", "counter", 4, 5, "B", 57, "touch"],+["lunge", "counter", 5, 0, "B", 58, "touch"],+["lunge", "counter", 5, 1, "B", 58, "touch"],+["lunge", "counter", 5, 2, "B", 58, "touch"],+["lunge", "counter", 5, 3, "B", 58, "touch"],+["lunge", "counter", 5, 4, "B", 58, "touch"],+["lunge", "counter", 5, 5, "B", 58, "touch"],+["lunge", "delay", 0, 0, "B", 69, "touch"],+["lunge", "delay", 0, 1, "B", 70, "touch"],+["lunge", "delay", 0, 2, "B", 71, "touch"],+["lunge", "delay", 0, 3, "AB", 67, "touch"],+["lunge", "delay", 0, 4, "AB", 68, "touch"],+["lunge", "delay", 0, 5, "AB", 69, "touch"],+["lunge", "delay", 1, 0, "AB", 64, "touch"],+["lunge", "delay", 1, 1, "AB", 65, "touch"],+["lunge", "delay", 1, 2, "AB", 66, "touch"],+["lunge", "delay", 1, 3, "AB", 68, "touch"],+["lunge", "delay", 1, 4, "AB", 68, "touch"],+["lunge", "delay", 1, 5, "A", 69, "touch"],+["lunge", "delay", 2, 0, "B", 68, "touch"],+["lunge", "delay", 2, 1, "B", 70, "touch"],+["lunge", "delay", 2, 2, "B", 71, "touch"],+["lunge", "delay", 2, 3, "B", 72, "touch"],+["lunge", "delay", 2, 4, "B", 73, "touch"],+["lunge", "delay", 2, 5, "AB", 69, "touch"],+["lunge", "delay", 3, 0, "B", 69, "touch"],+["lunge", "delay", 3, 1, "B", 70, "touch"],+["lunge", "delay", 3, 2, "B", 71, "touch"],+["lunge", "delay", 3, 3, "AB", 67, "touch"],+["lunge", "delay", 3, 4, "AB", 68, "touch"],+["lunge", "delay", 3, 5, "AB", 69, "touch"],+["lunge", "delay", 4, 0, "B", 69, "touch"],+["lunge", "delay", 4, 1, "B", 70, "touch"],+["lunge", "delay", 4, 2, "B", 71, "touch"],+["lunge", "delay", 4, 3, "B", 72, "touch"],+["lunge", "delay", 4, 4, "B", 73, "touch"],+["lunge", "delay", 4, 5, "B", 74, "touch"],+["lunge", "delay", 5, 0, "B", 69, "touch"],+["lunge", "delay", 5, 1, "B", 70, "touch"],+["lunge", "delay", 5, 2, "B", 71, "touch"],+["lunge", "delay", 5, 3, "B", 72, "touch"],+["lunge", "delay", 5, 4, "B", 72, "touch"],+["lunge", "delay", 5, 5, "AB", 70, "touch"],+["lunge", "retreat", 0, 0, "none", null, "time"],+["lunge", "retreat", 0, 1, "A", 73, "touch"],+["lunge", "retreat", 0, 2, "A", 73, "touch"],+["lunge", "retreat", 0, 3, "none", null, "time"],+["lunge", "retreat", 0, 4, "none", null, "time"],+["lunge", "retreat", 0, 5, "A", 72, "touch"],+["lunge", "retreat", 1, 0, "A", 69, "touch"],+["lunge", "retreat", 1, 1, "A", 69, "touch"],+["lunge", "retreat", 1, 2, "A", 69, "touch"],+["lunge", "retreat", 1, 3, "A", 69, "touch"],+["lunge", "retreat", 1, 4, "A", 69, "touch"],+["lunge", "retreat", 1, 5, "A", 68, "touch"],+["lunge", "retreat", 2, 0, "none", null, "time"],+["lunge", "retreat", 2, 1, "A", 75, "touch"],+["lunge", "retreat", 2, 2, "A", 75, "touch"],+["lunge", "retreat", 2, 3, "none", null, "time"],+["lunge", "retreat", 2, 4, "none", null, "time"],+["lunge", "retreat", 2, 5, "none", null, "time"],+["lunge", "retreat", 3, 0, "A", 72, "touch"],+["lunge", "retreat", 3, 1, "A", 71, "touch"],+["lunge", "retreat", 3, 2, "A", 71, "touch"],+["lunge", "retreat", 3, 3, "A", 71, "touch"],+["lunge", "retreat", 3, 4, "A", 71, "touch"],+["lunge", "retreat", 3, 5, "A", 70, "touch"],+["lunge", "retreat", 4, 0, "none", null, "time"],+["lunge", "retreat", 4, 1, "none", null, "time"],+["lunge", "retreat", 4, 2, "none", null, "time"],+["lunge", "retreat", 4, 3, "none", null, "time"],+["lunge", "retreat", 4, 4, "none", null, "time"],+["lunge", "retreat", 4, 5, "none", null, "time"],+["lunge", "retreat", 5, 0, "A", 74, "touch"],+["lunge", "retreat", 5, 1, "A", 74, "touch"],+["lunge", "retreat", 5, 2, "A", 74, "touch"],+["lunge", "retreat", 5, 3, "A", 73, "touch"],+["lunge", "retreat", 5, 4, "A", 73, "touch"],+["lunge", "retreat", 5, 5, "A", 73, "touch"],+["lunge", "draw", 0, 0, "A", 73, "touch"],+["lunge", "draw", 0, 1, "A", 73, "touch"],+["lunge", "draw", 0, 2, "A", 73, "touch"],+["lunge", "draw", 0, 3, "A", 73, "touch"],+["lunge", "draw", 0, 4, "A", 73, "touch"],+["lunge", "draw", 0, 5, "A", 131, "touch"],+["lunge", "draw", 1, 0, "A", 70, "touch"],+["lunge", "draw", 1, 1, "A", 70, "touch"],+["lunge", "draw", 1, 2, "A", 70, "touch"],+["lunge", "draw", 1, 3, "A", 70, "touch"],+["lunge", "draw", 1, 4, "A", 70, "touch"],+["lunge", "draw", 1, 5, "A", 70, "touch"],+["lunge", "draw", 2, 0, "B", 96, "touch"],+["lunge", "draw", 2, 1, "A", 75, "touch"],+["lunge", "draw", 2, 2, "A", 75, "touch"],+["lunge", "draw", 2, 3, "A", 75, "touch"],+["lunge", "draw", 2, 4, "A", 75, "touch"],+["lunge", "draw", 2, 5, "A", 75, "touch"],+["lunge", "draw", 3, 0, "B", 62, "touch"],+["lunge", "draw", 3, 1, "B", 62, "touch"],+["lunge", "draw", 3, 2, "B", 62, "touch"],+["lunge", "draw", 3, 3, "A", 72, "touch"],+["lunge", "draw", 3, 4, "A", 72, "touch"],+["lunge", "draw", 3, 5, "A", 72, "touch"],+["lunge", "draw", 4, 0, "A", 76, "touch"],+["lunge", "draw", 4, 1, "B", 97, "touch"],+["lunge", "draw", 4, 2, "B", 97, "touch"],+["lunge", "draw", 4, 3, "A", 75, "touch"],+["lunge", "draw", 4, 4, "A", 75, "touch"],+["lunge", "draw", 4, 5, "A", 76, "touch"],+["lunge", "draw", 5, 0, "A", 74, "touch"],+["lunge", "draw", 5, 1, "B", 63, "touch"],+["lunge", "draw", 5, 2, "B", 63, "touch"],+["lunge", "draw", 5, 3, "B", 64, "touch"],+["lunge", "draw", 5, 4, "B", 64, "touch"],+["lunge", "draw", 5, 5, "A", 74, "touch"],+["low", "lunge", 0, 0, "AB", 39, "touch"],+["low", "lunge", 0, 1, "AB", 40, "touch"],+["low", "lunge", 0, 2, "AB", 39, "touch"],+["low", "lunge", 0, 3, "AB", 40, "touch"],+["low", "lunge", 0, 4, "AB", 40, "touch"],+["low", "lunge", 0, 5, "B", 46, "touch"],+["low", "lunge", 1, 0, "AB", 39, "touch"],+["low", "lunge", 1, 1, "AB", 40, "touch"],+["low", "lunge", 1, 2, "AB", 40, "touch"],+["low", "lunge", 1, 3, "AB", 41, "touch"],+["low", "lunge", 1, 4, "AB", 40, "touch"],+["low", "lunge", 1, 5, "AB", 42, "touch"],+["low", "lunge", 2, 0, "AB", 40, "touch"],+["low", "lunge", 2, 1, "AB", 41, "touch"],+["low", "lunge", 2, 2, "AB", 41, "touch"],+["low", "lunge", 2, 3, "AB", 41, "touch"],+["low", "lunge", 2, 4, "AB", 41, "touch"],+["low", "lunge", 2, 5, "AB", 42, "touch"],+["low", "lunge", 3, 0, "AB", 41, "touch"],+["low", "lunge", 3, 1, "AB", 41, "touch"],+["low", "lunge", 3, 2, "AB", 42, "touch"],+["low", "lunge", 3, 3, "AB", 42, "touch"],+["low", "lunge", 3, 4, "AB", 42, "touch"],+["low", "lunge", 3, 5, "AB", 43, "touch"],+["low", "lunge", 4, 0, "AB", 42, "touch"],+["low", "lunge", 4, 1, "AB", 42, "touch"],+["low", "lunge", 4, 2, "AB", 42, "touch"],+["low", "lunge", 4, 3, "AB", 43, "touch"],+["low", "lunge", 4, 4, "AB", 43, "touch"],+["low", "lunge", 4, 5, "AB", 43, "touch"],+["low", "lunge", 5, 0, "AB", 42, "touch"],+["low", "lunge", 5, 1, "AB", 43, "touch"],+["low", "lunge", 5, 2, "AB", 43, "touch"],+["low", "lunge", 5, 3, "AB", 43, "touch"],+["low", "lunge", 5, 4, "AB", 43, "touch"],+["low", "lunge", 5, 5, "AB", 44, "touch"],+["low", "low", 0, 0, "AB", 37, "touch"],+["low", "low", 0, 1, "B", 42, "touch"],+["low", "low", 0, 2, "AB", 38, "touch"],+["low", "low", 0, 3, "B", 43, "touch"],+["low", "low", 0, 4, "AB", 39, "touch"],+["low", "low", 0, 5, "A", 44, "touch"],+["low", "low", 1, 0, "AB", 38, "touch"],+["low", "low", 1, 1, "AB", 39, "touch"],+["low", "low", 1, 2, "AB", 39, "touch"],+["low", "low", 1, 3, "AB", 39, "touch"],+["low", "low", 1, 4, "AB", 40, "touch"],+["low", "low", 1, 5, "AB", 40, "touch"],+["low", "low", 2, 0, "AB", 38, "touch"],+["low", "low", 2, 1, "AB", 40, "touch"],+["low", "low", 2, 2, "AB", 39, "touch"],+["low", "low", 2, 3, "AB", 40, "touch"],+["low", "low", 2, 4, "AB", 40, "touch"],+["low", "low", 2, 5, "AB", 41, "touch"],+["low", "low", 3, 0, "AB", 38, "touch"],+["low", "low", 3, 1, "AB", 39, "touch"],+["low", "low", 3, 2, "AB", 40, "touch"],+["low", "low", 3, 3, "AB", 40, "touch"],+["low", "low", 3, 4, "AB", 41, "touch"],+["low", "low", 3, 5, "AB", 42, "touch"],+["low", "low", 4, 0, "AB", 39, "touch"],+["low", "low", 4, 1, "AB", 40, "touch"],+["low", "low", 4, 2, "AB", 40, "touch"],+["low", "low", 4, 3, "AB", 41, "touch"],+["low", "low", 4, 4, "AB", 41, "touch"],+["low", "low", 4, 5, "AB", 42, "touch"],+["low", "low", 5, 0, "A", 44, "touch"],+["low", "low", 5, 1, "AB", 40, "touch"],+["low", "low", 5, 2, "AB", 41, "touch"],+["low", "low", 5, 3, "AB", 41, "touch"],+["low", "low", 5, 4, "AB", 41, "touch"],+["low", "low", 5, 5, "AB", 42, "touch"],+["low", "line", 0, 0, "none", null, "time"],+["low", "line", 0, 1, "none", null, "time"],+["low", "line", 0, 2, "A", 147, "touch"],+["low", "line", 0, 3, "none", null, "time"],+["low", "line", 0, 4, "A", 149, "touch"],+["low", "line", 0, 5, "none", null, "time"],+["low", "line", 1, 0, "none", null, "time"],+["low", "line", 1, 1, "A", 160, "touch"],+["low", "line", 1, 2, "A", 119, "touch"],+["low", "line", 1, 3, "A", 169, "touch"],+["low", "line", 1, 4, "A", 156, "touch"],+["low", "line", 1, 5, "A", 162, "touch"],+["low", "line", 2, 0, "none", null, "time"],+["low", "line", 2, 1, "none", null, "time"],+["low", "line", 2, 2, "A", 146, "touch"],+["low", "line", 2, 3, "none", null, "time"],+["low", "line", 2, 4, "A", 147, "touch"],+["low", "line", 2, 5, "none", null, "time"],+["low", "line", 3, 0, "none", null, "time"],+["low", "line", 3, 1, "A", 164, "touch"],+["low", "line", 3, 2, "A", 168, "touch"],+["low", "line", 3, 3, "none", null, "time"],+["low", "line", 3, 4, "none", null, "time"],+["low", "line", 3, 5, "A", 164, "touch"],+["low", "line", 4, 0, "none", null, "time"],+["low", "line", 4, 1, "none", null, "time"],+["low", "line", 4, 2, "none", null, "time"],+["low", "line", 4, 3, "A", 157, "touch"],+["low", "line", 4, 4, "A", 151, "touch"],+["low", "line", 4, 5, "A", 165, "touch"],+["low", "line", 5, 0, "A", 174, "touch"],+["low", "line", 5, 1, "A", 166, "touch"],+["low", "line", 5, 2, "A", 169, "touch"],+["low", "line", 5, 3, "none", null, "time"],+["low", "line", 5, 4, "A", 172, "touch"],+["low", "line", 5, 5, "none", null, "time"],+["low", "rline", 0, 0, "none", null, "time"],+["low", "rline", 0, 1, "none", null, "time"],+["low", "rline", 0, 2, "none", null, "time"],+["low", "rline", 0, 3, "none", null, "time"],+["low", "rline", 0, 4, "none", null, "time"],+["low", "rline", 0, 5, "none", null, "time"],+["low", "rline", 1, 0, "B", 89, "touch"],+["low", "rline", 1, 1, "B", 89, "touch"],+["low", "rline", 1, 2, "B", 89, "touch"],+["low", "rline", 1, 3, "B", 89, "touch"],+["low", "rline", 1, 4, "B", 89, "touch"],+["low", "rline", 1, 5, "B", 89, "touch"],+["low", "rline", 2, 0, "A", 149, "touch"],+["low", "rline", 2, 1, "A", 149, "touch"],+["low", "rline", 2, 2, "A", 149, "touch"],+["low", "rline", 2, 3, "A", 149, "touch"],+["low", "rline", 2, 4, "A", 149, "touch"],+["low", "rline", 2, 5, "A", 149, "touch"],+["low", "rline", 3, 0, "B", 94, "touch"],+["low", "rline", 3, 1, "B", 94, "touch"],+["low", "rline", 3, 2, "B", 94, "touch"],+["low", "rline", 3, 3, "B", 94, "touch"],+["low", "rline", 3, 4, "B", 94, "touch"],+["low", "rline", 3, 5, "B", 94, "touch"],+["low", "rline", 4, 0, "none", null, "time"],+["low", "rline", 4, 1, "none", null, "time"],+["low", "rline", 4, 2, "none", null, "time"],+["low", "rline", 4, 3, "none", null, "time"],+["low", "rline", 4, 4, "none", null, "time"],+["low", "rline", 4, 5, "none", null, "time"],+["low", "rline", 5, 0, "B", 114, "touch"],+["low", "rline", 5, 1, "B", 114, "touch"],+["low", "rline", 5, 2, "B", 114, "touch"],+["low", "rline", 5, 3, "B", 114, "touch"],+["low", "rline", 5, 4, "B", 114, "touch"],+["low", "rline", 5, 5, "B", 114, "touch"],+["low", "stop", 0, 0, "B", 62, "touch"],+["low", "stop", 0, 1, "B", 62, "touch"],+["low", "stop", 0, 2, "B", 62, "touch"],+["low", "stop", 0, 3, "B", 62, "touch"],+["low", "stop", 0, 4, "B", 62, "touch"],+["low", "stop", 0, 5, "B", 62, "touch"],+["low", "stop", 1, 0, "A", 70, "touch"],+["low", "stop", 1, 1, "A", 70, "touch"],+["low", "stop", 1, 2, "A", 70, "touch"],+["low", "stop", 1, 3, "A", 70, "touch"],+["low", "stop", 1, 4, "A", 70, "touch"],+["low", "stop", 1, 5, "A", 70, "touch"],+["low", "stop", 2, 0, "A", 173, "touch"],+["low", "stop", 2, 1, "A", 173, "touch"],+["low", "stop", 2, 2, "A", 173, "touch"],+["low", "stop", 2, 3, "A", 173, "touch"],+["low", "stop", 2, 4, "A", 173, "touch"],+["low", "stop", 2, 5, "A", 173, "touch"],+["low", "stop", 3, 0, "B", 61, "touch"],+["low", "stop", 3, 1, "B", 61, "touch"],+["low", "stop", 3, 2, "B", 61, "touch"],+["low", "stop", 3, 3, "B", 61, "touch"],+["low", "stop", 3, 4, "B", 61, "touch"],+["low", "stop", 3, 5, "B", 61, "touch"],+["low", "stop", 4, 0, "B", 64, "touch"],+["low", "stop", 4, 1, "B", 64, "touch"],+["low", "stop", 4, 2, "B", 64, "touch"],+["low", "stop", 4, 3, "B", 64, "touch"],+["low", "stop", 4, 4, "B", 64, "touch"],+["low", "stop", 4, 5, "B", 64, "touch"],+["low", "stop", 5, 0, "B", 67, "touch"],+["low", "stop", 5, 1, "B", 67, "touch"],+["low", "stop", 5, 2, "B", 67, "touch"],+["low", "stop", 5, 3, "B", 67, "touch"],+["low", "stop", 5, 4, "B", 67, "touch"],+["low", "stop", 5, 5, "B", 67, "touch"],+["low", "counter", 0, 0, "B", 50, "touch"],+["low", "counter", 0, 1, "B", 50, "touch"],+["low", "counter", 0, 2, "B", 50, "touch"],+["low", "counter", 0, 3, "B", 50, "touch"],+["low", "counter", 0, 4, "B", 50, "touch"],+["low", "counter", 0, 5, "B", 50, "touch"],+["low", "counter", 1, 0, "B", 53, "touch"],+["low", "counter", 1, 1, "B", 53, "touch"],+["low", "counter", 1, 2, "B", 53, "touch"],+["low", "counter", 1, 3, "B", 53, "touch"],+["low", "counter", 1, 4, "B", 53, "touch"],+["low", "counter", 1, 5, "B", 53, "touch"],+["low", "counter", 2, 0, "B", 52, "touch"],+["low", "counter", 2, 1, "B", 52, "touch"],+["low", "counter", 2, 2, "B", 52, "touch"],+["low", "counter", 2, 3, "B", 52, "touch"],+["low", "counter", 2, 4, "B", 52, "touch"],+["low", "counter", 2, 5, "B", 52, "touch"],+["low", "counter", 3, 0, "B", 55, "touch"],+["low", "counter", 3, 1, "B", 55, "touch"],+["low", "counter", 3, 2, "B", 55, "touch"],+["low", "counter", 3, 3, "B", 55, "touch"],+["low", "counter", 3, 4, "B", 55, "touch"],+["low", "counter", 3, 5, "B", 55, "touch"],+["low", "counter", 4, 0, "B", 55, "touch"],+["low", "counter", 4, 1, "B", 55, "touch"],+["low", "counter", 4, 2, "B", 55, "touch"],+["low", "counter", 4, 3, "B", 55, "touch"],+["low", "counter", 4, 4, "B", 55, "touch"],+["low", "counter", 4, 5, "B", 55, "touch"],+["low", "counter", 5, 0, "B", 57, "touch"],+["low", "counter", 5, 1, "B", 57, "touch"],+["low", "counter", 5, 2, "B", 57, "touch"],+["low", "counter", 5, 3, "B", 57, "touch"],+["low", "counter", 5, 4, "B", 57, "touch"],+["low", "counter", 5, 5, "B", 57, "touch"],+["low", "delay", 0, 0, "B", 68, "touch"],+["low", "delay", 0, 1, "B", 70, "touch"],+["low", "delay", 0, 2, "B", 70, "touch"],+["low", "delay", 0, 3, "B", 71, "touch"],+["low", "delay", 0, 4, "B", 72, "touch"],+["low", "delay", 0, 5, "B", 73, "touch"],+["low", "delay", 1, 0, "B", 69, "touch"],+["low", "delay", 1, 1, "B", 70, "touch"],+["low", "delay", 1, 2, "B", 71, "touch"],+["low", "delay", 1, 3, "B", 72, "touch"],+["low", "delay", 1, 4, "B", 72, "touch"],+["low", "delay", 1, 5, "B", 73, "touch"],+["low", "delay", 2, 0, "B", 69, "touch"],+["low", "delay", 2, 1, "B", 70, "touch"],+["low", "delay", 2, 2, "B", 71, "touch"],+["low", "delay", 2, 3, "B", 71, "touch"],+["low", "delay", 2, 4, "B", 72, "touch"],+["low", "delay", 2, 5, "B", 73, "touch"],+["low", "delay", 3, 0, "B", 69, "touch"],+["low", "delay", 3, 1, "B", 69, "touch"],+["low", "delay", 3, 2, "B", 71, "touch"],+["low", "delay", 3, 3, "B", 72, "touch"],+["low", "delay", 3, 4, "B", 73, "touch"],+["low", "delay", 3, 5, "B", 73, "touch"],+["low", "delay", 4, 0, "B", 69, "touch"],+["low", "delay", 4, 1, "B", 70, "touch"],+["low", "delay", 4, 2, "B", 71, "touch"],+["low", "delay", 4, 3, "B", 72, "touch"],+["low", "delay", 4, 4, "B", 72, "touch"],+["low", "delay", 4, 5, "B", 73, "touch"],+["low", "delay", 5, 0, "B", 69, "touch"],+["low", "delay", 5, 1, "B", 70, "touch"],+["low", "delay", 5, 2, "B", 71, "touch"],+["low", "delay", 5, 3, "B", 72, "touch"],+["low", "delay", 5, 4, "B", 72, "touch"],+["low", "delay", 5, 5, "B", 74, "touch"],+["low", "retreat", 0, 0, "A", 49, "touch"],+["low", "retreat", 0, 1, "A", 49, "touch"],+["low", "retreat", 0, 2, "A", 49, "touch"],+["low", "retreat", 0, 3, "A", 49, "touch"],+["low", "retreat", 0, 4, "A", 49, "touch"],+["low", "retreat", 0, 5, "A", 49, "touch"],+["low", "retreat", 1, 0, "A", 85, "touch"],+["low", "retreat", 1, 1, "none", null, "time"],+["low", "retreat", 1, 2, "none", null, "time"],+["low", "retreat", 1, 3, "A", 88, "touch"],+["low", "retreat", 1, 4, "A", 88, "touch"],+["low", "retreat", 1, 5, "A", 91, "touch"],+["low", "retreat", 2, 0, "A", 52, "touch"],+["low", "retreat", 2, 1, "A", 51, "touch"],+["low", "retreat", 2, 2, "A", 51, "touch"],+["low", "retreat", 2, 3, "A", 51, "touch"],+["low", "retreat", 2, 4, "A", 51, "touch"],+["low", "retreat", 2, 5, "A", 51, "touch"],+["low", "retreat", 3, 0, "none", null, "time"],+["low", "retreat", 3, 1, "none", null, "time"],+["low", "retreat", 3, 2, "none", null, "time"],+["low", "retreat", 3, 3, "none", null, "time"],+["low", "retreat", 3, 4, "none", null, "time"],+["low", "retreat", 3, 5, "none", null, "time"],+["low", "retreat", 4, 0, "A", 54, "touch"],+["low", "retreat", 4, 1, "A", 54, "touch"],+["low", "retreat", 4, 2, "A", 54, "touch"],+["low", "retreat", 4, 3, "A", 53, "touch"],+["low", "retreat", 4, 4, "A", 53, "touch"],+["low", "retreat", 4, 5, "A", 53, "touch"],+["low", "retreat", 5, 0, "none", null, "time"],+["low", "retreat", 5, 1, "none", null, "time"],+["low", "retreat", 5, 2, "none", null, "time"],+["low", "retreat", 5, 3, "none", null, "time"],+["low", "retreat", 5, 4, "none", null, "time"],+["low", "retreat", 5, 5, "none", null, "time"],+["low", "draw", 0, 0, "B", 57, "touch"],+["low", "draw", 0, 1, "B", 58, "touch"],+["low", "draw", 0, 2, "B", 58, "touch"],+["low", "draw", 0, 3, "B", 60, "touch"],+["low", "draw", 0, 4, "B", 60, "touch"],+["low", "draw", 0, 5, "B", 60, "touch"],+["low", "draw", 1, 0, "A", 106, "touch"],+["low", "draw", 1, 1, "none", null, "time"],+["low", "draw", 1, 2, "none", null, "time"],+["low", "draw", 1, 3, "B", 59, "touch"],+["low", "draw", 1, 4, "B", 59, "touch"],+["low", "draw", 1, 5, "B", 60, "touch"],+["low", "draw", 2, 0, "B", 59, "touch"],+["low", "draw", 2, 1, "B", 60, "touch"],+["low", "draw", 2, 2, "B", 60, "touch"],+["low", "draw", 2, 3, "B", 61, "touch"],+["low", "draw", 2, 4, "B", 61, "touch"],+["low", "draw", 2, 5, "B", 61, "touch"],+["low", "draw", 3, 0, "B", 61, "touch"],+["low", "draw", 3, 1, "B", 59, "touch"],+["low", "draw", 3, 2, "B", 59, "touch"],+["low", "draw", 3, 3, "none", null, "time"],+["low", "draw", 3, 4, "none", null, "time"],+["low", "draw", 3, 5, "B", 61, "touch"],+["low", "draw", 4, 0, "B", 62, "touch"],+["low", "draw", 4, 1, "A", 105, "touch"],+["low", "draw", 4, 2, "A", 105, "touch"],+["low", "draw", 4, 3, "B", 262, "touch"],+["low", "draw", 4, 4, "B", 262, "touch"],+["low", "draw", 4, 5, "B", 61, "touch"],+["low", "draw", 5, 0, "B", 256, "touch"],+["low", "draw", 5, 1, "B", 62, "touch"],+["low", "draw", 5, 2, "B", 62, "touch"],+["low", "draw", 5, 3, "B", 61, "touch"],+["low", "draw", 5, 4, "B", 61, "touch"],+["low", "draw", 5, 5, "B", 62, "touch"],+["line", "lunge", 0, 0, "A", 31, "touch"],+["line", "lunge", 0, 1, "B", 71, "touch"],+["line", "lunge", 0, 2, "A", 32, "touch"],+["line", "lunge", 0, 3, "B", 73, "touch"],+["line", "lunge", 0, 4, "B", 130, "touch"],+["line", "lunge", 0, 5, "B", 75, "touch"],+["line", "lunge", 1, 0, "none", null, "time"],+["line", "lunge", 1, 1, "B", 70, "touch"],+["line", "lunge", 1, 2, "B", 144, "touch"],+["line", "lunge", 1, 3, "B", 72, "touch"],+["line", "lunge", 1, 4, "B", 153, "touch"],+["line", "lunge", 1, 5, "B", 74, "touch"],+["line", "lunge", 2, 0, "none", null, "time"],+["line", "lunge", 2, 1, "A", 33, "touch"],+["line", "lunge", 2, 2, "A", 33, "touch"],+["line", "lunge", 2, 3, "B", 72, "touch"],+["line", "lunge", 2, 4, "A", 34, "touch"],+["line", "lunge", 2, 5, "B", 75, "touch"],+["line", "lunge", 3, 0, "B", 31, "touch"],+["line", "lunge", 3, 1, "B", 69, "touch"],+["line", "lunge", 3, 2, "B", 136, "touch"],+["line", "lunge", 3, 3, "B", 72, "touch"],+["line", "lunge", 3, 4, "A", 34, "touch"],+["line", "lunge", 3, 5, "B", 75, "touch"],+["line", "lunge", 4, 0, "B", 31, "touch"],+["line", "lunge", 4, 1, "A", 35, "touch"],+["line", "lunge", 4, 2, "B", 131, "touch"],+["line", "lunge", 4, 3, "A", 35, "touch"],+["line", "lunge", 4, 4, "A", 35, "touch"],+["line", "lunge", 4, 5, "B", 75, "touch"],+["line", "lunge", 5, 0, "B", 31, "touch"],+["line", "lunge", 5, 1, "B", 70, "touch"],+["line", "lunge", 5, 2, "B", 33, "touch"],+["line", "lunge", 5, 3, "B", 72, "touch"],+["line", "lunge", 5, 4, "B", 122, "touch"],+["line", "lunge", 5, 5, "B", 74, "touch"],+["line", "low", 0, 0, "B", 147, "touch"],+["line", "low", 0, 1, "B", 166, "touch"],+["line", "low", 0, 2, "B", 147, "touch"],+["line", "low", 0, 3, "B", 166, "touch"],+["line", "low", 0, 4, "none", null, "time"],+["line", "low", 0, 5, "none", null, "time"],+["line", "low", 1, 0, "none", null, "time"],+["line", "low", 1, 1, "B", 106, "touch"],+["line", "low", 1, 2, "none", null, "time"],+["line", "low", 1, 3, "none", null, "time"],+["line", "low", 1, 4, "none", null, "time"],+["line", "low", 1, 5, "none", null, "time"],+["line", "low", 2, 0, "B", 149, "touch"],+["line", "low", 2, 1, "B", 103, "touch"],+["line", "low", 2, 2, "none", null, "time"],+["line", "low", 2, 3, "none", null, "time"],+["line", "low", 2, 4, "B", 149, "touch"],+["line", "low", 2, 5, "none", null, "time"],+["line", "low", 3, 0, "B", 155, "touch"],+["line", "low", 3, 1, "none", null, "time"],+["line", "low", 3, 2, "none", null, "time"],+["line", "low", 3, 3, "B", 103, "touch"],+["line", "low", 3, 4, "none", null, "time"],+["line", "low", 3, 5, "none", null, "time"],+["line", "low", 4, 0, "B", 147, "touch"],+["line", "low", 4, 1, "none", null, "time"],+["line", "low", 4, 2, "B", 153, "touch"],+["line", "low", 4, 3, "B", 175, "touch"],+["line", "low", 4, 4, "none", null, "time"],+["line", "low", 4, 5, "none", null, "time"],+["line", "low", 5, 0, "none", null, "time"],+["line", "low", 5, 1, "B", 164, "touch"],+["line", "low", 5, 2, "none", null, "time"],+["line", "low", 5, 3, "B", 164, "touch"],+["line", "low", 5, 4, "none", null, "time"],+["line", "low", 5, 5, "none", null, "time"],+["line", "line", 0, 0, "none", null, "time"],+["line", "line", 0, 1, "none", null, "time"],+["line", "line", 0, 2, "none", null, "time"],+["line", "line", 0, 3, "none", null, "time"],+["line", "line", 0, 4, "none", null, "time"],+["line", "line", 0, 5, "none", null, "time"],+["line", "line", 1, 0, "none", null, "time"],+["line", "line", 1, 1, "none", null, "time"],+["line", "line", 1, 2, "none", null, "time"],+["line", "line", 1, 3, "none", null, "time"],+["line", "line", 1, 4, "none", null, "time"],+["line", "line", 1, 5, "none", null, "time"],+["line", "line", 2, 0, "none", null, "time"],+["line", "line", 2, 1, "none", null, "time"],+["line", "line", 2, 2, "none", null, "time"],+["line", "line", 2, 3, "none", null, "time"],+["line", "line", 2, 4, "none", null, "time"],+["line", "line", 2, 5, "none", null, "time"],+["line", "line", 3, 0, "none", null, "time"],+["line", "line", 3, 1, "none", null, "time"],+["line", "line", 3, 2, "none", null, "time"],+["line", "line", 3, 3, "none", null, "time"],+["line", "line", 3, 4, "none", null, "time"],+["line", "line", 3, 5, "none", null, "time"],+["line", "line", 4, 0, "none", null, "time"],+["line", "line", 4, 1, "none", null, "time"],+["line", "line", 4, 2, "none", null, "time"],+["line", "line", 4, 3, "none", null, "time"],+["line", "line", 4, 4, "none", null, "time"],+["line", "line", 4, 5, "none", null, "time"],+["line", "line", 5, 0, "none", null, "time"],+["line", "line", 5, 1, "none", null, "time"],+["line", "line", 5, 2, "none", null, "time"],+["line", "line", 5, 3, "none", null, "time"],+["line", "line", 5, 4, "none", null, "time"],+["line", "line", 5, 5, "none", null, "time"],+["line", "rline", 0, 0, "none", null, "time"],+["line", "rline", 0, 1, "none", null, "time"],+["line", "rline", 0, 2, "none", null, "time"],+["line", "rline", 0, 3, "none", null, "time"],+["line", "rline", 0, 4, "none", null, "time"],+["line", "rline", 0, 5, "none", null, "time"],+["line", "rline", 1, 0, "none", null, "time"],+["line", "rline", 1, 1, "none", null, "time"],+["line", "rline", 1, 2, "none", null, "time"],+["line", "rline", 1, 3, "none", null, "time"],+["line", "rline", 1, 4, "none", null, "time"],+["line", "rline", 1, 5, "none", null, "time"],+["line", "rline", 2, 0, "none", null, "time"],+["line", "rline", 2, 1, "none", null, "time"],+["line", "rline", 2, 2, "none", null, "time"],+["line", "rline", 2, 3, "none", null, "time"],+["line", "rline", 2, 4, "none", null, "time"],+["line", "rline", 2, 5, "none", null, "time"],+["line", "rline", 3, 0, "none", null, "time"],+["line", "rline", 3, 1, "none", null, "time"],+["line", "rline", 3, 2, "none", null, "time"],+["line", "rline", 3, 3, "none", null, "time"],+["line", "rline", 3, 4, "none", null, "time"],+["line", "rline", 3, 5, "none", null, "time"],+["line", "rline", 4, 0, "none", null, "time"],+["line", "rline", 4, 1, "none", null, "time"],+["line", "rline", 4, 2, "none", null, "time"],+["line", "rline", 4, 3, "none", null, "time"],+["line", "rline", 4, 4, "none", null, "time"],+["line", "rline", 4, 5, "none", null, "time"],+["line", "rline", 5, 0, "none", null, "time"],+["line", "rline", 5, 1, "none", null, "time"],+["line", "rline", 5, 2, "none", null, "time"],+["line", "rline", 5, 3, "none", null, "time"],+["line", "rline", 5, 4, "none", null, "time"],+["line", "rline", 5, 5, "none", null, "time"],+["line", "stop", 0, 0, "none", null, "time"],+["line", "stop", 0, 1, "none", null, "time"],+["line", "stop", 0, 2, "none", null, "time"],+["line", "stop", 0, 3, "none", null, "time"],+["line", "stop", 0, 4, "none", null, "time"],+["line", "stop", 0, 5, "none", null, "time"],+["line", "stop", 1, 0, "none", null, "time"],+["line", "stop", 1, 1, "none", null, "time"],+["line", "stop", 1, 2, "none", null, "time"],+["line", "stop", 1, 3, "none", null, "time"],+["line", "stop", 1, 4, "none", null, "time"],+["line", "stop", 1, 5, "none", null, "time"],+["line", "stop", 2, 0, "none", null, "time"],+["line", "stop", 2, 1, "none", null, "time"],+["line", "stop", 2, 2, "none", null, "time"],+["line", "stop", 2, 3, "none", null, "time"],+["line", "stop", 2, 4, "none", null, "time"],+["line", "stop", 2, 5, "none", null, "time"],+["line", "stop", 3, 0, "none", null, "time"],+["line", "stop", 3, 1, "none", null, "time"],+["line", "stop", 3, 2, "none", null, "time"],+["line", "stop", 3, 3, "none", null, "time"],+["line", "stop", 3, 4, "none", null, "time"],+["line", "stop", 3, 5, "none", null, "time"],+["line", "stop", 4, 0, "none", null, "time"],+["line", "stop", 4, 1, "none", null, "time"],+["line", "stop", 4, 2, "none", null, "time"],+["line", "stop", 4, 3, "none", null, "time"],+["line", "stop", 4, 4, "none", null, "time"],+["line", "stop", 4, 5, "none", null, "time"],+["line", "stop", 5, 0, "none", null, "time"],+["line", "stop", 5, 1, "none", null, "time"],+["line", "stop", 5, 2, "none", null, "time"],+["line", "stop", 5, 3, "none", null, "time"],+["line", "stop", 5, 4, "none", null, "time"],+["line", "stop", 5, 5, "none", null, "time"],+["line", "counter", 0, 0, "none", null, "time"],+["line", "counter", 0, 1, "none", null, "time"],+["line", "counter", 0, 2, "none", null, "time"],+["line", "counter", 0, 3, "none", null, "time"],+["line", "counter", 0, 4, "none", null, "time"],+["line", "counter", 0, 5, "none", null, "time"],+["line", "counter", 1, 0, "none", null, "time"],+["line", "counter", 1, 1, "none", null, "time"],+["line", "counter", 1, 2, "none", null, "time"],+["line", "counter", 1, 3, "none", null, "time"],+["line", "counter", 1, 4, "none", null, "time"],+["line", "counter", 1, 5, "none", null, "time"],+["line", "counter", 2, 0, "none", null, "time"],+["line", "counter", 2, 1, "none", null, "time"],+["line", "counter", 2, 2, "none", null, "time"],+["line", "counter", 2, 3, "none", null, "time"],+["line", "counter", 2, 4, "none", null, "time"],+["line", "counter", 2, 5, "none", null, "time"],+["line", "counter", 3, 0, "none", null, "time"],+["line", "counter", 3, 1, "none", null, "time"],+["line", "counter", 3, 2, "none", null, "time"],+["line", "counter", 3, 3, "none", null, "time"],+["line", "counter", 3, 4, "none", null, "time"],+["line", "counter", 3, 5, "none", null, "time"],+["line", "counter", 4, 0, "none", null, "time"],+["line", "counter", 4, 1, "none", null, "time"],+["line", "counter", 4, 2, "none", null, "time"],+["line", "counter", 4, 3, "none", null, "time"],+["line", "counter", 4, 4, "none", null, "time"],+["line", "counter", 4, 5, "none", null, "time"],+["line", "counter", 5, 0, "none", null, "time"],+["line", "counter", 5, 1, "none", null, "time"],+["line", "counter", 5, 2, "none", null, "time"],+["line", "counter", 5, 3, "none", null, "time"],+["line", "counter", 5, 4, "none", null, "time"],+["line", "counter", 5, 5, "none", null, "time"],+["line", "delay", 0, 0, "B", 107, "touch"],+["line", "delay", 0, 1, "B", 108, "touch"],+["line", "delay", 0, 2, "B", 110, "touch"],+["line", "delay", 0, 3, "B", 111, "touch"],+["line", "delay", 0, 4, "B", 111, "touch"],+["line", "delay", 0, 5, "B", 112, "touch"],+["line", "delay", 1, 0, "B", 108, "touch"],+["line", "delay", 1, 1, "B", 108, "touch"],+["line", "delay", 1, 2, "B", 108, "touch"],+["line", "delay", 1, 3, "B", 110, "touch"],+["line", "delay", 1, 4, "B", 111, "touch"],+["line", "delay", 1, 5, "B", 113, "touch"],+["line", "delay", 2, 0, "B", 72, "touch"],+["line", "delay", 2, 1, "B", 108, "touch"],+["line", "delay", 2, 2, "B", 110, "touch"],+["line", "delay", 2, 3, "B", 110, "touch"],+["line", "delay", 2, 4, "B", 117, "touch"],+["line", "delay", 2, 5, "B", 112, "touch"],+["line", "delay", 3, 0, "B", 106, "touch"],+["line", "delay", 3, 1, "B", 108, "touch"],+["line", "delay", 3, 2, "B", 108, "touch"],+["line", "delay", 3, 3, "B", 110, "touch"],+["line", "delay", 3, 4, "B", 110, "touch"],+["line", "delay", 3, 5, "B", 112, "touch"],+["line", "delay", 4, 0, "B", 107, "touch"],+["line", "delay", 4, 1, "B", 108, "touch"],+["line", "delay", 4, 2, "B", 110, "touch"],+["line", "delay", 4, 3, "B", 110, "touch"],+["line", "delay", 4, 4, "B", 112, "touch"],+["line", "delay", 4, 5, "B", 111, "touch"],+["line", "delay", 5, 0, "B", 108, "touch"],+["line", "delay", 5, 1, "B", 108, "touch"],+["line", "delay", 5, 2, "B", 109, "touch"],+["line", "delay", 5, 3, "B", 109, "touch"],+["line", "delay", 5, 4, "B", 110, "touch"],+["line", "delay", 5, 5, "B", 112, "touch"],+["line", "retreat", 0, 0, "none", null, "time"],+["line", "retreat", 0, 1, "none", null, "time"],+["line", "retreat", 0, 2, "none", null, "time"],+["line", "retreat", 0, 3, "none", null, "time"],+["line", "retreat", 0, 4, "none", null, "time"],+["line", "retreat", 0, 5, "none", null, "time"],+["line", "retreat", 1, 0, "none", null, "time"],+["line", "retreat", 1, 1, "none", null, "time"],+["line", "retreat", 1, 2, "none", null, "time"],+["line", "retreat", 1, 3, "none", null, "time"],+["line", "retreat", 1, 4, "none", null, "time"],+["line", "retreat", 1, 5, "none", null, "time"],+["line", "retreat", 2, 0, "none", null, "time"],+["line", "retreat", 2, 1, "none", null, "time"],+["line", "retreat", 2, 2, "none", null, "time"],+["line", "retreat", 2, 3, "none", null, "time"],+["line", "retreat", 2, 4, "none", null, "time"],+["line", "retreat", 2, 5, "none", null, "time"],+["line", "retreat", 3, 0, "none", null, "time"],+["line", "retreat", 3, 1, "none", null, "time"],+["line", "retreat", 3, 2, "none", null, "time"],+["line", "retreat", 3, 3, "none", null, "time"],+["line", "retreat", 3, 4, "none", null, "time"],+["line", "retreat", 3, 5, "none", null, "time"],+["line", "retreat", 4, 0, "none", null, "time"],+["line", "retreat", 4, 1, "none", null, "time"],+["line", "retreat", 4, 2, "none", null, "time"],+["line", "retreat", 4, 3, "none", null, "time"],+["line", "retreat", 4, 4, "none", null, "time"],+["line", "retreat", 4, 5, "none", null, "time"],+["line", "retreat", 5, 0, "none", null, "time"],+["line", "retreat", 5, 1, "none", null, "time"],+["line", "retreat", 5, 2, "none", null, "time"],+["line", "retreat", 5, 3, "none", null, "time"],+["line", "retreat", 5, 4, "none", null, "time"],+["line", "retreat", 5, 5, "none", null, "time"],+["line", "draw", 0, 0, "none", null, "time"],+["line", "draw", 0, 1, "none", null, "time"],+["line", "draw", 0, 2, "none", null, "time"],+["line", "draw", 0, 3, "none", null, "time"],+["line", "draw", 0, 4, "none", null, "time"],+["line", "draw", 0, 5, "none", null, "time"],+["line", "draw", 1, 0, "none", null, "time"],+["line", "draw", 1, 1, "none", null, "time"],+["line", "draw", 1, 2, "none", null, "time"],+["line", "draw", 1, 3, "none", null, "time"],+["line", "draw", 1, 4, "none", null, "time"],+["line", "draw", 1, 5, "none", null, "time"],+["line", "draw", 2, 0, "none", null, "time"],+["line", "draw", 2, 1, "none", null, "time"],+["line", "draw", 2, 2, "none", null, "time"],+["line", "draw", 2, 3, "none", null, "time"],+["line", "draw", 2, 4, "none", null, "time"],+["line", "draw", 2, 5, "none", null, "time"],+["line", "draw", 3, 0, "none", null, "time"],+["line", "draw", 3, 1, "none", null, "time"],+["line", "draw", 3, 2, "none", null, "time"],+["line", "draw", 3, 3, "none", null, "time"],+["line", "draw", 3, 4, "none", null, "time"],+["line", "draw", 3, 5, "none", null, "time"],+["line", "draw", 4, 0, "none", null, "time"],+["line", "draw", 4, 1, "none", null, "time"],+["line", "draw", 4, 2, "none", null, "time"],+["line", "draw", 4, 3, "none", null, "time"],+["line", "draw", 4, 4, "none", null, "time"],+["line", "draw", 4, 5, "none", null, "time"],+["line", "draw", 5, 0, "none", null, "time"],+["line", "draw", 5, 1, "none", null, "time"],+["line", "draw", 5, 2, "none", null, "time"],+["line", "draw", 5, 3, "none", null, "time"],+["line", "draw", 5, 4, "none", null, "time"],+["line", "draw", 5, 5, "none", null, "time"],+["rline", "lunge", 0, 0, "A", 85, "touch"],+["rline", "lunge", 0, 1, "B", 114, "touch"],+["rline", "lunge", 0, 2, "B", 156, "touch"],+["rline", "lunge", 0, 3, "none", null, "time"],+["rline", "lunge", 0, 4, "none", null, "time"],+["rline", "lunge", 0, 5, "B", 82, "touch"],+["rline", "lunge", 1, 0, "A", 85, "touch"],+["rline", "lunge", 1, 1, "B", 114, "touch"],+["rline", "lunge", 1, 2, "B", 156, "touch"],+["rline", "lunge", 1, 3, "none", null, "time"],+["rline", "lunge", 1, 4, "none", null, "time"],+["rline", "lunge", 1, 5, "B", 82, "touch"],+["rline", "lunge", 2, 0, "A", 85, "touch"],+["rline", "lunge", 2, 1, "B", 114, "touch"],+["rline", "lunge", 2, 2, "B", 156, "touch"],+["rline", "lunge", 2, 3, "none", null, "time"],+["rline", "lunge", 2, 4, "none", null, "time"],+["rline", "lunge", 2, 5, "B", 82, "touch"],+["rline", "lunge", 3, 0, "A", 85, "touch"],+["rline", "lunge", 3, 1, "B", 114, "touch"],+["rline", "lunge", 3, 2, "B", 156, "touch"],+["rline", "lunge", 3, 3, "none", null, "time"],+["rline", "lunge", 3, 4, "none", null, "time"],+["rline", "lunge", 3, 5, "B", 82, "touch"],+["rline", "lunge", 4, 0, "A", 85, "touch"],+["rline", "lunge", 4, 1, "B", 114, "touch"],+["rline", "lunge", 4, 2, "B", 156, "touch"],+["rline", "lunge", 4, 3, "none", null, "time"],+["rline", "lunge", 4, 4, "none", null, "time"],+["rline", "lunge", 4, 5, "B", 82, "touch"],+["rline", "lunge", 5, 0, "A", 85, "touch"],+["rline", "lunge", 5, 1, "B", 114, "touch"],+["rline", "lunge", 5, 2, "B", 156, "touch"],+["rline", "lunge", 5, 3, "none", null, "time"],+["rline", "lunge", 5, 4, "none", null, "time"],+["rline", "lunge", 5, 5, "B", 82, "touch"],+["rline", "low", 0, 0, "B", 145, "touch"],+["rline", "low", 0, 1, "A", 114, "touch"],+["rline", "low", 0, 2, "none", null, "time"],+["rline", "low", 0, 3, "B", 143, "touch"],+["rline", "low", 0, 4, "none", null, "time"],+["rline", "low", 0, 5, "A", 118, "touch"],+["rline", "low", 1, 0, "B", 145, "touch"],+["rline", "low", 1, 1, "A", 114, "touch"],+["rline", "low", 1, 2, "none", null, "time"],+["rline", "low", 1, 3, "B", 143, "touch"],+["rline", "low", 1, 4, "none", null, "time"],+["rline", "low", 1, 5, "A", 118, "touch"],+["rline", "low", 2, 0, "B", 145, "touch"],+["rline", "low", 2, 1, "A", 114, "touch"],+["rline", "low", 2, 2, "none", null, "time"],+["rline", "low", 2, 3, "B", 143, "touch"],+["rline", "low", 2, 4, "none", null, "time"],+["rline", "low", 2, 5, "A", 118, "touch"],+["rline", "low", 3, 0, "B", 145, "touch"],+["rline", "low", 3, 1, "A", 114, "touch"],+["rline", "low", 3, 2, "none", null, "time"],+["rline", "low", 3, 3, "B", 143, "touch"],+["rline", "low", 3, 4, "none", null, "time"],+["rline", "low", 3, 5, "A", 118, "touch"],+["rline", "low", 4, 0, "B", 145, "touch"],+["rline", "low", 4, 1, "A", 114, "touch"],+["rline", "low", 4, 2, "none", null, "time"],+["rline", "low", 4, 3, "B", 143, "touch"],+["rline", "low", 4, 4, "none", null, "time"],+["rline", "low", 4, 5, "A", 118, "touch"],+["rline", "low", 5, 0, "B", 145, "touch"],+["rline", "low", 5, 1, "A", 114, "touch"],+["rline", "low", 5, 2, "none", null, "time"],+["rline", "low", 5, 3, "B", 143, "touch"],+["rline", "low", 5, 4, "none", null, "time"],+["rline", "low", 5, 5, "A", 118, "touch"],+["rline", "line", 0, 0, "none", null, "time"],+["rline", "line", 0, 1, "none", null, "time"],+["rline", "line", 0, 2, "none", null, "time"],+["rline", "line", 0, 3, "none", null, "time"],+["rline", "line", 0, 4, "none", null, "time"],+["rline", "line", 0, 5, "none", null, "time"],+["rline", "line", 1, 0, "none", null, "time"],+["rline", "line", 1, 1, "none", null, "time"],+["rline", "line", 1, 2, "none", null, "time"],+["rline", "line", 1, 3, "none", null, "time"],+["rline", "line", 1, 4, "none", null, "time"],+["rline", "line", 1, 5, "none", null, "time"],+["rline", "line", 2, 0, "none", null, "time"],+["rline", "line", 2, 1, "none", null, "time"],+["rline", "line", 2, 2, "none", null, "time"],+["rline", "line", 2, 3, "none", null, "time"],+["rline", "line", 2, 4, "none", null, "time"],+["rline", "line", 2, 5, "none", null, "time"],+["rline", "line", 3, 0, "none", null, "time"],+["rline", "line", 3, 1, "none", null, "time"],+["rline", "line", 3, 2, "none", null, "time"],+["rline", "line", 3, 3, "none", null, "time"],+["rline", "line", 3, 4, "none", null, "time"],+["rline", "line", 3, 5, "none", null, "time"],+["rline", "line", 4, 0, "none", null, "time"],+["rline", "line", 4, 1, "none", null, "time"],+["rline", "line", 4, 2, "none", null, "time"],+["rline", "line", 4, 3, "none", null, "time"],+["rline", "line", 4, 4, "none", null, "time"],+["rline", "line", 4, 5, "none", null, "time"],+["rline", "line", 5, 0, "none", null, "time"],+["rline", "line", 5, 1, "none", null, "time"],+["rline", "line", 5, 2, "none", null, "time"],+["rline", "line", 5, 3, "none", null, "time"],+["rline", "line", 5, 4, "none", null, "time"],+["rline", "line", 5, 5, "none", null, "time"],+["rline", "rline", 0, 0, "none", null, "time"],+["rline", "rline", 0, 1, "none", null, "time"],+["rline", "rline", 0, 2, "none", null, "time"],+["rline", "rline", 0, 3, "none", null, "time"],+["rline", "rline", 0, 4, "none", null, "time"],+["rline", "rline", 0, 5, "none", null, "time"],+["rline", "rline", 1, 0, "none", null, "time"],+["rline", "rline", 1, 1, "none", null, "time"],+["rline", "rline", 1, 2, "none", null, "time"],+["rline", "rline", 1, 3, "none", null, "time"],+["rline", "rline", 1, 4, "none", null, "time"],+["rline", "rline", 1, 5, "none", null, "time"],+["rline", "rline", 2, 0, "none", null, "time"],+["rline", "rline", 2, 1, "none", null, "time"],+["rline", "rline", 2, 2, "none", null, "time"],+["rline", "rline", 2, 3, "none", null, "time"],+["rline", "rline", 2, 4, "none", null, "time"],+["rline", "rline", 2, 5, "none", null, "time"],+["rline", "rline", 3, 0, "none", null, "time"],+["rline", "rline", 3, 1, "none", null, "time"],+["rline", "rline", 3, 2, "none", null, "time"],+["rline", "rline", 3, 3, "none", null, "time"],+["rline", "rline", 3, 4, "none", null, "time"],+["rline", "rline", 3, 5, "none", null, "time"],+["rline", "rline", 4, 0, "none", null, "time"],+["rline", "rline", 4, 1, "none", null, "time"],+["rline", "rline", 4, 2, "none", null, "time"],+["rline", "rline", 4, 3, "none", null, "time"],+["rline", "rline", 4, 4, "none", null, "time"],+["rline", "rline", 4, 5, "none", null, "time"],+["rline", "rline", 5, 0, "none", null, "time"],+["rline", "rline", 5, 1, "none", null, "time"],+["rline", "rline", 5, 2, "none", null, "time"],+["rline", "rline", 5, 3, "none", null, "time"],+["rline", "rline", 5, 4, "none", null, "time"],+["rline", "rline", 5, 5, "none", null, "time"],+["rline", "stop", 0, 0, "none", null, "time"],+["rline", "stop", 0, 1, "none", null, "time"],+["rline", "stop", 0, 2, "none", null, "time"],+["rline", "stop", 0, 3, "none", null, "time"],+["rline", "stop", 0, 4, "none", null, "time"],+["rline", "stop", 0, 5, "none", null, "time"],+["rline", "stop", 1, 0, "none", null, "time"],+["rline", "stop", 1, 1, "none", null, "time"],+["rline", "stop", 1, 2, "none", null, "time"],+["rline", "stop", 1, 3, "none", null, "time"],+["rline", "stop", 1, 4, "none", null, "time"],+["rline", "stop", 1, 5, "none", null, "time"],+["rline", "stop", 2, 0, "none", null, "time"],+["rline", "stop", 2, 1, "none", null, "time"],+["rline", "stop", 2, 2, "none", null, "time"],+["rline", "stop", 2, 3, "none", null, "time"],+["rline", "stop", 2, 4, "none", null, "time"],+["rline", "stop", 2, 5, "none", null, "time"],+["rline", "stop", 3, 0, "none", null, "time"],+["rline", "stop", 3, 1, "none", null, "time"],+["rline", "stop", 3, 2, "none", null, "time"],+["rline", "stop", 3, 3, "none", null, "time"],+["rline", "stop", 3, 4, "none", null, "time"],+["rline", "stop", 3, 5, "none", null, "time"],+["rline", "stop", 4, 0, "none", null, "time"],+["rline", "stop", 4, 1, "none", null, "time"],+["rline", "stop", 4, 2, "none", null, "time"],+["rline", "stop", 4, 3, "none", null, "time"],+["rline", "stop", 4, 4, "none", null, "time"],+["rline", "stop", 4, 5, "none", null, "time"],+["rline", "stop", 5, 0, "none", null, "time"],+["rline", "stop", 5, 1, "none", null, "time"],+["rline", "stop", 5, 2, "none", null, "time"],+["rline", "stop", 5, 3, "none", null, "time"],+["rline", "stop", 5, 4, "none", null, "time"],+["rline", "stop", 5, 5, "none", null, "time"],+["rline", "counter", 0, 0, "none", null, "time"],+["rline", "counter", 0, 1, "none", null, "time"],+["rline", "counter", 0, 2, "none", null, "time"],+["rline", "counter", 0, 3, "none", null, "time"],+["rline", "counter", 0, 4, "none", null, "time"],+["rline", "counter", 0, 5, "none", null, "time"],+["rline", "counter", 1, 0, "none", null, "time"],+["rline", "counter", 1, 1, "none", null, "time"],+["rline", "counter", 1, 2, "none", null, "time"],+["rline", "counter", 1, 3, "none", null, "time"],+["rline", "counter", 1, 4, "none", null, "time"],+["rline", "counter", 1, 5, "none", null, "time"],+["rline", "counter", 2, 0, "none", null, "time"],+["rline", "counter", 2, 1, "none", null, "time"],+["rline", "counter", 2, 2, "none", null, "time"],+["rline", "counter", 2, 3, "none", null, "time"],+["rline", "counter", 2, 4, "none", null, "time"],+["rline", "counter", 2, 5, "none", null, "time"],+["rline", "counter", 3, 0, "none", null, "time"],+["rline", "counter", 3, 1, "none", null, "time"],+["rline", "counter", 3, 2, "none", null, "time"],+["rline", "counter", 3, 3, "none", null, "time"],+["rline", "counter", 3, 4, "none", null, "time"],+["rline", "counter", 3, 5, "none", null, "time"],+["rline", "counter", 4, 0, "none", null, "time"],+["rline", "counter", 4, 1, "none", null, "time"],+["rline", "counter", 4, 2, "none", null, "time"],+["rline", "counter", 4, 3, "none", null, "time"],+["rline", "counter", 4, 4, "none", null, "time"],+["rline", "counter", 4, 5, "none", null, "time"],+["rline", "counter", 5, 0, "none", null, "time"],+["rline", "counter", 5, 1, "none", null, "time"],+["rline", "counter", 5, 2, "none", null, "time"],+["rline", "counter", 5, 3, "none", null, "time"],+["rline", "counter", 5, 4, "none", null, "time"],+["rline", "counter", 5, 5, "none", null, "time"],+["rline", "delay", 0, 0, "none", null, "time"],+["rline", "delay", 0, 1, "B", 152, "touch"],+["rline", "delay", 0, 2, "none", null, "time"],+["rline", "delay", 0, 3, "B", 125, "touch"],+["rline", "delay", 0, 4, "none", null, "time"],+["rline", "delay", 0, 5, "B", 160, "touch"],+["rline", "delay", 1, 0, "none", null, "time"],+["rline", "delay", 1, 1, "B", 152, "touch"],+["rline", "delay", 1, 2, "none", null, "time"],+["rline", "delay", 1, 3, "B", 125, "touch"],+["rline", "delay", 1, 4, "none", null, "time"],+["rline", "delay", 1, 5, "B", 160, "touch"],+["rline", "delay", 2, 0, "none", null, "time"],+["rline", "delay", 2, 1, "B", 152, "touch"],+["rline", "delay", 2, 2, "none", null, "time"],+["rline", "delay", 2, 3, "B", 125, "touch"],+["rline", "delay", 2, 4, "none", null, "time"],+["rline", "delay", 2, 5, "B", 160, "touch"],+["rline", "delay", 3, 0, "none", null, "time"],+["rline", "delay", 3, 1, "B", 152, "touch"],+["rline", "delay", 3, 2, "none", null, "time"],+["rline", "delay", 3, 3, "B", 125, "touch"],+["rline", "delay", 3, 4, "none", null, "time"],+["rline", "delay", 3, 5, "B", 160, "touch"],+["rline", "delay", 4, 0, "none", null, "time"],+["rline", "delay", 4, 1, "B", 152, "touch"],+["rline", "delay", 4, 2, "none", null, "time"],+["rline", "delay", 4, 3, "B", 125, "touch"],+["rline", "delay", 4, 4, "none", null, "time"],+["rline", "delay", 4, 5, "B", 160, "touch"],+["rline", "delay", 5, 0, "none", null, "time"],+["rline", "delay", 5, 1, "B", 152, "touch"],+["rline", "delay", 5, 2, "none", null, "time"],+["rline", "delay", 5, 3, "B", 125, "touch"],+["rline", "delay", 5, 4, "none", null, "time"],+["rline", "delay", 5, 5, "B", 160, "touch"],+["rline", "retreat", 0, 0, "none", null, "time"],+["rline", "retreat", 0, 1, "none", null, "time"],+["rline", "retreat", 0, 2, "none", null, "time"],+["rline", "retreat", 0, 3, "none", null, "time"],+["rline", "retreat", 0, 4, "none", null, "time"],+["rline", "retreat", 0, 5, "none", null, "time"],+["rline", "retreat", 1, 0, "none", null, "time"],+["rline", "retreat", 1, 1, "none", null, "time"],+["rline", "retreat", 1, 2, "none", null, "time"],+["rline", "retreat", 1, 3, "none", null, "time"],+["rline", "retreat", 1, 4, "none", null, "time"],+["rline", "retreat", 1, 5, "none", null, "time"],+["rline", "retreat", 2, 0, "none", null, "time"],+["rline", "retreat", 2, 1, "none", null, "time"],+["rline", "retreat", 2, 2, "none", null, "time"],+["rline", "retreat", 2, 3, "none", null, "time"],+["rline", "retreat", 2, 4, "none", null, "time"],+["rline", "retreat", 2, 5, "none", null, "time"],+["rline", "retreat", 3, 0, "none", null, "time"],+["rline", "retreat", 3, 1, "none", null, "time"],+["rline", "retreat", 3, 2, "none", null, "time"],+["rline", "retreat", 3, 3, "none", null, "time"],+["rline", "retreat", 3, 4, "none", null, "time"],+["rline", "retreat", 3, 5, "none", null, "time"],+["rline", "retreat", 4, 0, "none", null, "time"],+["rline", "retreat", 4, 1, "none", null, "time"],+["rline", "retreat", 4, 2, "none", null, "time"],+["rline", "retreat", 4, 3, "none", null, "time"],+["rline", "retreat", 4, 4, "none", null, "time"],+["rline", "retreat", 4, 5, "none", null, "time"],+["rline", "retreat", 5, 0, "none", null, "time"],+["rline", "retreat", 5, 1, "none", null, "time"],+["rline", "retreat", 5, 2, "none", null, "time"],+["rline", "retreat", 5, 3, "none", null, "time"],+["rline", "retreat", 5, 4, "none", null, "time"],+["rline", "retreat", 5, 5, "none", null, "time"],+["rline", "draw", 0, 0, "none", null, "time"],+["rline", "draw", 0, 1, "none", null, "time"],+["rline", "draw", 0, 2, "none", null, "time"],+["rline", "draw", 0, 3, "none", null, "time"],+["rline", "draw", 0, 4, "none", null, "time"],+["rline", "draw", 0, 5, "none", null, "time"],+["rline", "draw", 1, 0, "none", null, "time"],+["rline", "draw", 1, 1, "none", null, "time"],+["rline", "draw", 1, 2, "none", null, "time"],+["rline", "draw", 1, 3, "none", null, "time"],+["rline", "draw", 1, 4, "none", null, "time"],+["rline", "draw", 1, 5, "none", null, "time"],+["rline", "draw", 2, 0, "none", null, "time"],+["rline", "draw", 2, 1, "none", null, "time"],+["rline", "draw", 2, 2, "none", null, "time"],+["rline", "draw", 2, 3, "none", null, "time"],+["rline", "draw", 2, 4, "none", null, "time"],+["rline", "draw", 2, 5, "none", null, "time"],+["rline", "draw", 3, 0, "none", null, "time"],+["rline", "draw", 3, 1, "none", null, "time"],+["rline", "draw", 3, 2, "none", null, "time"],+["rline", "draw", 3, 3, "none", null, "time"],+["rline", "draw", 3, 4, "none", null, "time"],+["rline", "draw", 3, 5, "none", null, "time"],+["rline", "draw", 4, 0, "none", null, "time"],+["rline", "draw", 4, 1, "none", null, "time"],+["rline", "draw", 4, 2, "none", null, "time"],+["rline", "draw", 4, 3, "none", null, "time"],+["rline", "draw", 4, 4, "none", null, "time"],+["rline", "draw", 4, 5, "none", null, "time"],+["rline", "draw", 5, 0, "none", null, "time"],+["rline", "draw", 5, 1, "none", null, "time"],+["rline", "draw", 5, 2, "none", null, "time"],+["rline", "draw", 5, 3, "none", null, "time"],+["rline", "draw", 5, 4, "none", null, "time"],+["rline", "draw", 5, 5, "none", null, "time"],+["stop", "lunge", 0, 0, "B", 74, "touch"],+["stop", "lunge", 0, 1, "B", 70, "touch"],+["stop", "lunge", 0, 2, "B", 76, "touch"],+["stop", "lunge", 0, 3, "B", 73, "touch"],+["stop", "lunge", 0, 4, "B", 76, "touch"],+["stop", "lunge", 0, 5, "B", 75, "touch"],+["stop", "lunge", 1, 0, "B", 74, "touch"],+["stop", "lunge", 1, 1, "B", 70, "touch"],+["stop", "lunge", 1, 2, "B", 76, "touch"],+["stop", "lunge", 1, 3, "B", 73, "touch"],+["stop", "lunge", 1, 4, "B", 76, "touch"],+["stop", "lunge", 1, 5, "B", 75, "touch"],+["stop", "lunge", 2, 0, "B", 74, "touch"],+["stop", "lunge", 2, 1, "B", 70, "touch"],+["stop", "lunge", 2, 2, "B", 76, "touch"],+["stop", "lunge", 2, 3, "B", 73, "touch"],+["stop", "lunge", 2, 4, "B", 76, "touch"],+["stop", "lunge", 2, 5, "B", 75, "touch"],+["stop", "lunge", 3, 0, "B", 74, "touch"],+["stop", "lunge", 3, 1, "B", 70, "touch"],+["stop", "lunge", 3, 2, "B", 76, "touch"],+["stop", "lunge", 3, 3, "B", 73, "touch"],+["stop", "lunge", 3, 4, "B", 76, "touch"],+["stop", "lunge", 3, 5, "B", 75, "touch"],+["stop", "lunge", 4, 0, "B", 74, "touch"],+["stop", "lunge", 4, 1, "B", 70, "touch"],+["stop", "lunge", 4, 2, "B", 76, "touch"],+["stop", "lunge", 4, 3, "B", 73, "touch"],+["stop", "lunge", 4, 4, "B", 76, "touch"],+["stop", "lunge", 4, 5, "B", 75, "touch"],+["stop", "lunge", 5, 0, "B", 74, "touch"],+["stop", "lunge", 5, 1, "B", 70, "touch"],+["stop", "lunge", 5, 2, "B", 76, "touch"],+["stop", "lunge", 5, 3, "B", 73, "touch"],+["stop", "lunge", 5, 4, "B", 76, "touch"],+["stop", "lunge", 5, 5, "B", 75, "touch"],+["stop", "low", 0, 0, "A", 119, "touch"],+["stop", "low", 0, 1, "A", 151, "touch"],+["stop", "low", 0, 2, "A", 60, "touch"],+["stop", "low", 0, 3, "A", 65, "touch"],+["stop", "low", 0, 4, "A", 63, "touch"],+["stop", "low", 0, 5, "A", 128, "touch"],+["stop", "low", 1, 0, "A", 119, "touch"],+["stop", "low", 1, 1, "A", 151, "touch"],+["stop", "low", 1, 2, "A", 60, "touch"],+["stop", "low", 1, 3, "A", 65, "touch"],+["stop", "low", 1, 4, "A", 63, "touch"],+["stop", "low", 1, 5, "A", 128, "touch"],+["stop", "low", 2, 0, "A", 119, "touch"],+["stop", "low", 2, 1, "A", 151, "touch"],+["stop", "low", 2, 2, "A", 60, "touch"],+["stop", "low", 2, 3, "A", 65, "touch"],+["stop", "low", 2, 4, "A", 63, "touch"],+["stop", "low", 2, 5, "A", 128, "touch"],+["stop", "low", 3, 0, "A", 119, "touch"],+["stop", "low", 3, 1, "A", 151, "touch"],+["stop", "low", 3, 2, "A", 60, "touch"],+["stop", "low", 3, 3, "A", 65, "touch"],+["stop", "low", 3, 4, "A", 63, "touch"],+["stop", "low", 3, 5, "A", 128, "touch"],+["stop", "low", 4, 0, "A", 119, "touch"],+["stop", "low", 4, 1, "A", 151, "touch"],+["stop", "low", 4, 2, "A", 60, "touch"],+["stop", "low", 4, 3, "A", 65, "touch"],+["stop", "low", 4, 4, "A", 63, "touch"],+["stop", "low", 4, 5, "A", 128, "touch"],+["stop", "low", 5, 0, "A", 119, "touch"],+["stop", "low", 5, 1, "A", 151, "touch"],+["stop", "low", 5, 2, "A", 60, "touch"],+["stop", "low", 5, 3, "A", 65, "touch"],+["stop", "low", 5, 4, "A", 63, "touch"],+["stop", "low", 5, 5, "A", 128, "touch"],+["stop", "line", 0, 0, "none", null, "time"],+["stop", "line", 0, 1, "none", null, "time"],+["stop", "line", 0, 2, "none", null, "time"],+["stop", "line", 0, 3, "none", null, "time"],+["stop", "line", 0, 4, "none", null, "time"],+["stop", "line", 0, 5, "none", null, "time"],+["stop", "line", 1, 0, "none", null, "time"],+["stop", "line", 1, 1, "none", null, "time"],+["stop", "line", 1, 2, "none", null, "time"],+["stop", "line", 1, 3, "none", null, "time"],+["stop", "line", 1, 4, "none", null, "time"],+["stop", "line", 1, 5, "none", null, "time"],+["stop", "line", 2, 0, "none", null, "time"],+["stop", "line", 2, 1, "none", null, "time"],+["stop", "line", 2, 2, "none", null, "time"],+["stop", "line", 2, 3, "none", null, "time"],+["stop", "line", 2, 4, "none", null, "time"],+["stop", "line", 2, 5, "none", null, "time"],+["stop", "line", 3, 0, "none", null, "time"],+["stop", "line", 3, 1, "none", null, "time"],+["stop", "line", 3, 2, "none", null, "time"],+["stop", "line", 3, 3, "none", null, "time"],+["stop", "line", 3, 4, "none", null, "time"],+["stop", "line", 3, 5, "none", null, "time"],+["stop", "line", 4, 0, "none", null, "time"],+["stop", "line", 4, 1, "none", null, "time"],+["stop", "line", 4, 2, "none", null, "time"],+["stop", "line", 4, 3, "none", null, "time"],+["stop", "line", 4, 4, "none", null, "time"],+["stop", "line", 4, 5, "none", null, "time"],+["stop", "line", 5, 0, "none", null, "time"],+["stop", "line", 5, 1, "none", null, "time"],+["stop", "line", 5, 2, "none", null, "time"],+["stop", "line", 5, 3, "none", null, "time"],+["stop", "line", 5, 4, "none", null, "time"],+["stop", "line", 5, 5, "none", null, "time"],+["stop", "rline", 0, 0, "none", null, "time"],+["stop", "rline", 0, 1, "none", null, "time"],+["stop", "rline", 0, 2, "none", null, "time"],+["stop", "rline", 0, 3, "none", null, "time"],+["stop", "rline", 0, 4, "none", null, "time"],+["stop", "rline", 0, 5, "none", null, "time"],+["stop", "rline", 1, 0, "none", null, "time"],+["stop", "rline", 1, 1, "none", null, "time"],+["stop", "rline", 1, 2, "none", null, "time"],+["stop", "rline", 1, 3, "none", null, "time"],+["stop", "rline", 1, 4, "none", null, "time"],+["stop", "rline", 1, 5, "none", null, "time"],+["stop", "rline", 2, 0, "none", null, "time"],+["stop", "rline", 2, 1, "none", null, "time"],+["stop", "rline", 2, 2, "none", null, "time"],+["stop", "rline", 2, 3, "none", null, "time"],+["stop", "rline", 2, 4, "none", null, "time"],+["stop", "rline", 2, 5, "none", null, "time"],+["stop", "rline", 3, 0, "none", null, "time"],+["stop", "rline", 3, 1, "none", null, "time"],+["stop", "rline", 3, 2, "none", null, "time"],+["stop", "rline", 3, 3, "none", null, "time"],+["stop", "rline", 3, 4, "none", null, "time"],+["stop", "rline", 3, 5, "none", null, "time"],+["stop", "rline", 4, 0, "none", null, "time"],+["stop", "rline", 4, 1, "none", null, "time"],+["stop", "rline", 4, 2, "none", null, "time"],+["stop", "rline", 4, 3, "none", null, "time"],+["stop", "rline", 4, 4, "none", null, "time"],+["stop", "rline", 4, 5, "none", null, "time"],+["stop", "rline", 5, 0, "none", null, "time"],+["stop", "rline", 5, 1, "none", null, "time"],+["stop", "rline", 5, 2, "none", null, "time"],+["stop", "rline", 5, 3, "none", null, "time"],+["stop", "rline", 5, 4, "none", null, "time"],+["stop", "rline", 5, 5, "none", null, "time"],+["stop", "stop", 0, 0, "none", null, "time"],+["stop", "stop", 0, 1, "none", null, "time"],+["stop", "stop", 0, 2, "none", null, "time"],+["stop", "stop", 0, 3, "none", null, "time"],+["stop", "stop", 0, 4, "none", null, "time"],+["stop", "stop", 0, 5, "none", null, "time"],+["stop", "stop", 1, 0, "none", null, "time"],+["stop", "stop", 1, 1, "none", null, "time"],+["stop", "stop", 1, 2, "none", null, "time"],+["stop", "stop", 1, 3, "none", null, "time"],+["stop", "stop", 1, 4, "none", null, "time"],+["stop", "stop", 1, 5, "none", null, "time"],+["stop", "stop", 2, 0, "none", null, "time"],+["stop", "stop", 2, 1, "none", null, "time"],+["stop", "stop", 2, 2, "none", null, "time"],+["stop", "stop", 2, 3, "none", null, "time"],+["stop", "stop", 2, 4, "none", null, "time"],+["stop", "stop", 2, 5, "none", null, "time"],+["stop", "stop", 3, 0, "none", null, "time"],+["stop", "stop", 3, 1, "none", null, "time"],+["stop", "stop", 3, 2, "none", null, "time"],+["stop", "stop", 3, 3, "none", null, "time"],+["stop", "stop", 3, 4, "none", null, "time"],+["stop", "stop", 3, 5, "none", null, "time"],+["stop", "stop", 4, 0, "none", null, "time"],+["stop", "stop", 4, 1, "none", null, "time"],+["stop", "stop", 4, 2, "none", null, "time"],+["stop", "stop", 4, 3, "none", null, "time"],+["stop", "stop", 4, 4, "none", null, "time"],+["stop", "stop", 4, 5, "none", null, "time"],+["stop", "stop", 5, 0, "none", null, "time"],+["stop", "stop", 5, 1, "none", null, "time"],+["stop", "stop", 5, 2, "none", null, "time"],+["stop", "stop", 5, 3, "none", null, "time"],+["stop", "stop", 5, 4, "none", null, "time"],+["stop", "stop", 5, 5, "none", null, "time"],+["stop", "counter", 0, 0, "none", null, "time"],+["stop", "counter", 0, 1, "none", null, "time"],+["stop", "counter", 0, 2, "none", null, "time"],+["stop", "counter", 0, 3, "none", null, "time"],+["stop", "counter", 0, 4, "none", null, "time"],+["stop", "counter", 0, 5, "none", null, "time"],+["stop", "counter", 1, 0, "none", null, "time"],+["stop", "counter", 1, 1, "none", null, "time"],+["stop", "counter", 1, 2, "none", null, "time"],+["stop", "counter", 1, 3, "none", null, "time"],+["stop", "counter", 1, 4, "none", null, "time"],+["stop", "counter", 1, 5, "none", null, "time"],+["stop", "counter", 2, 0, "none", null, "time"],+["stop", "counter", 2, 1, "none", null, "time"],+["stop", "counter", 2, 2, "none", null, "time"],+["stop", "counter", 2, 3, "none", null, "time"],+["stop", "counter", 2, 4, "none", null, "time"],+["stop", "counter", 2, 5, "none", null, "time"],+["stop", "counter", 3, 0, "none", null, "time"],+["stop", "counter", 3, 1, "none", null, "time"],+["stop", "counter", 3, 2, "none", null, "time"],+["stop", "counter", 3, 3, "none", null, "time"],+["stop", "counter", 3, 4, "none", null, "time"],+["stop", "counter", 3, 5, "none", null, "time"],+["stop", "counter", 4, 0, "none", null, "time"],+["stop", "counter", 4, 1, "none", null, "time"],+["stop", "counter", 4, 2, "none", null, "time"],+["stop", "counter", 4, 3, "none", null, "time"],+["stop", "counter", 4, 4, "none", null, "time"],+["stop", "counter", 4, 5, "none", null, "time"],+["stop", "counter", 5, 0, "none", null, "time"],+["stop", "counter", 5, 1, "none", null, "time"],+["stop", "counter", 5, 2, "none", null, "time"],+["stop", "counter", 5, 3, "none", null, "time"],+["stop", "counter", 5, 4, "none", null, "time"],+["stop", "counter", 5, 5, "none", null, "time"],+["stop", "delay", 0, 0, "B", 111, "touch"],+["stop", "delay", 0, 1, "B", 111, "touch"],+["stop", "delay", 0, 2, "B", 114, "touch"],+["stop", "delay", 0, 3, "B", 113, "touch"],+["stop", "delay", 0, 4, "B", 116, "touch"],+["stop", "delay", 0, 5, "B", 115, "touch"],+["stop", "delay", 1, 0, "B", 111, "touch"],+["stop", "delay", 1, 1, "B", 111, "touch"],+["stop", "delay", 1, 2, "B", 114, "touch"],+["stop", "delay", 1, 3, "B", 113, "touch"],+["stop", "delay", 1, 4, "B", 116, "touch"],+["stop", "delay", 1, 5, "B", 115, "touch"],+["stop", "delay", 2, 0, "B", 111, "touch"],+["stop", "delay", 2, 1, "B", 111, "touch"],+["stop", "delay", 2, 2, "B", 114, "touch"],+["stop", "delay", 2, 3, "B", 113, "touch"],+["stop", "delay", 2, 4, "B", 116, "touch"],+["stop", "delay", 2, 5, "B", 115, "touch"],+["stop", "delay", 3, 0, "B", 111, "touch"],+["stop", "delay", 3, 1, "B", 111, "touch"],+["stop", "delay", 3, 2, "B", 114, "touch"],+["stop", "delay", 3, 3, "B", 113, "touch"],+["stop", "delay", 3, 4, "B", 116, "touch"],+["stop", "delay", 3, 5, "B", 115, "touch"],+["stop", "delay", 4, 0, "B", 111, "touch"],+["stop", "delay", 4, 1, "B", 111, "touch"],+["stop", "delay", 4, 2, "B", 114, "touch"],+["stop", "delay", 4, 3, "B", 113, "touch"],+["stop", "delay", 4, 4, "B", 116, "touch"],+["stop", "delay", 4, 5, "B", 115, "touch"],+["stop", "delay", 5, 0, "B", 111, "touch"],+["stop", "delay", 5, 1, "B", 111, "touch"],+["stop", "delay", 5, 2, "B", 114, "touch"],+["stop", "delay", 5, 3, "B", 113, "touch"],+["stop", "delay", 5, 4, "B", 116, "touch"],+["stop", "delay", 5, 5, "B", 115, "touch"],+["stop", "retreat", 0, 0, "none", null, "time"],+["stop", "retreat", 0, 1, "none", null, "time"],+["stop", "retreat", 0, 2, "none", null, "time"],+["stop", "retreat", 0, 3, "none", null, "time"],+["stop", "retreat", 0, 4, "none", null, "time"],+["stop", "retreat", 0, 5, "none", null, "time"],+["stop", "retreat", 1, 0, "none", null, "time"],+["stop", "retreat", 1, 1, "none", null, "time"],+["stop", "retreat", 1, 2, "none", null, "time"],+["stop", "retreat", 1, 3, "none", null, "time"],+["stop", "retreat", 1, 4, "none", null, "time"],+["stop", "retreat", 1, 5, "none", null, "time"],+["stop", "retreat", 2, 0, "none", null, "time"],+["stop", "retreat", 2, 1, "none", null, "time"],+["stop", "retreat", 2, 2, "none", null, "time"],+["stop", "retreat", 2, 3, "none", null, "time"],+["stop", "retreat", 2, 4, "none", null, "time"],+["stop", "retreat", 2, 5, "none", null, "time"],+["stop", "retreat", 3, 0, "none", null, "time"],+["stop", "retreat", 3, 1, "none", null, "time"],+["stop", "retreat", 3, 2, "none", null, "time"],+["stop", "retreat", 3, 3, "none", null, "time"],+["stop", "retreat", 3, 4, "none", null, "time"],+["stop", "retreat", 3, 5, "none", null, "time"],+["stop", "retreat", 4, 0, "none", null, "time"],+["stop", "retreat", 4, 1, "none", null, "time"],+["stop", "retreat", 4, 2, "none", null, "time"],+["stop", "retreat", 4, 3, "none", null, "time"],+["stop", "retreat", 4, 4, "none", null, "time"],+["stop", "retreat", 4, 5, "none", null, "time"],+["stop", "retreat", 5, 0, "none", null, "time"],+["stop", "retreat", 5, 1, "none", null, "time"],+["stop", "retreat", 5, 2, "none", null, "time"],+["stop", "retreat", 5, 3, "none", null, "time"],+["stop", "retreat", 5, 4, "none", null, "time"],+["stop", "retreat", 5, 5, "none", null, "time"],+["stop", "draw", 0, 0, "none", null, "time"],+["stop", "draw", 0, 1, "none", null, "time"],+["stop", "draw", 0, 2, "none", null, "time"],+["stop", "draw", 0, 3, "none", null, "time"],+["stop", "draw", 0, 4, "none", null, "time"],+["stop", "draw", 0, 5, "none", null, "time"],+["stop", "draw", 1, 0, "none", null, "time"],+["stop", "draw", 1, 1, "none", null, "time"],+["stop", "draw", 1, 2, "none", null, "time"],+["stop", "draw", 1, 3, "none", null, "time"],+["stop", "draw", 1, 4, "none", null, "time"],+["stop", "draw", 1, 5, "none", null, "time"],+["stop", "draw", 2, 0, "none", null, "time"],+["stop", "draw", 2, 1, "none", null, "time"],+["stop", "draw", 2, 2, "none", null, "time"],+["stop", "draw", 2, 3, "none", null, "time"],+["stop", "draw", 2, 4, "none", null, "time"],+["stop", "draw", 2, 5, "none", null, "time"],+["stop", "draw", 3, 0, "none", null, "time"],+["stop", "draw", 3, 1, "none", null, "time"],+["stop", "draw", 3, 2, "none", null, "time"],+["stop", "draw", 3, 3, "none", null, "time"],+["stop", "draw", 3, 4, "none", null, "time"],+["stop", "draw", 3, 5, "none", null, "time"],+["stop", "draw", 4, 0, "none", null, "time"],+["stop", "draw", 4, 1, "none", null, "time"],+["stop", "draw", 4, 2, "none", null, "time"],+["stop", "draw", 4, 3, "none", null, "time"],+["stop", "draw", 4, 4, "none", null, "time"],+["stop", "draw", 4, 5, "none", null, "time"],+["stop", "draw", 5, 0, "none", null, "time"],+["stop", "draw", 5, 1, "none", null, "time"],+["stop", "draw", 5, 2, "none", null, "time"],+["stop", "draw", 5, 3, "none", null, "time"],+["stop", "draw", 5, 4, "none", null, "time"],+["stop", "draw", 5, 5, "none", null, "time"],+["counter", "lunge", 0, 0, "A", 55, "touch"],+["counter", "lunge", 0, 1, "A", 54, "touch"],+["counter", "lunge", 0, 2, "A", 57, "touch"],+["counter", "lunge", 0, 3, "A", 56, "touch"],+["counter", "lunge", 0, 4, "A", 56, "touch"],+["counter", "lunge", 0, 5, "A", 58, "touch"],+["counter", "lunge", 1, 0, "A", 55, "touch"],+["counter", "lunge", 1, 1, "A", 54, "touch"],+["counter", "lunge", 1, 2, "A", 57, "touch"],+["counter", "lunge", 1, 3, "A", 56, "touch"],+["counter", "lunge", 1, 4, "A", 56, "touch"],+["counter", "lunge", 1, 5, "A", 58, "touch"],+["counter", "lunge", 2, 0, "A", 55, "touch"],+["counter", "lunge", 2, 1, "A", 54, "touch"],+["counter", "lunge", 2, 2, "A", 57, "touch"],+["counter", "lunge", 2, 3, "A", 56, "touch"],+["counter", "lunge", 2, 4, "A", 56, "touch"],+["counter", "lunge", 2, 5, "A", 58, "touch"],+["counter", "lunge", 3, 0, "A", 55, "touch"],+["counter", "lunge", 3, 1, "A", 54, "touch"],+["counter", "lunge", 3, 2, "A", 57, "touch"],+["counter", "lunge", 3, 3, "A", 56, "touch"],+["counter", "lunge", 3, 4, "A", 56, "touch"],+["counter", "lunge", 3, 5, "A", 58, "touch"],+["counter", "lunge", 4, 0, "A", 55, "touch"],+["counter", "lunge", 4, 1, "A", 54, "touch"],+["counter", "lunge", 4, 2, "A", 57, "touch"],+["counter", "lunge", 4, 3, "A", 56, "touch"],+["counter", "lunge", 4, 4, "A", 56, "touch"],+["counter", "lunge", 4, 5, "A", 58, "touch"],+["counter", "lunge", 5, 0, "A", 55, "touch"],+["counter", "lunge", 5, 1, "A", 54, "touch"],+["counter", "lunge", 5, 2, "A", 57, "touch"],+["counter", "lunge", 5, 3, "A", 56, "touch"],+["counter", "lunge", 5, 4, "A", 56, "touch"],+["counter", "lunge", 5, 5, "A", 58, "touch"],+["counter", "low", 0, 0, "none", null, "time"],+["counter", "low", 0, 1, "A", 53, "touch"],+["counter", "low", 0, 2, "none", null, "time"],+["counter", "low", 0, 3, "A", 55, "touch"],+["counter", "low", 0, 4, "A", 55, "touch"],+["counter", "low", 0, 5, "A", 57, "touch"],+["counter", "low", 1, 0, "none", null, "time"],+["counter", "low", 1, 1, "A", 53, "touch"],+["counter", "low", 1, 2, "none", null, "time"],+["counter", "low", 1, 3, "A", 55, "touch"],+["counter", "low", 1, 4, "A", 55, "touch"],+["counter", "low", 1, 5, "A", 57, "touch"],+["counter", "low", 2, 0, "none", null, "time"],+["counter", "low", 2, 1, "A", 53, "touch"],+["counter", "low", 2, 2, "none", null, "time"],+["counter", "low", 2, 3, "A", 55, "touch"],+["counter", "low", 2, 4, "A", 55, "touch"],+["counter", "low", 2, 5, "A", 57, "touch"],+["counter", "low", 3, 0, "none", null, "time"],+["counter", "low", 3, 1, "A", 53, "touch"],+["counter", "low", 3, 2, "none", null, "time"],+["counter", "low", 3, 3, "A", 55, "touch"],+["counter", "low", 3, 4, "A", 55, "touch"],+["counter", "low", 3, 5, "A", 57, "touch"],+["counter", "low", 4, 0, "none", null, "time"],+["counter", "low", 4, 1, "A", 53, "touch"],+["counter", "low", 4, 2, "none", null, "time"],+["counter", "low", 4, 3, "A", 55, "touch"],+["counter", "low", 4, 4, "A", 55, "touch"],+["counter", "low", 4, 5, "A", 57, "touch"],+["counter", "low", 5, 0, "none", null, "time"],+["counter", "low", 5, 1, "A", 53, "touch"],+["counter", "low", 5, 2, "none", null, "time"],+["counter", "low", 5, 3, "A", 55, "touch"],+["counter", "low", 5, 4, "A", 55, "touch"],+["counter", "low", 5, 5, "A", 57, "touch"],+["counter", "line", 0, 0, "none", null, "time"],+["counter", "line", 0, 1, "none", null, "time"],+["counter", "line", 0, 2, "none", null, "time"],+["counter", "line", 0, 3, "none", null, "time"],+["counter", "line", 0, 4, "none", null, "time"],+["counter", "line", 0, 5, "none", null, "time"],+["counter", "line", 1, 0, "none", null, "time"],+["counter", "line", 1, 1, "none", null, "time"],+["counter", "line", 1, 2, "none", null, "time"],+["counter", "line", 1, 3, "none", null, "time"],+["counter", "line", 1, 4, "none", null, "time"],+["counter", "line", 1, 5, "none", null, "time"],+["counter", "line", 2, 0, "none", null, "time"],+["counter", "line", 2, 1, "none", null, "time"],+["counter", "line", 2, 2, "none", null, "time"],+["counter", "line", 2, 3, "none", null, "time"],+["counter", "line", 2, 4, "none", null, "time"],+["counter", "line", 2, 5, "none", null, "time"],+["counter", "line", 3, 0, "none", null, "time"],+["counter", "line", 3, 1, "none", null, "time"],+["counter", "line", 3, 2, "none", null, "time"],+["counter", "line", 3, 3, "none", null, "time"],+["counter", "line", 3, 4, "none", null, "time"],+["counter", "line", 3, 5, "none", null, "time"],+["counter", "line", 4, 0, "none", null, "time"],+["counter", "line", 4, 1, "none", null, "time"],+["counter", "line", 4, 2, "none", null, "time"],+["counter", "line", 4, 3, "none", null, "time"],+["counter", "line", 4, 4, "none", null, "time"],+["counter", "line", 4, 5, "none", null, "time"],+["counter", "line", 5, 0, "none", null, "time"],+["counter", "line", 5, 1, "none", null, "time"],+["counter", "line", 5, 2, "none", null, "time"],+["counter", "line", 5, 3, "none", null, "time"],+["counter", "line", 5, 4, "none", null, "time"],+["counter", "line", 5, 5, "none", null, "time"],+["counter", "rline", 0, 0, "none", null, "time"],+["counter", "rline", 0, 1, "none", null, "time"],+["counter", "rline", 0, 2, "none", null, "time"],+["counter", "rline", 0, 3, "none", null, "time"],+["counter", "rline", 0, 4, "none", null, "time"],+["counter", "rline", 0, 5, "none", null, "time"],+["counter", "rline", 1, 0, "none", null, "time"],+["counter", "rline", 1, 1, "none", null, "time"],+["counter", "rline", 1, 2, "none", null, "time"],+["counter", "rline", 1, 3, "none", null, "time"],+["counter", "rline", 1, 4, "none", null, "time"],+["counter", "rline", 1, 5, "none", null, "time"],+["counter", "rline", 2, 0, "none", null, "time"],+["counter", "rline", 2, 1, "none", null, "time"],+["counter", "rline", 2, 2, "none", null, "time"],+["counter", "rline", 2, 3, "none", null, "time"],+["counter", "rline", 2, 4, "none", null, "time"],+["counter", "rline", 2, 5, "none", null, "time"],+["counter", "rline", 3, 0, "none", null, "time"],+["counter", "rline", 3, 1, "none", null, "time"],+["counter", "rline", 3, 2, "none", null, "time"],+["counter", "rline", 3, 3, "none", null, "time"],+["counter", "rline", 3, 4, "none", null, "time"],+["counter", "rline", 3, 5, "none", null, "time"],+["counter", "rline", 4, 0, "none", null, "time"],+["counter", "rline", 4, 1, "none", null, "time"],+["counter", "rline", 4, 2, "none", null, "time"],+["counter", "rline", 4, 3, "none", null, "time"],+["counter", "rline", 4, 4, "none", null, "time"],+["counter", "rline", 4, 5, "none", null, "time"],+["counter", "rline", 5, 0, "none", null, "time"],+["counter", "rline", 5, 1, "none", null, "time"],+["counter", "rline", 5, 2, "none", null, "time"],+["counter", "rline", 5, 3, "none", null, "time"],+["counter", "rline", 5, 4, "none", null, "time"],+["counter", "rline", 5, 5, "none", null, "time"],+["counter", "stop", 0, 0, "none", null, "time"],+["counter", "stop", 0, 1, "none", null, "time"],+["counter", "stop", 0, 2, "none", null, "time"],+["counter", "stop", 0, 3, "none", null, "time"],+["counter", "stop", 0, 4, "none", null, "time"],+["counter", "stop", 0, 5, "none", null, "time"],+["counter", "stop", 1, 0, "none", null, "time"],+["counter", "stop", 1, 1, "none", null, "time"],+["counter", "stop", 1, 2, "none", null, "time"],+["counter", "stop", 1, 3, "none", null, "time"],+["counter", "stop", 1, 4, "none", null, "time"],+["counter", "stop", 1, 5, "none", null, "time"],+["counter", "stop", 2, 0, "none", null, "time"],+["counter", "stop", 2, 1, "none", null, "time"],+["counter", "stop", 2, 2, "none", null, "time"],+["counter", "stop", 2, 3, "none", null, "time"],+["counter", "stop", 2, 4, "none", null, "time"],+["counter", "stop", 2, 5, "none", null, "time"],+["counter", "stop", 3, 0, "none", null, "time"],+["counter", "stop", 3, 1, "none", null, "time"],+["counter", "stop", 3, 2, "none", null, "time"],+["counter", "stop", 3, 3, "none", null, "time"],+["counter", "stop", 3, 4, "none", null, "time"],+["counter", "stop", 3, 5, "none", null, "time"],+["counter", "stop", 4, 0, "none", null, "time"],+["counter", "stop", 4, 1, "none", null, "time"],+["counter", "stop", 4, 2, "none", null, "time"],+["counter", "stop", 4, 3, "none", null, "time"],+["counter", "stop", 4, 4, "none", null, "time"],+["counter", "stop", 4, 5, "none", null, "time"],+["counter", "stop", 5, 0, "none", null, "time"],+["counter", "stop", 5, 1, "none", null, "time"],+["counter", "stop", 5, 2, "none", null, "time"],+["counter", "stop", 5, 3, "none", null, "time"],+["counter", "stop", 5, 4, "none", null, "time"],+["counter", "stop", 5, 5, "none", null, "time"],+["counter", "counter", 0, 0, "none", null, "time"],+["counter", "counter", 0, 1, "none", null, "time"],+["counter", "counter", 0, 2, "none", null, "time"],+["counter", "counter", 0, 3, "none", null, "time"],+["counter", "counter", 0, 4, "none", null, "time"],+["counter", "counter", 0, 5, "none", null, "time"],+["counter", "counter", 1, 0, "none", null, "time"],+["counter", "counter", 1, 1, "none", null, "time"],+["counter", "counter", 1, 2, "none", null, "time"],+["counter", "counter", 1, 3, "none", null, "time"],+["counter", "counter", 1, 4, "none", null, "time"],+["counter", "counter", 1, 5, "none", null, "time"],+["counter", "counter", 2, 0, "none", null, "time"],+["counter", "counter", 2, 1, "none", null, "time"],+["counter", "counter", 2, 2, "none", null, "time"],+["counter", "counter", 2, 3, "none", null, "time"],+["counter", "counter", 2, 4, "none", null, "time"],+["counter", "counter", 2, 5, "none", null, "time"],+["counter", "counter", 3, 0, "none", null, "time"],+["counter", "counter", 3, 1, "none", null, "time"],+["counter", "counter", 3, 2, "none", null, "time"],+["counter", "counter", 3, 3, "none", null, "time"],+["counter", "counter", 3, 4, "none", null, "time"],+["counter", "counter", 3, 5, "none", null, "time"],+["counter", "counter", 4, 0, "none", null, "time"],+["counter", "counter", 4, 1, "none", null, "time"],+["counter", "counter", 4, 2, "none", null, "time"],+["counter", "counter", 4, 3, "none", null, "time"],+["counter", "counter", 4, 4, "none", null, "time"],+["counter", "counter", 4, 5, "none", null, "time"],+["counter", "counter", 5, 0, "none", null, "time"],+["counter", "counter", 5, 1, "none", null, "time"],+["counter", "counter", 5, 2, "none", null, "time"],+["counter", "counter", 5, 3, "none", null, "time"],+["counter", "counter", 5, 4, "none", null, "time"],+["counter", "counter", 5, 5, "none", null, "time"],+["counter", "delay", 0, 0, "A", 92, "touch"],+["counter", "delay", 0, 1, "A", 95, "touch"],+["counter", "delay", 0, 2, "A", 93, "touch"],+["counter", "delay", 0, 3, "A", 96, "touch"],+["counter", "delay", 0, 4, "A", 95, "touch"],+["counter", "delay", 0, 5, "B", 228, "touch"],+["counter", "delay", 1, 0, "A", 92, "touch"],+["counter", "delay", 1, 1, "A", 95, "touch"],+["counter", "delay", 1, 2, "A", 93, "touch"],+["counter", "delay", 1, 3, "A", 96, "touch"],+["counter", "delay", 1, 4, "A", 95, "touch"],+["counter", "delay", 1, 5, "B", 228, "touch"],+["counter", "delay", 2, 0, "A", 92, "touch"],+["counter", "delay", 2, 1, "A", 95, "touch"],+["counter", "delay", 2, 2, "A", 93, "touch"],+["counter", "delay", 2, 3, "A", 96, "touch"],+["counter", "delay", 2, 4, "A", 95, "touch"],+["counter", "delay", 2, 5, "B", 228, "touch"],+["counter", "delay", 3, 0, "A", 92, "touch"],+["counter", "delay", 3, 1, "A", 95, "touch"],+["counter", "delay", 3, 2, "A", 93, "touch"],+["counter", "delay", 3, 3, "A", 96, "touch"],+["counter", "delay", 3, 4, "A", 95, "touch"],+["counter", "delay", 3, 5, "B", 228, "touch"],+["counter", "delay", 4, 0, "A", 92, "touch"],+["counter", "delay", 4, 1, "A", 95, "touch"],+["counter", "delay", 4, 2, "A", 93, "touch"],+["counter", "delay", 4, 3, "A", 96, "touch"],+["counter", "delay", 4, 4, "A", 95, "touch"],+["counter", "delay", 4, 5, "B", 228, "touch"],+["counter", "delay", 5, 0, "A", 92, "touch"],+["counter", "delay", 5, 1, "A", 95, "touch"],+["counter", "delay", 5, 2, "A", 93, "touch"],+["counter", "delay", 5, 3, "A", 96, "touch"],+["counter", "delay", 5, 4, "A", 95, "touch"],+["counter", "delay", 5, 5, "B", 228, "touch"],+["counter", "retreat", 0, 0, "none", null, "time"],+["counter", "retreat", 0, 1, "none", null, "time"],+["counter", "retreat", 0, 2, "none", null, "time"],+["counter", "retreat", 0, 3, "none", null, "time"],+["counter", "retreat", 0, 4, "none", null, "time"],+["counter", "retreat", 0, 5, "none", null, "time"],+["counter", "retreat", 1, 0, "none", null, "time"],+["counter", "retreat", 1, 1, "none", null, "time"],+["counter", "retreat", 1, 2, "none", null, "time"],+["counter", "retreat", 1, 3, "none", null, "time"],+["counter", "retreat", 1, 4, "none", null, "time"],+["counter", "retreat", 1, 5, "none", null, "time"],+["counter", "retreat", 2, 0, "none", null, "time"],+["counter", "retreat", 2, 1, "none", null, "time"],+["counter", "retreat", 2, 2, "none", null, "time"],+["counter", "retreat", 2, 3, "none", null, "time"],+["counter", "retreat", 2, 4, "none", null, "time"],+["counter", "retreat", 2, 5, "none", null, "time"],+["counter", "retreat", 3, 0, "none", null, "time"],+["counter", "retreat", 3, 1, "none", null, "time"],+["counter", "retreat", 3, 2, "none", null, "time"],+["counter", "retreat", 3, 3, "none", null, "time"],+["counter", "retreat", 3, 4, "none", null, "time"],+["counter", "retreat", 3, 5, "none", null, "time"],+["counter", "retreat", 4, 0, "none", null, "time"],+["counter", "retreat", 4, 1, "none", null, "time"],+["counter", "retreat", 4, 2, "none", null, "time"],+["counter", "retreat", 4, 3, "none", null, "time"],+["counter", "retreat", 4, 4, "none", null, "time"],+["counter", "retreat", 4, 5, "none", null, "time"],+["counter", "retreat", 5, 0, "none", null, "time"],+["counter", "retreat", 5, 1, "none", null, "time"],+["counter", "retreat", 5, 2, "none", null, "time"],+["counter", "retreat", 5, 3, "none", null, "time"],+["counter", "retreat", 5, 4, "none", null, "time"],+["counter", "retreat", 5, 5, "none", null, "time"],+["counter", "draw", 0, 0, "B", 94, "touch"],+["counter", "draw", 0, 1, "B", 95, "touch"],+["counter", "draw", 0, 2, "B", 95, "touch"],+["counter", "draw", 0, 3, "B", 92, "touch"],+["counter", "draw", 0, 4, "B", 92, "touch"],+["counter", "draw", 0, 5, "B", 100, "touch"],+["counter", "draw", 1, 0, "B", 94, "touch"],+["counter", "draw", 1, 1, "B", 95, "touch"],+["counter", "draw", 1, 2, "B", 95, "touch"],+["counter", "draw", 1, 3, "B", 92, "touch"],+["counter", "draw", 1, 4, "B", 92, "touch"],+["counter", "draw", 1, 5, "B", 100, "touch"],+["counter", "draw", 2, 0, "B", 94, "touch"],+["counter", "draw", 2, 1, "B", 95, "touch"],+["counter", "draw", 2, 2, "B", 95, "touch"],+["counter", "draw", 2, 3, "B", 92, "touch"],+["counter", "draw", 2, 4, "B", 92, "touch"],+["counter", "draw", 2, 5, "B", 100, "touch"],+["counter", "draw", 3, 0, "B", 94, "touch"],+["counter", "draw", 3, 1, "B", 95, "touch"],+["counter", "draw", 3, 2, "B", 95, "touch"],+["counter", "draw", 3, 3, "B", 92, "touch"],+["counter", "draw", 3, 4, "B", 92, "touch"],+["counter", "draw", 3, 5, "B", 100, "touch"],+["counter", "draw", 4, 0, "B", 94, "touch"],+["counter", "draw", 4, 1, "B", 95, "touch"],+["counter", "draw", 4, 2, "B", 95, "touch"],+["counter", "draw", 4, 3, "B", 92, "touch"],+["counter", "draw", 4, 4, "B", 92, "touch"],+["counter", "draw", 4, 5, "B", 100, "touch"],+["counter", "draw", 5, 0, "B", 94, "touch"],+["counter", "draw", 5, 1, "B", 95, "touch"],+["counter", "draw", 5, 2, "B", 95, "touch"],+["counter", "draw", 5, 3, "B", 92, "touch"],+["counter", "draw", 5, 4, "B", 92, "touch"],+["counter", "draw", 5, 5, "B", 100, "touch"],+["delay", "lunge", 0, 0, "A", 69, "touch"],+["delay", "lunge", 0, 1, "AB", 64, "touch"],+["delay", "lunge", 0, 2, "A", 69, "touch"],+["delay", "lunge", 0, 3, "A", 69, "touch"],+["delay", "lunge", 0, 4, "A", 69, "touch"],+["delay", "lunge", 0, 5, "A", 69, "touch"],+["delay", "lunge", 1, 0, "A", 70, "touch"],+["delay", "lunge", 1, 1, "AB", 65, "touch"],+["delay", "lunge", 1, 2, "A", 70, "touch"],+["delay", "lunge", 1, 3, "A", 70, "touch"],+["delay", "lunge", 1, 4, "A", 70, "touch"],+["delay", "lunge", 1, 5, "A", 70, "touch"],+["delay", "lunge", 2, 0, "A", 71, "touch"],+["delay", "lunge", 2, 1, "AB", 66, "touch"],+["delay", "lunge", 2, 2, "A", 71, "touch"],+["delay", "lunge", 2, 3, "A", 71, "touch"],+["delay", "lunge", 2, 4, "AB", 67, "touch"],+["delay", "lunge", 2, 5, "A", 71, "touch"],+["delay", "lunge", 3, 0, "A", 72, "touch"],+["delay", "lunge", 3, 1, "AB", 67, "touch"],+["delay", "lunge", 3, 2, "AB", 68, "touch"],+["delay", "lunge", 3, 3, "AB", 67, "touch"],+["delay", "lunge", 3, 4, "AB", 68, "touch"],+["delay", "lunge", 3, 5, "A", 72, "touch"],+["delay", "lunge", 4, 0, "AB", 68, "touch"],+["delay", "lunge", 4, 1, "B", 68, "touch"],+["delay", "lunge", 4, 2, "AB", 68, "touch"],+["delay", "lunge", 4, 3, "AB", 68, "touch"],+["delay", "lunge", 4, 4, "AB", 69, "touch"],+["delay", "lunge", 4, 5, "AB", 68, "touch"],+["delay", "lunge", 5, 0, "AB", 69, "touch"],+["delay", "lunge", 5, 1, "B", 68, "touch"],+["delay", "lunge", 5, 2, "AB", 70, "touch"],+["delay", "lunge", 5, 3, "AB", 69, "touch"],+["delay", "lunge", 5, 4, "AB", 70, "touch"],+["delay", "lunge", 5, 5, "AB", 69, "touch"],+["delay", "low", 0, 0, "A", 69, "touch"],+["delay", "low", 0, 1, "A", 69, "touch"],+["delay", "low", 0, 2, "A", 68, "touch"],+["delay", "low", 0, 3, "A", 69, "touch"],+["delay", "low", 0, 4, "A", 69, "touch"],+["delay", "low", 0, 5, "A", 69, "touch"],+["delay", "low", 1, 0, "A", 69, "touch"],+["delay", "low", 1, 1, "A", 70, "touch"],+["delay", "low", 1, 2, "A", 70, "touch"],+["delay", "low", 1, 3, "A", 70, "touch"],+["delay", "low", 1, 4, "A", 70, "touch"],+["delay", "low", 1, 5, "A", 70, "touch"],+["delay", "low", 2, 0, "A", 70, "touch"],+["delay", "low", 2, 1, "A", 70, "touch"],+["delay", "low", 2, 2, "A", 71, "touch"],+["delay", "low", 2, 3, "A", 71, "touch"],+["delay", "low", 2, 4, "A", 71, "touch"],+["delay", "low", 2, 5, "A", 71, "touch"],+["delay", "low", 3, 0, "A", 71, "touch"],+["delay", "low", 3, 1, "A", 72, "touch"],+["delay", "low", 3, 2, "A", 71, "touch"],+["delay", "low", 3, 3, "A", 72, "touch"],+["delay", "low", 3, 4, "A", 72, "touch"],+["delay", "low", 3, 5, "A", 72, "touch"],+["delay", "low", 4, 0, "A", 72, "touch"],+["delay", "low", 4, 1, "A", 72, "touch"],+["delay", "low", 4, 2, "A", 72, "touch"],+["delay", "low", 4, 3, "A", 73, "touch"],+["delay", "low", 4, 4, "A", 72, "touch"],+["delay", "low", 4, 5, "A", 73, "touch"],+["delay", "low", 5, 0, "A", 73, "touch"],+["delay", "low", 5, 1, "A", 73, "touch"],+["delay", "low", 5, 2, "A", 73, "touch"],+["delay", "low", 5, 3, "A", 74, "touch"],+["delay", "low", 5, 4, "A", 74, "touch"],+["delay", "low", 5, 5, "A", 73, "touch"],+["delay", "line", 0, 0, "A", 109, "touch"],+["delay", "line", 0, 1, "A", 107, "touch"],+["delay", "line", 0, 2, "A", 108, "touch"],+["delay", "line", 0, 3, "A", 106, "touch"],+["delay", "line", 0, 4, "A", 107, "touch"],+["delay", "line", 0, 5, "A", 107, "touch"],+["delay", "line", 1, 0, "A", 109, "touch"],+["delay", "line", 1, 1, "A", 108, "touch"],+["delay", "line", 1, 2, "A", 108, "touch"],+["delay", "line", 1, 3, "A", 108, "touch"],+["delay", "line", 1, 4, "A", 108, "touch"],+["delay", "line", 1, 5, "A", 108, "touch"],+["delay", "line", 2, 0, "A", 109, "touch"],+["delay", "line", 2, 1, "A", 109, "touch"],+["delay", "line", 2, 2, "A", 108, "touch"],+["delay", "line", 2, 3, "A", 109, "touch"],+["delay", "line", 2, 4, "A", 110, "touch"],+["delay", "line", 2, 5, "A", 109, "touch"],+["delay", "line", 3, 0, "A", 110, "touch"],+["delay", "line", 3, 1, "A", 110, "touch"],+["delay", "line", 3, 2, "A", 109, "touch"],+["delay", "line", 3, 3, "A", 110, "touch"],+["delay", "line", 3, 4, "A", 110, "touch"],+["delay", "line", 3, 5, "A", 110, "touch"],+["delay", "line", 4, 0, "A", 117, "touch"],+["delay", "line", 4, 1, "A", 111, "touch"],+["delay", "line", 4, 2, "A", 110, "touch"],+["delay", "line", 4, 3, "A", 112, "touch"],+["delay", "line", 4, 4, "A", 111, "touch"],+["delay", "line", 4, 5, "A", 110, "touch"],+["delay", "line", 5, 0, "A", 113, "touch"],+["delay", "line", 5, 1, "A", 112, "touch"],+["delay", "line", 5, 2, "A", 112, "touch"],+["delay", "line", 5, 3, "A", 112, "touch"],+["delay", "line", 5, 4, "A", 112, "touch"],+["delay", "line", 5, 5, "A", 112, "touch"],+["delay", "rline", 0, 0, "A", 107, "touch"],+["delay", "rline", 0, 1, "A", 107, "touch"],+["delay", "rline", 0, 2, "A", 107, "touch"],+["delay", "rline", 0, 3, "A", 107, "touch"],+["delay", "rline", 0, 4, "A", 107, "touch"],+["delay", "rline", 0, 5, "A", 107, "touch"],+["delay", "rline", 1, 0, "A", 116, "touch"],+["delay", "rline", 1, 1, "A", 116, "touch"],+["delay", "rline", 1, 2, "A", 116, "touch"],+["delay", "rline", 1, 3, "A", 116, "touch"],+["delay", "rline", 1, 4, "A", 116, "touch"],+["delay", "rline", 1, 5, "A", 116, "touch"],+["delay", "rline", 2, 0, "A", 150, "touch"],+["delay", "rline", 2, 1, "A", 150, "touch"],+["delay", "rline", 2, 2, "A", 150, "touch"],+["delay", "rline", 2, 3, "A", 150, "touch"],+["delay", "rline", 2, 4, "A", 150, "touch"],+["delay", "rline", 2, 5, "A", 150, "touch"],+["delay", "rline", 3, 0, "none", null, "time"],+["delay", "rline", 3, 1, "none", null, "time"],+["delay", "rline", 3, 2, "none", null, "time"],+["delay", "rline", 3, 3, "none", null, "time"],+["delay", "rline", 3, 4, "none", null, "time"],+["delay", "rline", 3, 5, "none", null, "time"],+["delay", "rline", 4, 0, "none", null, "time"],+["delay", "rline", 4, 1, "none", null, "time"],+["delay", "rline", 4, 2, "none", null, "time"],+["delay", "rline", 4, 3, "none", null, "time"],+["delay", "rline", 4, 4, "none", null, "time"],+["delay", "rline", 4, 5, "none", null, "time"],+["delay", "rline", 5, 0, "A", 149, "touch"],+["delay", "rline", 5, 1, "A", 149, "touch"],+["delay", "rline", 5, 2, "A", 149, "touch"],+["delay", "rline", 5, 3, "A", 149, "touch"],+["delay", "rline", 5, 4, "A", 149, "touch"],+["delay", "rline", 5, 5, "A", 149, "touch"],+["delay", "stop", 0, 0, "A", 112, "touch"],+["delay", "stop", 0, 1, "A", 112, "touch"],+["delay", "stop", 0, 2, "A", 112, "touch"],+["delay", "stop", 0, 3, "A", 112, "touch"],+["delay", "stop", 0, 4, "A", 112, "touch"],+["delay", "stop", 0, 5, "A", 112, "touch"],+["delay", "stop", 1, 0, "A", 110, "touch"],+["delay", "stop", 1, 1, "A", 110, "touch"],+["delay", "stop", 1, 2, "A", 110, "touch"],+["delay", "stop", 1, 3, "A", 110, "touch"],+["delay", "stop", 1, 4, "A", 110, "touch"],+["delay", "stop", 1, 5, "A", 110, "touch"],+["delay", "stop", 2, 0, "A", 115, "touch"],+["delay", "stop", 2, 1, "A", 115, "touch"],+["delay", "stop", 2, 2, "A", 115, "touch"],+["delay", "stop", 2, 3, "A", 115, "touch"],+["delay", "stop", 2, 4, "A", 115, "touch"],+["delay", "stop", 2, 5, "A", 115, "touch"],+["delay", "stop", 3, 0, "A", 112, "touch"],+["delay", "stop", 3, 1, "A", 112, "touch"],+["delay", "stop", 3, 2, "A", 112, "touch"],+["delay", "stop", 3, 3, "A", 112, "touch"],+["delay", "stop", 3, 4, "A", 112, "touch"],+["delay", "stop", 3, 5, "A", 112, "touch"],+["delay", "stop", 4, 0, "A", 116, "touch"],+["delay", "stop", 4, 1, "A", 116, "touch"],+["delay", "stop", 4, 2, "A", 116, "touch"],+["delay", "stop", 4, 3, "A", 116, "touch"],+["delay", "stop", 4, 4, "A", 116, "touch"],+["delay", "stop", 4, 5, "A", 116, "touch"],+["delay", "stop", 5, 0, "A", 115, "touch"],+["delay", "stop", 5, 1, "A", 115, "touch"],+["delay", "stop", 5, 2, "A", 115, "touch"],+["delay", "stop", 5, 3, "A", 115, "touch"],+["delay", "stop", 5, 4, "A", 115, "touch"],+["delay", "stop", 5, 5, "A", 115, "touch"],+["delay", "counter", 0, 0, "B", 92, "touch"],+["delay", "counter", 0, 1, "B", 92, "touch"],+["delay", "counter", 0, 2, "B", 92, "touch"],+["delay", "counter", 0, 3, "B", 92, "touch"],+["delay", "counter", 0, 4, "B", 92, "touch"],+["delay", "counter", 0, 5, "B", 92, "touch"],+["delay", "counter", 1, 0, "B", 95, "touch"],+["delay", "counter", 1, 1, "B", 95, "touch"],+["delay", "counter", 1, 2, "B", 95, "touch"],+["delay", "counter", 1, 3, "B", 95, "touch"],+["delay", "counter", 1, 4, "B", 95, "touch"],+["delay", "counter", 1, 5, "B", 95, "touch"],+["delay", "counter", 2, 0, "B", 93, "touch"],+["delay", "counter", 2, 1, "B", 93, "touch"],+["delay", "counter", 2, 2, "B", 93, "touch"],+["delay", "counter", 2, 3, "B", 93, "touch"],+["delay", "counter", 2, 4, "B", 93, "touch"],+["delay", "counter", 2, 5, "B", 93, "touch"],+["delay", "counter", 3, 0, "B", 95, "touch"],+["delay", "counter", 3, 1, "B", 95, "touch"],+["delay", "counter", 3, 2, "B", 95, "touch"],+["delay", "counter", 3, 3, "B", 95, "touch"],+["delay", "counter", 3, 4, "B", 95, "touch"],+["delay", "counter", 3, 5, "B", 95, "touch"],+["delay", "counter", 4, 0, "B", 96, "touch"],+["delay", "counter", 4, 1, "B", 96, "touch"],+["delay", "counter", 4, 2, "B", 96, "touch"],+["delay", "counter", 4, 3, "B", 96, "touch"],+["delay", "counter", 4, 4, "B", 96, "touch"],+["delay", "counter", 4, 5, "B", 96, "touch"],+["delay", "counter", 5, 0, "B", 99, "touch"],+["delay", "counter", 5, 1, "B", 99, "touch"],+["delay", "counter", 5, 2, "B", 99, "touch"],+["delay", "counter", 5, 3, "B", 99, "touch"],+["delay", "counter", 5, 4, "B", 99, "touch"],+["delay", "counter", 5, 5, "B", 99, "touch"],+["delay", "delay", 0, 0, "A", 285, "touch"],+["delay", "delay", 0, 1, "none", null, "time"],+["delay", "delay", 0, 2, "B", 226, "touch"],+["delay", "delay", 0, 3, "none", null, "time"],+["delay", "delay", 0, 4, "none", null, "time"],+["delay", "delay", 0, 5, "none", null, "time"],+["delay", "delay", 1, 0, "none", null, "time"],+["delay", "delay", 1, 1, "A", 209, "touch"],+["delay", "delay", 1, 2, "none", null, "time"],+["delay", "delay", 1, 3, "none", null, "time"],+["delay", "delay", 1, 4, "A", 222, "touch"],+["delay", "delay", 1, 5, "A", 219, "touch"],+["delay", "delay", 2, 0, "AB", 278, "touch"],+["delay", "delay", 2, 1, "none", null, "time"],+["delay", "delay", 2, 2, "none", null, "time"],+["delay", "delay", 2, 3, "B", 220, "touch"],+["delay", "delay", 2, 4, "none", null, "time"],+["delay", "delay", 2, 5, "none", null, "time"],+["delay", "delay", 3, 0, "A", 220, "touch"],+["delay", "delay", 3, 1, "none", null, "time"],+["delay", "delay", 3, 2, "none", null, "time"],+["delay", "delay", 3, 3, "B", 212, "touch"],+["delay", "delay", 3, 4, "B", 210, "touch"],+["delay", "delay", 3, 5, "B", 223, "touch"],+["delay", "delay", 4, 0, "AB", 225, "touch"],+["delay", "delay", 4, 1, "none", null, "time"],+["delay", "delay", 4, 2, "B", 207, "touch"],+["delay", "delay", 4, 3, "B", 221, "touch"],+["delay", "delay", 4, 4, "A", 259, "touch"],+["delay", "delay", 4, 5, "none", null, "time"],+["delay", "delay", 5, 0, "B", 210, "touch"],+["delay", "delay", 5, 1, "B", 210, "touch"],+["delay", "delay", 5, 2, "none", null, "time"],+["delay", "delay", 5, 3, "none", null, "time"],+["delay", "delay", 5, 4, "A", 219, "touch"],+["delay", "delay", 5, 5, "none", null, "time"],+["delay", "retreat", 0, 0, "none", null, "time"],+["delay", "retreat", 0, 1, "none", null, "time"],+["delay", "retreat", 0, 2, "none", null, "time"],+["delay", "retreat", 0, 3, "none", null, "time"],+["delay", "retreat", 0, 4, "none", null, "time"],+["delay", "retreat", 0, 5, "none", null, "time"],+["delay", "retreat", 1, 0, "none", null, "time"],+["delay", "retreat", 1, 1, "none", null, "time"],+["delay", "retreat", 1, 2, "none", null, "time"],+["delay", "retreat", 1, 3, "none", null, "time"],+["delay", "retreat", 1, 4, "none", null, "time"],+["delay", "retreat", 1, 5, "none", null, "time"],+["delay", "retreat", 2, 0, "none", null, "time"],+["delay", "retreat", 2, 1, "none", null, "time"],+["delay", "retreat", 2, 2, "none", null, "time"],+["delay", "retreat", 2, 3, "none", null, "time"],+["delay", "retreat", 2, 4, "none", null, "time"],+["delay", "retreat", 2, 5, "none", null, "time"],+["delay", "retreat", 3, 0, "none", null, "time"],+["delay", "retreat", 3, 1, "none", null, "time"],+["delay", "retreat", 3, 2, "none", null, "time"],+["delay", "retreat", 3, 3, "none", null, "time"],+["delay", "retreat", 3, 4, "none", null, "time"],+["delay", "retreat", 3, 5, "none", null, "time"],+["delay", "retreat", 4, 0, "none", null, "time"],+["delay", "retreat", 4, 1, "none", null, "time"],+["delay", "retreat", 4, 2, "none", null, "time"],+["delay", "retreat", 4, 3, "none", null, "time"],+["delay", "retreat", 4, 4, "none", null, "time"],+["delay", "retreat", 4, 5, "none", null, "time"],+["delay", "retreat", 5, 0, "none", null, "time"],+["delay", "retreat", 5, 1, "none", null, "time"],+["delay", "retreat", 5, 2, "none", null, "time"],+["delay", "retreat", 5, 3, "none", null, "time"],+["delay", "retreat", 5, 4, "none", null, "time"],+["delay", "retreat", 5, 5, "none", null, "time"],+["delay", "draw", 0, 0, "B", 96, "touch"],+["delay", "draw", 0, 1, "A", 107, "touch"],+["delay", "draw", 0, 2, "A", 107, "touch"],+["delay", "draw", 0, 3, "A", 110, "touch"],+["delay", "draw", 0, 4, "A", 110, "touch"],+["delay", "draw", 0, 5, "A", 107, "touch"],+["delay", "draw", 1, 0, "B", 97, "touch"],+["delay", "draw", 1, 1, "B", 99, "touch"],+["delay", "draw", 1, 2, "B", 99, "touch"],+["delay", "draw", 1, 3, "B", 92, "touch"],+["delay", "draw", 1, 4, "B", 92, "touch"],+["delay", "draw", 1, 5, "B", 98, "touch"],+["delay", "draw", 2, 0, "B", 99, "touch"],+["delay", "draw", 2, 1, "B", 98, "touch"],+["delay", "draw", 2, 2, "B", 98, "touch"],+["delay", "draw", 2, 3, "B", 99, "touch"],+["delay", "draw", 2, 4, "B", 99, "touch"],+["delay", "draw", 2, 5, "B", 100, "touch"],+["delay", "draw", 3, 0, "B", 101, "touch"],+["delay", "draw", 3, 1, "B", 93, "touch"],+["delay", "draw", 3, 2, "B", 93, "touch"],+["delay", "draw", 3, 3, "B", 99, "touch"],+["delay", "draw", 3, 4, "B", 99, "touch"],+["delay", "draw", 3, 5, "B", 100, "touch"],+["delay", "draw", 4, 0, "B", 94, "touch"],+["delay", "draw", 4, 1, "A", 111, "touch"],+["delay", "draw", 4, 2, "A", 111, "touch"],+["delay", "draw", 4, 3, "B", 101, "touch"],+["delay", "draw", 4, 4, "B", 101, "touch"],+["delay", "draw", 4, 5, "B", 100, "touch"],+["delay", "draw", 5, 0, "B", 95, "touch"],+["delay", "draw", 5, 1, "B", 105, "touch"],+["delay", "draw", 5, 2, "B", 105, "touch"],+["delay", "draw", 5, 3, "B", 102, "touch"],+["delay", "draw", 5, 4, "B", 102, "touch"],+["delay", "draw", 5, 5, "B", 95, "touch"],+["retreat", "lunge", 0, 0, "B", 73, "touch"],+["retreat", "lunge", 0, 1, "B", 69, "touch"],+["retreat", "lunge", 0, 2, "none", null, "time"],+["retreat", "lunge", 0, 3, "B", 71, "touch"],+["retreat", "lunge", 0, 4, "none", null, "time"],+["retreat", "lunge", 0, 5, "B", 74, "touch"],+["retreat", "lunge", 1, 0, "none", null, "time"],+["retreat", "lunge", 1, 1, "B", 69, "touch"],+["retreat", "lunge", 1, 2, "none", null, "time"],+["retreat", "lunge", 1, 3, "B", 71, "touch"],+["retreat", "lunge", 1, 4, "none", null, "time"],+["retreat", "lunge", 1, 5, "B", 74, "touch"],+["retreat", "lunge", 2, 0, "none", null, "time"],+["retreat", "lunge", 2, 1, "B", 69, "touch"],+["retreat", "lunge", 2, 2, "none", null, "time"],+["retreat", "lunge", 2, 3, "B", 71, "touch"],+["retreat", "lunge", 2, 4, "none", null, "time"],+["retreat", "lunge", 2, 5, "B", 74, "touch"],+["retreat", "lunge", 3, 0, "B", 72, "touch"],+["retreat", "lunge", 3, 1, "B", 69, "touch"],+["retreat", "lunge", 3, 2, "none", null, "time"],+["retreat", "lunge", 3, 3, "B", 71, "touch"],+["retreat", "lunge", 3, 4, "none", null, "time"],+["retreat", "lunge", 3, 5, "B", 74, "touch"],+["retreat", "lunge", 4, 0, "B", 72, "touch"],+["retreat", "lunge", 4, 1, "B", 69, "touch"],+["retreat", "lunge", 4, 2, "none", null, "time"],+["retreat", "lunge", 4, 3, "B", 71, "touch"],+["retreat", "lunge", 4, 4, "none", null, "time"],+["retreat", "lunge", 4, 5, "B", 74, "touch"],+["retreat", "lunge", 5, 0, "B", 71, "touch"],+["retreat", "lunge", 5, 1, "B", 68, "touch"],+["retreat", "lunge", 5, 2, "B", 72, "touch"],+["retreat", "lunge", 5, 3, "B", 71, "touch"],+["retreat", "lunge", 5, 4, "B", 72, "touch"],+["retreat", "lunge", 5, 5, "B", 72, "touch"],+["retreat", "low", 0, 0, "none", null, "time"],+["retreat", "low", 0, 1, "none", null, "time"],+["retreat", "low", 0, 2, "none", null, "time"],+["retreat", "low", 0, 3, "none", null, "time"],+["retreat", "low", 0, 4, "B", 54, "touch"],+["retreat", "low", 0, 5, "none", null, "time"],+["retreat", "low", 1, 0, "none", null, "time"],+["retreat", "low", 1, 1, "B", 87, "touch"],+["retreat", "low", 1, 2, "B", 52, "touch"],+["retreat", "low", 1, 3, "none", null, "time"],+["retreat", "low", 1, 4, "none", null, "time"],+["retreat", "low", 1, 5, "none", null, "time"],+["retreat", "low", 2, 0, "none", null, "time"],+["retreat", "low", 2, 1, "B", 87, "touch"],+["retreat", "low", 2, 2, "B", 52, "touch"],+["retreat", "low", 2, 3, "none", null, "time"],+["retreat", "low", 2, 4, "none", null, "time"],+["retreat", "low", 2, 5, "none", null, "time"],+["retreat", "low", 3, 0, "none", null, "time"],+["retreat", "low", 3, 1, "B", 88, "touch"],+["retreat", "low", 3, 2, "B", 52, "touch"],+["retreat", "low", 3, 3, "B", 89, "touch"],+["retreat", "low", 3, 4, "B", 53, "touch"],+["retreat", "low", 3, 5, "none", null, "time"],+["retreat", "low", 4, 0, "none", null, "time"],+["retreat", "low", 4, 1, "B", 88, "touch"],+["retreat", "low", 4, 2, "B", 52, "touch"],+["retreat", "low", 4, 3, "B", 89, "touch"],+["retreat", "low", 4, 4, "B", 53, "touch"],+["retreat", "low", 4, 5, "none", null, "time"],+["retreat", "low", 5, 0, "none", null, "time"],+["retreat", "low", 5, 1, "B", 90, "touch"],+["retreat", "low", 5, 2, "B", 52, "touch"],+["retreat", "low", 5, 3, "none", null, "time"],+["retreat", "low", 5, 4, "B", 53, "touch"],+["retreat", "low", 5, 5, "B", 90, "touch"],+["retreat", "line", 0, 0, "none", null, "time"],+["retreat", "line", 0, 1, "none", null, "time"],+["retreat", "line", 0, 2, "none", null, "time"],+["retreat", "line", 0, 3, "none", null, "time"],+["retreat", "line", 0, 4, "none", null, "time"],+["retreat", "line", 0, 5, "none", null, "time"],+["retreat", "line", 1, 0, "none", null, "time"],+["retreat", "line", 1, 1, "none", null, "time"],+["retreat", "line", 1, 2, "none", null, "time"],+["retreat", "line", 1, 3, "none", null, "time"],+["retreat", "line", 1, 4, "none", null, "time"],+["retreat", "line", 1, 5, "none", null, "time"],+["retreat", "line", 2, 0, "none", null, "time"],+["retreat", "line", 2, 1, "none", null, "time"],+["retreat", "line", 2, 2, "none", null, "time"],+["retreat", "line", 2, 3, "none", null, "time"],+["retreat", "line", 2, 4, "none", null, "time"],+["retreat", "line", 2, 5, "none", null, "time"],+["retreat", "line", 3, 0, "none", null, "time"],+["retreat", "line", 3, 1, "none", null, "time"],+["retreat", "line", 3, 2, "none", null, "time"],+["retreat", "line", 3, 3, "none", null, "time"],+["retreat", "line", 3, 4, "none", null, "time"],+["retreat", "line", 3, 5, "none", null, "time"],+["retreat", "line", 4, 0, "none", null, "time"],+["retreat", "line", 4, 1, "none", null, "time"],+["retreat", "line", 4, 2, "none", null, "time"],+["retreat", "line", 4, 3, "none", null, "time"],+["retreat", "line", 4, 4, "none", null, "time"],+["retreat", "line", 4, 5, "none", null, "time"],+["retreat", "line", 5, 0, "none", null, "time"],+["retreat", "line", 5, 1, "none", null, "time"],+["retreat", "line", 5, 2, "none", null, "time"],+["retreat", "line", 5, 3, "none", null, "time"],+["retreat", "line", 5, 4, "none", null, "time"],+["retreat", "line", 5, 5, "none", null, "time"],+["retreat", "rline", 0, 0, "none", null, "time"],+["retreat", "rline", 0, 1, "none", null, "time"],+["retreat", "rline", 0, 2, "none", null, "time"],+["retreat", "rline", 0, 3, "none", null, "time"],+["retreat", "rline", 0, 4, "none", null, "time"],+["retreat", "rline", 0, 5, "none", null, "time"],+["retreat", "rline", 1, 0, "none", null, "time"],+["retreat", "rline", 1, 1, "none", null, "time"],+["retreat", "rline", 1, 2, "none", null, "time"],+["retreat", "rline", 1, 3, "none", null, "time"],+["retreat", "rline", 1, 4, "none", null, "time"],+["retreat", "rline", 1, 5, "none", null, "time"],+["retreat", "rline", 2, 0, "none", null, "time"],+["retreat", "rline", 2, 1, "none", null, "time"],+["retreat", "rline", 2, 2, "none", null, "time"],+["retreat", "rline", 2, 3, "none", null, "time"],+["retreat", "rline", 2, 4, "none", null, "time"],+["retreat", "rline", 2, 5, "none", null, "time"],+["retreat", "rline", 3, 0, "none", null, "time"],+["retreat", "rline", 3, 1, "none", null, "time"],+["retreat", "rline", 3, 2, "none", null, "time"],+["retreat", "rline", 3, 3, "none", null, "time"],+["retreat", "rline", 3, 4, "none", null, "time"],+["retreat", "rline", 3, 5, "none", null, "time"],+["retreat", "rline", 4, 0, "none", null, "time"],+["retreat", "rline", 4, 1, "none", null, "time"],+["retreat", "rline", 4, 2, "none", null, "time"],+["retreat", "rline", 4, 3, "none", null, "time"],+["retreat", "rline", 4, 4, "none", null, "time"],+["retreat", "rline", 4, 5, "none", null, "time"],+["retreat", "rline", 5, 0, "none", null, "time"],+["retreat", "rline", 5, 1, "none", null, "time"],+["retreat", "rline", 5, 2, "none", null, "time"],+["retreat", "rline", 5, 3, "none", null, "time"],+["retreat", "rline", 5, 4, "none", null, "time"],+["retreat", "rline", 5, 5, "none", null, "time"],+["retreat", "stop", 0, 0, "none", null, "time"],+["retreat", "stop", 0, 1, "none", null, "time"],+["retreat", "stop", 0, 2, "none", null, "time"],+["retreat", "stop", 0, 3, "none", null, "time"],+["retreat", "stop", 0, 4, "none", null, "time"],+["retreat", "stop", 0, 5, "none", null, "time"],+["retreat", "stop", 1, 0, "none", null, "time"],+["retreat", "stop", 1, 1, "none", null, "time"],+["retreat", "stop", 1, 2, "none", null, "time"],+["retreat", "stop", 1, 3, "none", null, "time"],+["retreat", "stop", 1, 4, "none", null, "time"],+["retreat", "stop", 1, 5, "none", null, "time"],+["retreat", "stop", 2, 0, "none", null, "time"],+["retreat", "stop", 2, 1, "none", null, "time"],+["retreat", "stop", 2, 2, "none", null, "time"],+["retreat", "stop", 2, 3, "none", null, "time"],+["retreat", "stop", 2, 4, "none", null, "time"],+["retreat", "stop", 2, 5, "none", null, "time"],+["retreat", "stop", 3, 0, "none", null, "time"],+["retreat", "stop", 3, 1, "none", null, "time"],+["retreat", "stop", 3, 2, "none", null, "time"],+["retreat", "stop", 3, 3, "none", null, "time"],+["retreat", "stop", 3, 4, "none", null, "time"],+["retreat", "stop", 3, 5, "none", null, "time"],+["retreat", "stop", 4, 0, "none", null, "time"],+["retreat", "stop", 4, 1, "none", null, "time"],+["retreat", "stop", 4, 2, "none", null, "time"],+["retreat", "stop", 4, 3, "none", null, "time"],+["retreat", "stop", 4, 4, "none", null, "time"],+["retreat", "stop", 4, 5, "none", null, "time"],+["retreat", "stop", 5, 0, "none", null, "time"],+["retreat", "stop", 5, 1, "none", null, "time"],+["retreat", "stop", 5, 2, "none", null, "time"],+["retreat", "stop", 5, 3, "none", null, "time"],+["retreat", "stop", 5, 4, "none", null, "time"],+["retreat", "stop", 5, 5, "none", null, "time"],+["retreat", "counter", 0, 0, "none", null, "time"],+["retreat", "counter", 0, 1, "none", null, "time"],+["retreat", "counter", 0, 2, "none", null, "time"],+["retreat", "counter", 0, 3, "none", null, "time"],+["retreat", "counter", 0, 4, "none", null, "time"],+["retreat", "counter", 0, 5, "none", null, "time"],+["retreat", "counter", 1, 0, "none", null, "time"],+["retreat", "counter", 1, 1, "none", null, "time"],+["retreat", "counter", 1, 2, "none", null, "time"],+["retreat", "counter", 1, 3, "none", null, "time"],+["retreat", "counter", 1, 4, "none", null, "time"],+["retreat", "counter", 1, 5, "none", null, "time"],+["retreat", "counter", 2, 0, "none", null, "time"],+["retreat", "counter", 2, 1, "none", null, "time"],+["retreat", "counter", 2, 2, "none", null, "time"],+["retreat", "counter", 2, 3, "none", null, "time"],+["retreat", "counter", 2, 4, "none", null, "time"],+["retreat", "counter", 2, 5, "none", null, "time"],+["retreat", "counter", 3, 0, "none", null, "time"],+["retreat", "counter", 3, 1, "none", null, "time"],+["retreat", "counter", 3, 2, "none", null, "time"],+["retreat", "counter", 3, 3, "none", null, "time"],+["retreat", "counter", 3, 4, "none", null, "time"],+["retreat", "counter", 3, 5, "none", null, "time"],+["retreat", "counter", 4, 0, "none", null, "time"],+["retreat", "counter", 4, 1, "none", null, "time"],+["retreat", "counter", 4, 2, "none", null, "time"],+["retreat", "counter", 4, 3, "none", null, "time"],+["retreat", "counter", 4, 4, "none", null, "time"],+["retreat", "counter", 4, 5, "none", null, "time"],+["retreat", "counter", 5, 0, "none", null, "time"],+["retreat", "counter", 5, 1, "none", null, "time"],+["retreat", "counter", 5, 2, "none", null, "time"],+["retreat", "counter", 5, 3, "none", null, "time"],+["retreat", "counter", 5, 4, "none", null, "time"],+["retreat", "counter", 5, 5, "none", null, "time"],+["retreat", "delay", 0, 0, "none", null, "time"],+["retreat", "delay", 0, 1, "none", null, "time"],+["retreat", "delay", 0, 2, "none", null, "time"],+["retreat", "delay", 0, 3, "none", null, "time"],+["retreat", "delay", 0, 4, "none", null, "time"],+["retreat", "delay", 0, 5, "none", null, "time"],+["retreat", "delay", 1, 0, "none", null, "time"],+["retreat", "delay", 1, 1, "none", null, "time"],+["retreat", "delay", 1, 2, "none", null, "time"],+["retreat", "delay", 1, 3, "none", null, "time"],+["retreat", "delay", 1, 4, "none", null, "time"],+["retreat", "delay", 1, 5, "none", null, "time"],+["retreat", "delay", 2, 0, "none", null, "time"],+["retreat", "delay", 2, 1, "none", null, "time"],+["retreat", "delay", 2, 2, "none", null, "time"],+["retreat", "delay", 2, 3, "none", null, "time"],+["retreat", "delay", 2, 4, "none", null, "time"],+["retreat", "delay", 2, 5, "none", null, "time"],+["retreat", "delay", 3, 0, "none", null, "time"],+["retreat", "delay", 3, 1, "none", null, "time"],+["retreat", "delay", 3, 2, "none", null, "time"],+["retreat", "delay", 3, 3, "none", null, "time"],+["retreat", "delay", 3, 4, "none", null, "time"],+["retreat", "delay", 3, 5, "none", null, "time"],+["retreat", "delay", 4, 0, "none", null, "time"],+["retreat", "delay", 4, 1, "none", null, "time"],+["retreat", "delay", 4, 2, "none", null, "time"],+["retreat", "delay", 4, 3, "none", null, "time"],+["retreat", "delay", 4, 4, "none", null, "time"],+["retreat", "delay", 4, 5, "none", null, "time"],+["retreat", "delay", 5, 0, "none", null, "time"],+["retreat", "delay", 5, 1, "none", null, "time"],+["retreat", "delay", 5, 2, "none", null, "time"],+["retreat", "delay", 5, 3, "none", null, "time"],+["retreat", "delay", 5, 4, "none", null, "time"],+["retreat", "delay", 5, 5, "none", null, "time"],+["retreat", "retreat", 0, 0, "none", null, "time"],+["retreat", "retreat", 0, 1, "none", null, "time"],+["retreat", "retreat", 0, 2, "none", null, "time"],+["retreat", "retreat", 0, 3, "none", null, "time"],+["retreat", "retreat", 0, 4, "none", null, "time"],+["retreat", "retreat", 0, 5, "none", null, "time"],+["retreat", "retreat", 1, 0, "none", null, "time"],+["retreat", "retreat", 1, 1, "none", null, "time"],+["retreat", "retreat", 1, 2, "none", null, "time"],+["retreat", "retreat", 1, 3, "none", null, "time"],+["retreat", "retreat", 1, 4, "none", null, "time"],+["retreat", "retreat", 1, 5, "none", null, "time"],+["retreat", "retreat", 2, 0, "none", null, "time"],+["retreat", "retreat", 2, 1, "none", null, "time"],+["retreat", "retreat", 2, 2, "none", null, "time"],+["retreat", "retreat", 2, 3, "none", null, "time"],+["retreat", "retreat", 2, 4, "none", null, "time"],+["retreat", "retreat", 2, 5, "none", null, "time"],+["retreat", "retreat", 3, 0, "none", null, "time"],+["retreat", "retreat", 3, 1, "none", null, "time"],+["retreat", "retreat", 3, 2, "none", null, "time"],+["retreat", "retreat", 3, 3, "none", null, "time"],+["retreat", "retreat", 3, 4, "none", null, "time"],+["retreat", "retreat", 3, 5, "none", null, "time"],+["retreat", "retreat", 4, 0, "none", null, "time"],+["retreat", "retreat", 4, 1, "none", null, "time"],+["retreat", "retreat", 4, 2, "none", null, "time"],+["retreat", "retreat", 4, 3, "none", null, "time"],+["retreat", "retreat", 4, 4, "none", null, "time"],+["retreat", "retreat", 4, 5, "none", null, "time"],+["retreat", "retreat", 5, 0, "none", null, "time"],+["retreat", "retreat", 5, 1, "none", null, "time"],+["retreat", "retreat", 5, 2, "none", null, "time"],+["retreat", "retreat", 5, 3, "none", null, "time"],+["retreat", "retreat", 5, 4, "none", null, "time"],+["retreat", "retreat", 5, 5, "none", null, "time"],+["retreat", "draw", 0, 0, "B", 173, "touch"],+["retreat", "draw", 0, 1, "B", 174, "touch"],+["retreat", "draw", 0, 2, "B", 174, "touch"],+["retreat", "draw", 0, 3, "B", 175, "touch"],+["retreat", "draw", 0, 4, "B", 175, "touch"],+["retreat", "draw", 0, 5, "B", 178, "touch"],+["retreat", "draw", 1, 0, "B", 175, "touch"],+["retreat", "draw", 1, 1, "B", 177, "touch"],+["retreat", "draw", 1, 2, "B", 177, "touch"],+["retreat", "draw", 1, 3, "B", 177, "touch"],+["retreat", "draw", 1, 4, "B", 177, "touch"],+["retreat", "draw", 1, 5, "B", 179, "touch"],+["retreat", "draw", 2, 0, "B", 175, "touch"],+["retreat", "draw", 2, 1, "B", 177, "touch"],+["retreat", "draw", 2, 2, "B", 177, "touch"],+["retreat", "draw", 2, 3, "B", 177, "touch"],+["retreat", "draw", 2, 4, "B", 177, "touch"],+["retreat", "draw", 2, 5, "B", 179, "touch"],+["retreat", "draw", 3, 0, "B", 176, "touch"],+["retreat", "draw", 3, 1, "B", 177, "touch"],+["retreat", "draw", 3, 2, "B", 177, "touch"],+["retreat", "draw", 3, 3, "B", 178, "touch"],+["retreat", "draw", 3, 4, "B", 178, "touch"],+["retreat", "draw", 3, 5, "B", 179, "touch"],+["retreat", "draw", 4, 0, "B", 176, "touch"],+["retreat", "draw", 4, 1, "B", 177, "touch"],+["retreat", "draw", 4, 2, "B", 177, "touch"],+["retreat", "draw", 4, 3, "B", 178, "touch"],+["retreat", "draw", 4, 4, "B", 178, "touch"],+["retreat", "draw", 4, 5, "B", 179, "touch"],+["retreat", "draw", 5, 0, "B", 177, "touch"],+["retreat", "draw", 5, 1, "B", 177, "touch"],+["retreat", "draw", 5, 2, "B", 177, "touch"],+["retreat", "draw", 5, 3, "B", 179, "touch"],+["retreat", "draw", 5, 4, "B", 179, "touch"],+["retreat", "draw", 5, 5, "B", 181, "touch"],+["draw", "lunge", 0, 0, "B", 73, "touch"],+["draw", "lunge", 0, 1, "A", 60, "touch"],+["draw", "lunge", 0, 2, "B", 74, "touch"],+["draw", "lunge", 0, 3, "A", 61, "touch"],+["draw", "lunge", 0, 4, "A", 98, "touch"],+["draw", "lunge", 0, 5, "A", 63, "touch"],+["draw", "lunge", 1, 0, "B", 125, "touch"],+["draw", "lunge", 1, 1, "A", 61, "touch"],+["draw", "lunge", 1, 2, "B", 74, "touch"],+["draw", "lunge", 1, 3, "A", 62, "touch"],+["draw", "lunge", 1, 4, "A", 98, "touch"],+["draw", "lunge", 1, 5, "A", 63, "touch"],+["draw", "lunge", 2, 0, "B", 125, "touch"],+["draw", "lunge", 2, 1, "A", 61, "touch"],+["draw", "lunge", 2, 2, "B", 74, "touch"],+["draw", "lunge", 2, 3, "A", 62, "touch"],+["draw", "lunge", 2, 4, "A", 98, "touch"],+["draw", "lunge", 2, 5, "A", 63, "touch"],+["draw", "lunge", 3, 0, "A", 174, "touch"],+["draw", "lunge", 3, 1, "B", 70, "touch"],+["draw", "lunge", 3, 2, "B", 74, "touch"],+["draw", "lunge", 3, 3, "B", 73, "touch"],+["draw", "lunge", 3, 4, "B", 75, "touch"],+["draw", "lunge", 3, 5, "A", 65, "touch"],+["draw", "lunge", 4, 0, "A", 174, "touch"],+["draw", "lunge", 4, 1, "B", 70, "touch"],+["draw", "lunge", 4, 2, "B", 74, "touch"],+["draw", "lunge", 4, 3, "B", 73, "touch"],+["draw", "lunge", 4, 4, "B", 75, "touch"],+["draw", "lunge", 4, 5, "A", 65, "touch"],+["draw", "lunge", 5, 0, "B", 140, "touch"],+["draw", "lunge", 5, 1, "B", 70, "touch"],+["draw", "lunge", 5, 2, "B", 74, "touch"],+["draw", "lunge", 5, 3, "B", 72, "touch"],+["draw", "lunge", 5, 4, "B", 76, "touch"],+["draw", "lunge", 5, 5, "B", 74, "touch"],+["draw", "low", 0, 0, "A", 60, "touch"],+["draw", "low", 0, 1, "A", 60, "touch"],+["draw", "low", 0, 2, "A", 59, "touch"],+["draw", "low", 0, 3, "none", null, "time"],+["draw", "low", 0, 4, "A", 62, "touch"],+["draw", "low", 0, 5, "A", 62, "touch"],+["draw", "low", 1, 0, "A", 58, "touch"],+["draw", "low", 1, 1, "none", null, "time"],+["draw", "low", 1, 2, "A", 59, "touch"],+["draw", "low", 1, 3, "B", 105, "touch"],+["draw", "low", 1, 4, "A", 61, "touch"],+["draw", "low", 1, 5, "A", 62, "touch"],+["draw", "low", 2, 0, "A", 58, "touch"],+["draw", "low", 2, 1, "none", null, "time"],+["draw", "low", 2, 2, "A", 59, "touch"],+["draw", "low", 2, 3, "B", 105, "touch"],+["draw", "low", 2, 4, "A", 61, "touch"],+["draw", "low", 2, 5, "A", 62, "touch"],+["draw", "low", 3, 0, "A", 60, "touch"],+["draw", "low", 3, 1, "none", null, "time"],+["draw", "low", 3, 2, "A", 60, "touch"],+["draw", "low", 3, 3, "A", 60, "touch"],+["draw", "low", 3, 4, "none", null, "time"],+["draw", "low", 3, 5, "A", 61, "touch"],+["draw", "low", 4, 0, "A", 60, "touch"],+["draw", "low", 4, 1, "none", null, "time"],+["draw", "low", 4, 2, "A", 60, "touch"],+["draw", "low", 4, 3, "A", 60, "touch"],+["draw", "low", 4, 4, "none", null, "time"],+["draw", "low", 4, 5, "A", 61, "touch"],+["draw", "low", 5, 0, "A", 61, "touch"],+["draw", "low", 5, 1, "A", 60, "touch"],+["draw", "low", 5, 2, "none", null, "time"],+["draw", "low", 5, 3, "A", 61, "touch"],+["draw", "low", 5, 4, "A", 61, "touch"],+["draw", "low", 5, 5, "A", 62, "touch"],+["draw", "line", 0, 0, "none", null, "time"],+["draw", "line", 0, 1, "none", null, "time"],+["draw", "line", 0, 2, "none", null, "time"],+["draw", "line", 0, 3, "none", null, "time"],+["draw", "line", 0, 4, "none", null, "time"],+["draw", "line", 0, 5, "none", null, "time"],+["draw", "line", 1, 0, "none", null, "time"],+["draw", "line", 1, 1, "none", null, "time"],+["draw", "line", 1, 2, "none", null, "time"],+["draw", "line", 1, 3, "none", null, "time"],+["draw", "line", 1, 4, "none", null, "time"],+["draw", "line", 1, 5, "none", null, "time"],+["draw", "line", 2, 0, "none", null, "time"],+["draw", "line", 2, 1, "none", null, "time"],+["draw", "line", 2, 2, "none", null, "time"],+["draw", "line", 2, 3, "none", null, "time"],+["draw", "line", 2, 4, "none", null, "time"],+["draw", "line", 2, 5, "none", null, "time"],+["draw", "line", 3, 0, "none", null, "time"],+["draw", "line", 3, 1, "none", null, "time"],+["draw", "line", 3, 2, "none", null, "time"],+["draw", "line", 3, 3, "none", null, "time"],+["draw", "line", 3, 4, "none", null, "time"],+["draw", "line", 3, 5, "none", null, "time"],+["draw", "line", 4, 0, "none", null, "time"],+["draw", "line", 4, 1, "none", null, "time"],+["draw", "line", 4, 2, "none", null, "time"],+["draw", "line", 4, 3, "none", null, "time"],+["draw", "line", 4, 4, "none", null, "time"],+["draw", "line", 4, 5, "none", null, "time"],+["draw", "line", 5, 0, "none", null, "time"],+["draw", "line", 5, 1, "none", null, "time"],+["draw", "line", 5, 2, "none", null, "time"],+["draw", "line", 5, 3, "none", null, "time"],+["draw", "line", 5, 4, "none", null, "time"],+["draw", "line", 5, 5, "none", null, "time"],+["draw", "rline", 0, 0, "none", null, "time"],+["draw", "rline", 0, 1, "none", null, "time"],+["draw", "rline", 0, 2, "none", null, "time"],+["draw", "rline", 0, 3, "none", null, "time"],+["draw", "rline", 0, 4, "none", null, "time"],+["draw", "rline", 0, 5, "none", null, "time"],+["draw", "rline", 1, 0, "none", null, "time"],+["draw", "rline", 1, 1, "none", null, "time"],+["draw", "rline", 1, 2, "none", null, "time"],+["draw", "rline", 1, 3, "none", null, "time"],+["draw", "rline", 1, 4, "none", null, "time"],+["draw", "rline", 1, 5, "none", null, "time"],+["draw", "rline", 2, 0, "none", null, "time"],+["draw", "rline", 2, 1, "none", null, "time"],+["draw", "rline", 2, 2, "none", null, "time"],+["draw", "rline", 2, 3, "none", null, "time"],+["draw", "rline", 2, 4, "none", null, "time"],+["draw", "rline", 2, 5, "none", null, "time"],+["draw", "rline", 3, 0, "none", null, "time"],+["draw", "rline", 3, 1, "none", null, "time"],+["draw", "rline", 3, 2, "none", null, "time"],+["draw", "rline", 3, 3, "none", null, "time"],+["draw", "rline", 3, 4, "none", null, "time"],+["draw", "rline", 3, 5, "none", null, "time"],+["draw", "rline", 4, 0, "none", null, "time"],+["draw", "rline", 4, 1, "none", null, "time"],+["draw", "rline", 4, 2, "none", null, "time"],+["draw", "rline", 4, 3, "none", null, "time"],+["draw", "rline", 4, 4, "none", null, "time"],+["draw", "rline", 4, 5, "none", null, "time"],+["draw", "rline", 5, 0, "none", null, "time"],+["draw", "rline", 5, 1, "none", null, "time"],+["draw", "rline", 5, 2, "none", null, "time"],+["draw", "rline", 5, 3, "none", null, "time"],+["draw", "rline", 5, 4, "none", null, "time"],+["draw", "rline", 5, 5, "none", null, "time"],+["draw", "stop", 0, 0, "none", null, "time"],+["draw", "stop", 0, 1, "none", null, "time"],+["draw", "stop", 0, 2, "none", null, "time"],+["draw", "stop", 0, 3, "none", null, "time"],+["draw", "stop", 0, 4, "none", null, "time"],+["draw", "stop", 0, 5, "none", null, "time"],+["draw", "stop", 1, 0, "none", null, "time"],+["draw", "stop", 1, 1, "none", null, "time"],+["draw", "stop", 1, 2, "none", null, "time"],+["draw", "stop", 1, 3, "none", null, "time"],+["draw", "stop", 1, 4, "none", null, "time"],+["draw", "stop", 1, 5, "none", null, "time"],+["draw", "stop", 2, 0, "none", null, "time"],+["draw", "stop", 2, 1, "none", null, "time"],+["draw", "stop", 2, 2, "none", null, "time"],+["draw", "stop", 2, 3, "none", null, "time"],+["draw", "stop", 2, 4, "none", null, "time"],+["draw", "stop", 2, 5, "none", null, "time"],+["draw", "stop", 3, 0, "none", null, "time"],+["draw", "stop", 3, 1, "none", null, "time"],+["draw", "stop", 3, 2, "none", null, "time"],+["draw", "stop", 3, 3, "none", null, "time"],+["draw", "stop", 3, 4, "none", null, "time"],+["draw", "stop", 3, 5, "none", null, "time"],+["draw", "stop", 4, 0, "none", null, "time"],+["draw", "stop", 4, 1, "none", null, "time"],+["draw", "stop", 4, 2, "none", null, "time"],+["draw", "stop", 4, 3, "none", null, "time"],+["draw", "stop", 4, 4, "none", null, "time"],+["draw", "stop", 4, 5, "none", null, "time"],+["draw", "stop", 5, 0, "none", null, "time"],+["draw", "stop", 5, 1, "none", null, "time"],+["draw", "stop", 5, 2, "none", null, "time"],+["draw", "stop", 5, 3, "none", null, "time"],+["draw", "stop", 5, 4, "none", null, "time"],+["draw", "stop", 5, 5, "none", null, "time"],+["draw", "counter", 0, 0, "A", 94, "touch"],+["draw", "counter", 0, 1, "A", 94, "touch"],+["draw", "counter", 0, 2, "A", 94, "touch"],+["draw", "counter", 0, 3, "A", 94, "touch"],+["draw", "counter", 0, 4, "A", 94, "touch"],+["draw", "counter", 0, 5, "A", 94, "touch"],+["draw", "counter", 1, 0, "A", 95, "touch"],+["draw", "counter", 1, 1, "A", 95, "touch"],+["draw", "counter", 1, 2, "A", 95, "touch"],+["draw", "counter", 1, 3, "A", 95, "touch"],+["draw", "counter", 1, 4, "A", 95, "touch"],+["draw", "counter", 1, 5, "A", 95, "touch"],+["draw", "counter", 2, 0, "A", 95, "touch"],+["draw", "counter", 2, 1, "A", 95, "touch"],+["draw", "counter", 2, 2, "A", 95, "touch"],+["draw", "counter", 2, 3, "A", 95, "touch"],+["draw", "counter", 2, 4, "A", 95, "touch"],+["draw", "counter", 2, 5, "A", 95, "touch"],+["draw", "counter", 3, 0, "A", 92, "touch"],+["draw", "counter", 3, 1, "A", 92, "touch"],+["draw", "counter", 3, 2, "A", 92, "touch"],+["draw", "counter", 3, 3, "A", 92, "touch"],+["draw", "counter", 3, 4, "A", 92, "touch"],+["draw", "counter", 3, 5, "A", 92, "touch"],+["draw", "counter", 4, 0, "A", 92, "touch"],+["draw", "counter", 4, 1, "A", 92, "touch"],+["draw", "counter", 4, 2, "A", 92, "touch"],+["draw", "counter", 4, 3, "A", 92, "touch"],+["draw", "counter", 4, 4, "A", 92, "touch"],+["draw", "counter", 4, 5, "A", 92, "touch"],+["draw", "counter", 5, 0, "A", 100, "touch"],+["draw", "counter", 5, 1, "A", 100, "touch"],+["draw", "counter", 5, 2, "A", 100, "touch"],+["draw", "counter", 5, 3, "A", 100, "touch"],+["draw", "counter", 5, 4, "A", 100, "touch"],+["draw", "counter", 5, 5, "A", 100, "touch"],+["draw", "delay", 0, 0, "A", 97, "touch"],+["draw", "delay", 0, 1, "B", 107, "touch"],+["draw", "delay", 0, 2, "A", 100, "touch"],+["draw", "delay", 0, 3, "A", 101, "touch"],+["draw", "delay", 0, 4, "A", 93, "touch"],+["draw", "delay", 0, 5, "A", 95, "touch"],+["draw", "delay", 1, 0, "A", 96, "touch"],+["draw", "delay", 1, 1, "A", 98, "touch"],+["draw", "delay", 1, 2, "B", 111, "touch"],+["draw", "delay", 1, 3, "A", 93, "touch"],+["draw", "delay", 1, 4, "A", 94, "touch"],+["draw", "delay", 1, 5, "A", 101, "touch"],+["draw", "delay", 2, 0, "A", 96, "touch"],+["draw", "delay", 2, 1, "A", 98, "touch"],+["draw", "delay", 2, 2, "B", 111, "touch"],+["draw", "delay", 2, 3, "A", 93, "touch"],+["draw", "delay", 2, 4, "A", 94, "touch"],+["draw", "delay", 2, 5, "A", 101, "touch"],+["draw", "delay", 3, 0, "B", 111, "touch"],+["draw", "delay", 3, 1, "A", 92, "touch"],+["draw", "delay", 3, 2, "A", 99, "touch"],+["draw", "delay", 3, 3, "A", 99, "touch"],+["draw", "delay", 3, 4, "B", 112, "touch"],+["draw", "delay", 3, 5, "A", 95, "touch"],+["draw", "delay", 4, 0, "B", 111, "touch"],+["draw", "delay", 4, 1, "A", 92, "touch"],+["draw", "delay", 4, 2, "A", 99, "touch"],+["draw", "delay", 4, 3, "A", 99, "touch"],+["draw", "delay", 4, 4, "B", 112, "touch"],+["draw", "delay", 4, 5, "A", 95, "touch"],+["draw", "delay", 5, 0, "B", 109, "touch"],+["draw", "delay", 5, 1, "A", 98, "touch"],+["draw", "delay", 5, 2, "B", 109, "touch"],+["draw", "delay", 5, 3, "A", 100, "touch"],+["draw", "delay", 5, 4, "A", 100, "touch"],+["draw", "delay", 5, 5, "A", 102, "touch"],+["draw", "retreat", 0, 0, "A", 173, "touch"],+["draw", "retreat", 0, 1, "A", 175, "touch"],+["draw", "retreat", 0, 2, "A", 175, "touch"],+["draw", "retreat", 0, 3, "A", 176, "touch"],+["draw", "retreat", 0, 4, "A", 176, "touch"],+["draw", "retreat", 0, 5, "A", 176, "touch"],+["draw", "retreat", 1, 0, "A", 174, "touch"],+["draw", "retreat", 1, 1, "A", 175, "touch"],+["draw", "retreat", 1, 2, "A", 175, "touch"],+["draw", "retreat", 1, 3, "A", 177, "touch"],+["draw", "retreat", 1, 4, "A", 177, "touch"],+["draw", "retreat", 1, 5, "A", 178, "touch"],+["draw", "retreat", 2, 0, "A", 174, "touch"],+["draw", "retreat", 2, 1, "A", 175, "touch"],+["draw", "retreat", 2, 2, "A", 175, "touch"],+["draw", "retreat", 2, 3, "A", 177, "touch"],+["draw", "retreat", 2, 4, "A", 177, "touch"],+["draw", "retreat", 2, 5, "A", 178, "touch"],+["draw", "retreat", 3, 0, "A", 175, "touch"],+["draw", "retreat", 3, 1, "A", 177, "touch"],+["draw", "retreat", 3, 2, "A", 177, "touch"],+["draw", "retreat", 3, 3, "A", 179, "touch"],+["draw", "retreat", 3, 4, "A", 179, "touch"],+["draw", "retreat", 3, 5, "A", 179, "touch"],+["draw", "retreat", 4, 0, "A", 175, "touch"],+["draw", "retreat", 4, 1, "A", 177, "touch"],+["draw", "retreat", 4, 2, "A", 177, "touch"],+["draw", "retreat", 4, 3, "A", 179, "touch"],+["draw", "retreat", 4, 4, "A", 179, "touch"],+["draw", "retreat", 4, 5, "A", 179, "touch"],+["draw", "retreat", 5, 0, "A", 178, "touch"],+["draw", "retreat", 5, 1, "A", 178, "touch"],+["draw", "retreat", 5, 2, "A", 178, "touch"],+["draw", "retreat", 5, 3, "A", 178, "touch"],+["draw", "retreat", 5, 4, "A", 178, "touch"],+["draw", "retreat", 5, 5, "A", 181, "touch"],+["draw", "draw", 0, 0, "A", 149, "touch"],+["draw", "draw", 0, 1, "A", 164, "touch"],+["draw", "draw", 0, 2, "A", 164, "touch"],+["draw", "draw", 0, 3, "B", 153, "touch"],+["draw", "draw", 0, 4, "B", 153, "touch"],+["draw", "draw", 0, 5, "B", 153, "touch"],+["draw", "draw", 1, 0, "B", 164, "touch"],+["draw", "draw", 1, 1, "B", 151, "touch"],+["draw", "draw", 1, 2, "B", 151, "touch"],+["draw", "draw", 1, 3, "A", 166, "touch"],+["draw", "draw", 1, 4, "A", 166, "touch"],+["draw", "draw", 1, 5, "B", 155, "touch"],+["draw", "draw", 2, 0, "B", 164, "touch"],+["draw", "draw", 2, 1, "B", 151, "touch"],+["draw", "draw", 2, 2, "B", 151, "touch"],+["draw", "draw", 2, 3, "A", 166, "touch"],+["draw", "draw", 2, 4, "A", 166, "touch"],+["draw", "draw", 2, 5, "B", 155, "touch"],+["draw", "draw", 3, 0, "A", 152, "touch"],+["draw", "draw", 3, 1, "B", 167, "touch"],+["draw", "draw", 3, 2, "B", 167, "touch"],+["draw", "draw", 3, 3, "AB", 273, "touch"],+["draw", "draw", 3, 4, "AB", 273, "touch"],+["draw", "draw", 3, 5, "B", 157, "touch"],+["draw", "draw", 4, 0, "A", 152, "touch"],+["draw", "draw", 4, 1, "B", 167, "touch"],+["draw", "draw", 4, 2, "B", 167, "touch"],+["draw", "draw", 4, 3, "AB", 273, "touch"],+["draw", "draw", 4, 4, "AB", 273, "touch"],+["draw", "draw", 4, 5, "B", 157, "touch"],+["draw", "draw", 5, 0, "B", 148, "touch"],+["draw", "draw", 5, 1, "B", 166, "touch"],+["draw", "draw", 5, 2, "B", 166, "touch"],+["draw", "draw", 5, 3, "B", 168, "touch"],+["draw", "draw", 5, 4, "B", 168, "touch"],+["draw", "draw", 5, 5, "A", 271, "touch"]+]}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/plugin.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/plugin.pynew file mode 100644index 0000000000..5f6d0d9ea7--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/plugin.py@@ -0,0 +1,295 @@+"""fencing (epee) on the v0.2 framework, the phrase-level sport since fencing-7 (the owner's decision of 2026-10-13):+the four groups of contract ② (core/sport.py) around the phrase table (phrases.py), the bout referee (bout.py) and the+scripted fencer (opponent.py).++ world + referee FencingMatch: turn protocol, one action = one fencer's intention for the next phrase. Format bout:+ seat A's intention; the scripted fencer (side B) chooses its own from what it has seen of the bout+ (never from A's choice), the phrase is played (phrases.play: the measured phrase with this phrase's+ delays and ends, drawn from the seed) and judged (bout.Bout.phrase), all inside apply. Format duel:+ the first player's intention is kept hidden, the other player's completes the phrase. The state+ digest covers the bout, the hidden intention, the scripted fencer and the table.+ actions one low level: phrase {intention} (sport.toml [modes]: the intention is the robot's whole command+ for a phrase, as a release command in the other turn sports)+ observation observe = the score, the clocks, the cards and every phrase so far from the seat's view (both+ intentions, both delays, the result); camera_job = the 2 x 2 tile image of the last phrase+ (cameras.py, drawn in the seat's render worker)+"""+from __future__ import annotations++import hashlib+import json+import os++import bout as BT+import cameras as CAM+import fencing as F+import opponent as OP+import phrases as PH+from core.sport import FINISHED, PLAYING, MatchBase, Phase, SchemaLayer++HERE = os.path.dirname(os.path.abspath(__file__))+REVISION = "fencing-7+core-0.2"+OPPONENT = "B" # the scripted fencer's side in format bout (it has no seat)+TIEBREAKS = ("touches", "passivity", "time", "deciding_touch", "priority")+INTENTION_DOC = {+ "lunge": "a lunge with the point at the opponent's chest",+ "low": "a lunge with the point at the opponent's front knee",+ "line": "the point in line at the opponent's chest, held",+ "rline": "on guard; the point raised into line when the opponent comes (its pelvis coming faster than 0.2 x the "+ "distance per second)",+ "stop": "on guard; a stop-hit at the opponent's sword hand when it comes within reach",+ "counter": "waits; when the opponent comes (its pelvis faster than 0.15 m/s towards you), a lunge at its chest",+ "delay": "a lunge at the opponent's chest 0.4 s late (after the opponent has shown its intention)",+ "retreat": "steps back for the whole phrase",+ "draw": "a short advance (0.3 s, one 0.15 m step) to draw the opponent's attack, then a lunge at its chest when it "+ "comes, as counter",+}+SCHEMA = {"phrase": {"intention": {"type": "enum", "values": list(PH.INTENTIONS),+ "doc": "your intention for the next phrase (`game spec` intentions)"}}}+RESULT_VIEW = {"double": "double", "none": "none"}+++def _res_code(res, me):+ """the decision programs' result code (opponent.Policy.observe): 1 = I scored alone, -1 = the other, 2 = double+ (also an annulled one), 0 = nothing"""+ return 2 if res == "double" else 0 if res == "none" else (1 if res == me else -1)+++class FencingMatch(MatchBase):+ def __init__(self, cfg):+ self.cfg = cfg+ self.table = PH.table()+ self.kn = OP.Knowledge(self.table.counts())+ self.single = len(cfg.side_list()) == 1+ self.level = self.opp = None+ if self.single:+ self.level = 1 if cfg.level is None else int(cfg.level)+ if self.level not in OP.LEVELS:+ raise ValueError(f"opponent level must be one of {sorted(OP.LEVELS)}")+ self.first, self.second = cfg.seats[0], OPPONENT+ self.opp = OP.Opponent(self.level, cfg.seed, self.kn)+ else:+ self.first = cfg.first if cfg.first in cfg.seats else cfg.seats[0]+ self.second = next(s for s in cfg.seats if s != self.first)+ self.bout = BT.Bout(cfg.seed, self.first, self.second)+ self.pending: dict = {} # format duel: the first player's hidden intention+ self.k = 0++ def other(self, side):+ return self.second if side == self.first else self.first++ # ---------------------------------------------------------------- world + referee+ def _phrase(self, choices):+ b = self.bout+ n = len(b.log)+ p = PH.play(self.table, choices[self.first], choices[self.second], self.cfg.seed, n)+ res = {"first": self.first, "second": self.second}.get(p["res"], p["res"])+ info = dict(intentions={self.first: choices[self.first], self.second: choices[self.second]},+ delays_ms={self.first: p["first_delay_ms"], self.second: p["second_delay_ms"]},+ ends={self.first: p["first_end"], self.second: "B" if p["first_end"] == "A" else "A"},+ why=p["why"], k=p["k"], row=p["row"])+ rec = b.phrase(res, p["s"], info)+ if self.opp is not None:+ idx = self.table.idx+ self.opp.observe(idx[choices[OPPONENT]], idx[choices[self.first]], _res_code(rec["res"], OPPONENT))+ return rec++ def apply(self, seat, cmd):+ i = cmd["intention"]+ self.k += 1+ if self.single:+ sc = self.bout.score+ j = self.table.names[self.opp.choose((sc[OPPONENT], sc[seat]))]+ rec = self._phrase({seat: i, OPPONENT: j})+ return self._result(seat, rec)+ self.pending[seat] = i+ if len(self.pending) < 2:+ return {"committed": i, "phrase": len(self.bout.log) + 1,+ "note": "kept hidden until the other fencer has chosen; the phrase is fenced then"}+ choices, self.pending = self.pending, {}+ rec = self._phrase(choices)+ return self._result(seat, rec)++ def _result(self, seat, rec):+ v = self._phrase_view(rec, seat)+ return {"phrase": v["n"], "you": v["you"], "opponent": v["opponent"], "result": v["result"],+ "score": v["score_after"], "bout_over": self.bout.over}++ def forfeit(self, seat, why):+ self.bout.forfeit(self.cfg.side_of(seat), why)+ return True++ def to_move(self):+ if self.bout.over:+ return None+ if self.single:+ return self.cfg.seats[0]+ return self.first if self.first not in self.pending else self.second++ def phase(self):+ return Phase(FINISHED, reason=self.bout.how or "bout_over") if self.bout.over else Phase(PLAYING)++ def unit(self):+ return len(self.bout.log)++ def scores(self):+ return dict(self.bout.score)++ def tiebreaks(self):+ """FIE t.38 and t.124 as bout.py decides it: 15 touches; the P-black card for unwillingness to fight; at time+ the fencer ahead; the deciding touch of the extra minute; the priority drawn by lot before it (the last rule+ always decides)."""+ rules = [(n, (lambda m, n=n: m.bout.winner if m.bout.how == n else None)) for n in TIEBREAKS[:-1]]+ return rules + [(TIEBREAKS[-1], lambda m: m.bout.winner)]++ def state_digest(self):+ st = dict(bout=self.bout.state(), pending=self.pending, k=self.k, table=self.table.sha,+ opp=None if self.opp is None else self.opp.state())+ return hashlib.sha256(json.dumps(st, sort_keys=True, default=str).encode()).hexdigest()++ # ---------------------------------------------------------------- actions+ def schema(self, seat):+ return SCHEMA++ # ---------------------------------------------------------------- observation+ def _phrase_view(self, r, seat):+ me = self.cfg.side_of(seat)+ ot = self.other(me)+ res = r["res"]+ result = "you" if res == me else "opponent" if res == ot else res+ if r.get("annulled"):+ result = "double, not counted at 14-14"+ out = {"n": r["n"], "you": r["intentions"][me], "opponent": r["intentions"][ot], "result": result,+ "seconds": r["s"], "your_delay_ms": r["delays_ms"][me], "opponent_delay_ms": r["delays_ms"][ot],+ "score_after": {"you": r["score"][me], "opponent": r["score"][ot]}}+ if r.get("cut_by_clock"):+ out["cut_by_clock"] = True+ if r.get("card"):+ out["card"] = r["card"] if r["card"] != "P-black" else \+ f"P-black to {'you' if r['black'] == me else 'the opponent'}"+ if r.get("extra_minute_starts"):+ out["extra_minute_starts"] = True+ return out++ def observe(self, seat, query=None):+ b, me = self.bout, self.cfg.side_of(seat)+ ot = self.other(me)+ out = {"score": {"you": b.score[me], "opponent": b.score[ot]}, "phrase": len(b.log) + 1,+ "fencing_time_s": round(b.t, 2), "time_left_s": b.time_left_s(), "extra_minute": b.extra,+ "priority": None if b.priority is None else ("you" if b.priority == me else "opponent"),+ "passivity": {"no_hit_s": b.no_hit_s(), "limit_s": BT.PASSIVE_S, "p_cards": b.p_calls},+ "phrases": [self._phrase_view(r, seat) for r in b.log]}+ if not self.single:+ out["committed"] = self.pending.get(me)+ return out++ def _snaps(self, seat):+ if not self.bout.log:+ q = self.table.guard_qpos()+ return [dict(label="on guard", qpos=q), dict(label="on guard", qpos=q)]+ r = self.bout.log[-1]+ steps, qs = self.table.frames(r["row"])+ seat_a = self.cfg.seats[0] if self.single else "A"+ turn = r["ends"].get(seat_a, "A") != "A" # seat A's fencer fenced from the table's end B+ m = _scene_model()+ out = []+ for s, q, what in zip(steps, qs, ("half-way", "end")):+ q = CAM.half_turn(m, q) if turn else q+ out.append(dict(label=f"phrase {r['n']} {what}: {(int(s) + 1) * PH.STEP_S:.2f} s", qpos=q))+ return out++ def camera_job(self, seat):+ job = {"seat": seat, "snaps": self._snaps(seat)}+ return job, dict(image_layout=CAM.IMAGE_LAYOUT, phrase=len(self.bout.log))++ def render_state(self):+ return {"qpos": [float(x) for x in self._snaps(self.cfg.seats[0])[-1]["qpos"]]}++ def final_fields(self):+ b = self.bout+ out = {"phrases": b.log, "extra_minute": b.extra, "priority": b.priority, "how": b.how,+ "fencing_time_s": round(b.t, 2), "first_player": self.first, "p_cards": b.p_calls,+ "touches": b.T, "table_sha256": self.table.sha}+ if self.single:+ out["level"] = self.level+ return out+++_MODEL: dict = {}+++def _scene_model():+ if "m" not in _MODEL:+ import mujoco as mj+ _MODEL["m"] = mj.MjModel.from_xml_string(F.scene_xml())+ return _MODEL["m"]+++_RENDER: dict = {}+++class Fencing:+ name = "fencing"+ protocol = "turn"+ revision = REVISION+ source_dirs = [HERE]+ workers = ("render",)++ def build(self, cfg):+ return FencingMatch(cfg)++ def action_layer(self, level):+ if level != "low":+ raise ValueError("fencing-7 has the low level only (sport.toml [modes]): the intention for a phrase")+ return SchemaLayer()++ def worker_init(self, kind, seat, cfg):+ r = CAM.Renderer(seat)+ q = PH.table().guard_qpos()+ r.render([dict(label="on guard", qpos=q)] * CAM.N_FRAMES) # the GL context before 'ready'+ return r++ def worker_call(self, obj, kind, job):+ if obj is None: # in-process (core/local.py): one renderer per seat+ obj = _RENDER.get(job["seat"]) or _RENDER.setdefault(job["seat"], CAM.Renderer(job["seat"]))+ return {"png": obj.render(job["snaps"])}++ def scene(self, cfg):+ from renderers.base import Scene+ return Scene(xml=F.scene_xml(), assets={})++ def spec(self, cfg, seat, match):+ t = PH.table()+ C = t.counts()+ names = t.names+ out = dict(+ cameras=CAM.cam_info(), image=CAM.IMAGE_LAYOUT,+ intentions={s: INTENTION_DOC[s] for s in names},+ phrase_table=dict(+ note=("your chances against each intention of the opponent: for each pair 'yours|theirs', the phrases "+ f"out of {int(C[0, 0].sum())} (both ends of the piste x {t.J} x {t.J} start delays) that end "+ "with a touch for you alone, for the opponent alone, a double, or no touch; every phrase draws "+ "its delays and ends from the seed, the same for both fencers"),+ columns=["you", "opponent", "double", "none"],+ counts={f"{a}|{b}": [int(x) for x in C[i, j]] for i, a in enumerate(names)+ for j, b in enumerate(names)}),+ phrase=dict(gap_m=t.gap_m, start_delay_ms=[0, 10 * (t.J - 1)], max_s=t.max_s,+ source="measured in the fencing-6 world (docs/screening/fencing/phrase/)"),+ bout=dict(touches=BT.TOUCHES, time_s=BT.regulation_s(BT.TOUCHES), extra_minute_s=BT.EXTRA_S,+ passivity_s=BT.PASSIVE_S))+ if len(cfg.side_list()) == 1:+ lv = int(cfg.level or 1)+ out["opponent"] = dict(level=lv, levels="1-2: level 2 is stronger",+ plays=("it chooses its intention before each phrase from what it has seen of the "+ "bout (both fencers' intentions and the results), never from yours for "+ "this phrase; it knows the phrase table"))+ else:+ out["first_player"] = cfg.first or "A"+ return out++ def players(self):+ import builtin_players as bp+ return {"reference": bp.Reference, "rival": bp.Rival, "random": bp.Random}+++SPORT = Fencing()diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/reference_check.py b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/reference_check.pynew file mode 100644index 0000000000..cb57b9f4c6--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/reference_check.py@@ -0,0 +1,42 @@+"""The reference check of tools/check stage 5 (docs/screening/README.md "Reference check", sport.toml [reference]):+one bout of the reference (builtin_players.Reference) against the scripted fencer at a level, played as the step-4+screening on the sport plays it (docs/screening/fencing/phrase/game/step4_sport.py): the player answers every phrase+from `game spec` and its state, the phrase is fenced at once.++ perception "truth" and "camera" are the same player on the same view: a seat's observation of a phrase is the+ referee's record of it (the intentions, the delays, the result: `state` phrases), and the reference+ reads nothing else; the images (a half-way and an end snapshot of the last phrase) carry no+ information the record does not, so none are drawn++Returns {"won", "scores": [ours, theirs], "perception", "report": {"touches": [ours, both], "phrases_won": [phrases+with our touch only, phrases]}}.+"""+from __future__ import annotations++import os+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+++def reference_match(format: str = "bout", level: int | None = 1, seed: int = 1, perception: str = "truth") -> dict:+ if perception not in ("truth", "camera"):+ raise ValueError(f"perception must be truth or camera, not {perception!r}")+ if format != "bout":+ raise ValueError("the opponent calibration is for format bout (the scripted fencer)")+ if HERE not in sys.path:+ sys.path.insert(0, HERE)+ import builtin_players as BP+ import plugin as PL+ from core.sport import MatchConfig++ cfg = MatchConfig(sport="fencing", format="bout", seats=("A",), seed=int(seed),+ level=1 if level is None else int(level), action_level="low")+ m = PL.SPORT.build(cfg)+ ref = BP.Reference({"seat": "A", "action_level": "low", **PL.SPORT.spec(cfg, "A", m)}, "A", int(seed))+ while not m.bout.over:+ m.apply("A", ref.act({"state": {"seat": "A", **m.observe("A")}}))+ ours, theirs = m.bout.score["A"], m.bout.score[m.other("A")]+ won = sum(m._phrase_view(r, "A")["result"] == "you" for r in m.bout.log)+ return {"won": m.bout.winner == "A", "scores": [ours, theirs], "perception": perception,+ "report": {"touches": [ours, ours + theirs], "phrases_won": [won, len(m.bout.log)]}}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/rules_check.md b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/rules_check.mdnew file mode 100644index 0000000000..9ed4fbc2da--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/rules_check.md@@ -0,0 +1,42 @@+# Fencing (epee): the rules check (fencing-7, the phrase-level sport)++Every article and value cited by the fencing tasks (README, prompt, code), checked against the two PDFs of the FIE+rules, edition of August 2026:++- Technical Rules: https://static.fie.org/uploads/40/204126-Technical%20rules%20August%202026%20ang.pdf+- Material Rules: https://static.fie.org/uploads/40/204156-book%20material%20August%202026%20ang.pdf++The bout (bout.py):++| Article | The rulebook says | Implemented | |+|---|---|---|---|+| t.22 | the fencers come on guard before 'Play!' | every phrase starts on guard, 1.95 m apart (pelvis to pelvis) | deviation D1 (the distance: closer than the on-guard lines) |+| t.37 | duration = effective fencing time between 'Play!' and 'Halt!' | each phrase takes its measured time to the halt (3 s without a touch) | match |+| t.39.1 | direct elimination: 15 hits, or three periods of three minutes with a one-minute rest between | 15 touches, 9 minutes of fencing time as one period | deviation D4 (no rests) |+| t.40.1-2 | the bout ends at 15 hits or after 9 minutes of effective fencing time; more hits wins | the same | match |+| t.40.3 | equal at the end of regulation time: one minute for a deciding hit, the winner if still equal drawn by lot before it | the same (the lot seeded by the seed, drawn for the first fencer) | match |+| t.38.1.b | (pools) at epee at 4-4 a double hit is not counted | at 14-14 a double is not counted | deviation D5 (no clause for 14-14 in direct elimination) |+| t.44.1 | at the end of time the apparatus is cut off; hits registered before count | a phrase whose touch would come after the end of time ends without it | match |+| t.92 | both hit and both registered: a double hit, one hit against each | the same; in the extra minute the scores stay equal and the minute goes on | match |+| t.124 (1, 3) | one minute of fencing without a hit: 'Halt!'; direct elimination: 1st time P-red to both, 2nd time P-black to the lower score (equal: the lower seeding, lots among fencers not ranked); no P-card at 14-14; the minute restarts after each hit, hit off the target, annulled hit, penalty hit and at each period; not when the scores are equal at the end of regulation time | 60 s of fencing time without a touch: 1st P-red to both (a penalty touch each), 2nd P-black to the lower score (equal: a seeded lot), no card at 14-14, the minute restarts after touches, doubles, annulled doubles and P-red cards; not in the extra minute | match (one period: D4; the lot: D9) |+| t.170 (0.5) | the P-cards of t.124 | the same | match |++The phrases (measured in fencing-6's world, docs/screening/fencing/phrase/):++| Article | The rulebook says | In the measured phrases | |+|---|---|---|---|+| t.24 | fencing at close quarters allowed while the weapons can be wielded | arms and blades touching: the phrase goes on | match |+| t.25, t.33-t.35, t.56.10 | corps a corps, a limit crossed, a fall halt the phrase; a hit during or after a fall is annulled | fencing-6's referee: such a phrase would end without a touch; none of the 2916 phrases did | deviation D3 |+| t.90.1 | epee: thrusting weapon, hits only with the point | only the point registers | match |+| t.91 | target: the whole body, clothing and equipment | the whole robot, not its epee | match (D2: the robot is the body) |+| t.93 / t.94.1, Annexe B (d) | hits on the ground, between points or on the guard are not registered / annulled | the point on the floor, the opponent's blade, guard or grip does not register | match |+| m.14 | the epee ready for use weighs less than 770 g | 0.455 kg (a standard-parts epee, bodies/hands/epee.xml) | match |+| m.16.3 | blade at most 90 cm | 0.90 m | match |+| m.17.1 | guard passes a 13.5 cm gauge, depth 3-5.5 cm | 13.5 cm diameter (a 1 cm disc: the library's epee) | match (diameter; depth: D10) |+| m.19.2 | the point registers under a pressure of more than 750 g | more than 7.35 N (750 g x 9.81 m/s^2) on the point along the blade | match |+| Annexe B, B. Epee (b) | under 40 ms between hits: a double; over 50 ms: one hit; tolerance between | 45 ms lockout | match |+| Annexe B, B. Epee (c) | hits of 2-10 ms registered; nothing under 2 ms | at least 2 ms (3 consecutive 1 ms samples) | match |++Deviations that are not in the rulebook's articles: the fencers are the robot library's Unitree G1 humanoids on+NVIDIA's SONIC whole-body policy, commanded by intentions (D8); the ends of the piste are drawn per phrase (D11); the+sport is a preview, a strategy special case accepted by the maintainers (D12).diff --git a/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/sport.toml b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/sport.tomlnew file mode 100644index 0000000000..2d08e2c03e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/environment/sim/sport/sport.toml@@ -0,0 +1,239 @@+# fencing (epee): one FIE direct-elimination bout between two robot fencers, fenced phrase by phrase (docs/framework_zh.md+# §4.2, §8). fencing-7 (the owner's decision of 2026-10-13): the phrase-level construction. Every phrase starts on guard;+# each fencer chooses an intention, executed by fixed skills on a Unitree G1 humanoid (NVIDIA's SONIC whole-body+# policy tracking our fencing motions, the point skill on the sword arm); the phrases were measured in the fencing-6+# world and are replayed from a table (phrases.py). Screening: docs/screening/fencing.md (section 6, "Phrase-level+# construction"). The simulator: phrases.py (the phrases), bout.py (the bout referee), opponent.py (the scripted+# fencer), fencing.py + cameras.py (the scene and the images). The declarations below are data: the core,+# tools/generate.py, tools/check and the prompt read them.+#+# A PREVIEW (the maintainers, Chi, 2026-10-14): accepted as a strategy special case, publishable and open to model runs,+# but not counted in the main board's capability statistics (deviation D12). It departs from the construction rules+# (docs/construction_zh.md P1/P2/P5, docs/framework_zh.md §6.3.1): the command is a tactical intention for a whole+# phrase, and four intentions (rline, stop, counter, draw) carry a fixed, published trigger; the agent's skill is+# choosing and reading the opponent, not moving the robot. tools/check stage 1 fails on [capabilities] (none of a1-a3+# is 2), declared honestly. A next version should bring distance and timing back (choosing the starting gap or the+# moment to go, or a free starting gap once our own footwork and lunge policy is trained).++[sport]+name = "fencing"+title = "Robot epee fencing"+summary = "two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time"+protocol = "turn"+revision = "fencing-7+core-0.2" # bump on any change that alters play (the phrase table, the rules, the opponent, the observation)+physics = "the phrases: MuJoCo 3.3.7 (1 ms physics steps, 10 ms control steps), two Unitree G1 of the robot library (bodies/unitree_g1, 29 DOF; Unitree's motor torque-speed curves through the library's output stage) with epees, robot x robot, blade x body and blade x blade contacts (bodies/contacts.py), NVIDIA SONIC (GR00T-WholeBodyControl b042411) on the legs, waist and free arm, the point skill on the sword arm, fencing-6's apparatus and phrase referee; each of the 2916 phrases measured once in that world (it is deterministic: 2799 earlier measurements of 1953 of the phrases all ended as in that run, with the same result at the same step) and replayed from sports/fencing/phrases/table.json"+image = "ghcr.io/mll-lab-nu/eai-olympiad:0.1.0"+status = "sport"+publish = true # both formats are PREVIEW formats ([formats.*] preview = true, D12)+category = "robotics-sports-arena"++[body] # the robot library (bodies/README.md): the robot and its tool, for the scene+name = "unitree_g1"+hand = "epee" # bodies/hands/epee.xml (a real epee's mass, #88)+controllers = [] # the phrases are replayed; their controllers (SONIC, the point skill) ran when they were measured++[rulebook]+name = "FIE Technical Rules (t.) and Material Rules (m.), epee"+version = "August 2026"+url = "https://static.fie.org/uploads/40/204126-Technical%20rules%20August%202026%20ang.pdf"+articles = "on guard (t.22); fencing time (t.37); direct-elimination bout to 15 hits or three periods of three minutes with a one-minute rest, 9 minutes of effective fencing time; more hits wins; equal at time: one minute for a deciding hit, the winner if still equal drawn by lot before it (t.39, t.40); at 4-4 in a pool bout at epee a double hit is not counted (t.38.1.b); clock end (t.44); epee: point only, whole body target, double hits count for both (t.90-t.93); unwillingness to fight: one minute of fencing without a hit, P-red to both, then P-black to the lower score, no P-card at 14-14 (t.124, t.170 0.5); the epee under 770 g (m.14); point pressure more than 750 g (m.19.2); apparatus: hits of 2-10 ms registered, none under 2 ms, double-hit window 40-50 ms (Material Rules Annexe B, B. Epee); blade at most 90 cm (m.16.3), guard through a 13.5 cm gauge (m.17.1)"+material_rules = "https://static.fie.org/uploads/40/204156-book%20material%20August%202026%20ang.pdf"+rules_check = "sports/fencing/rules_check.md (every article and value checked against the two PDFs)"++[[deviations]]+id = "D1"+rule = "t.22, t.28-t.31 (the bout's phrases and footwork)"+text = "the bout is fenced phrase by phrase: every phrase starts with both fencers on guard 1.95 m apart (pelvis to pelvis), each fencer chooses one of nine intentions (`game spec` intentions) executed by fixed skills on the robot, each starts its intention after 0, 10, ... or 50 ms (drawn per phrase), and the phrase ends at the first touch or after 3 s without one; distance, footwork between phrases and the length of the piste are not part of the bout (the screening found the robots' footwork too slow for a bout over the piste: docs/screening/fencing.md)"+affects_result = true+[[deviations]]+id = "D2"+rule = "t.91, m.19, Material Rules Annexe B"+text = "the robot's whole structure is the target (t.91: the whole body), its epee (guard, blade, grip) is not; the apparatus measures the force on the point along the blade (> 7.35 N for >= 2 ms, three consecutive 1 ms samples; lockout 45 ms, inside the 40-50 ms tolerance)"+affects_result = true+[[deviations]]+id = "D3"+rule = "t.24, t.25, t.33-t.35, t.56.10"+text = "a phrase that ended in a fall, a corps-a-corps or a fencer over a limit counts as a phrase without a touch (none of the 2916 measured phrases did)"+affects_result = false+[[deviations]]+id = "D4"+rule = "t.39, t.40"+text = "the 9 minutes of fencing time are one period (no one-minute rests); every phrase takes its measured fencing time (to the halt, 3 s without a touch)"+affects_result = true+[[deviations]]+id = "D5"+rule = "t.38.1.b"+text = "at 14-14 a double touch is not counted (the pool bout's rule at 4-4 applied to the 15-touch bout; the 2026 rules have no clause for 14-14 in direct elimination)"+affects_result = true+[[deviations]]+id = "D6"+rule = "t.158-t.170"+text = "no cards or penalties (the robots cannot commit the faults they punish), except the P-cards for unwillingness to fight (t.124)"+affects_result = false+[[deviations]]+id = "D7"+rule = "t.39 (competition formula)"+text = "one direct-elimination bout instead of a competition"+affects_result = false+[[deviations]]+id = "D8"+rule = "-"+text = "the fencer is the robot library's Unitree G1 (bodies/unitree_g1) with the epee on its right wrist mount, its legs, waist and free arm on NVIDIA's SONIC whole-body policy (tracking our en garde, step and lunge motions), its sword arm on the point skill; a lunge from guard covers about 0.25 m in 0.4 s, so the phrases are fenced from 1.95 m, where a lunge reaches the chest; you command it by intentions, not by motions"+affects_result = true+[[deviations]]+id = "D9"+rule = "t.124"+text = "unwillingness to fight as the FIE applies it to direct-elimination bouts (t.124.1): one minute of fencing time without a hit -> 'Halt!'; the first time a P-red card to both fencers, a penalty hit each; the second time the P-black card to the fencer with the lower score, who loses the bout, at equal scores to the fencer who loses a seeded lot (t.124.1.b.i: lots for fencers not in the FIE ranking); no P-card at 14-14 (t.124.3.a): the minute restarts; the minute restarts after each hit, double, annulled double and penalty hit (t.124.3.d), not after a phrase without a touch; t.124 does not apply in the extra minute (t.124.3.f)"+affects_result = true+[[deviations]]+id = "D10"+rule = "m.14-m.19"+text = "the epee is rigid (its blade does not bend) and its point is a sphere; its mass is a real standard-parts epee's (Leon Paul: 0.455 kg, balance 12 cm in front of the guard; bodies/hands/epee.xml)"+affects_result = false+[[deviations]]+id = "D11"+rule = "-"+text = "the two ends of the piste are not exactly alike in the simulation (the same phrase fenced from the other end ends differently in 205 of the 1431 pairs of mirrored phrases, about one in seven), so each phrase draws the end each fencer fences from, with probability 1/2 each: both fencers meet the same chances"+affects_result = true+[[deviations]]+id = "D12"+rule = "-"+text = "a preview, accepted by the maintainers (2026-10-14) as a strategy special case: a symmetric zero-sum game of intentions whose phrase table comes from the physics; the agent controls neither distance nor timing, so it is tested on reading the opponent only (capabilities a1 0, a2 0, a3 1, b2 2; tools/check stage 1 requires one of a1-a3 primary and fails), against construction_zh.md P1/P2/P5 (skills take motion targets and do not choose strategy) and framework_zh.md §6.3.1; publishable and open to model runs, not counted in the main board's capability statistics (both formats `preview = true`: never an official configuration, no hidden seeds)"+affects_result = false++[formats.bout] # seat A against the scripted fencer (opponent.Opponent; side B)+preview = true # D12: playable, never official (core 0.2.21: official_config = 0; tools/seeds.py: no cell)+seats = ["A"]+opponent = true # success = winning a valid bout (core/grading.py)+levels = [1, 2] # the opponent level (RCB_LEVEL; default 1)+[formats.duel]+preview = true # D12, as bout+seats = ["A", "B"]+first = ["A", "B"] # the first player chooses first in every phrase (kept hidden), is the first fencer of the phrase draws and of the lots++[modes]+action_levels = ["low"] # the intention for a phrase is the robot's whole command, as a release command in the other turn sports+plays = ["program"]++[timing]+clock_s = 3600 # turn protocol: each seat's chess clock, on its own turn only+start_timeout_s = 1800++[actions.cli] # `game phrase lunge`+low = { phrase = ["intention"] }++[observation]+fields = ["score", "phrase", "fencing_time_s", "time_left_s", "extra_minute", "priority", "passivity", "phrases",+ "committed"]+renderer = "mujoco" # the images are drawn by the sport (cameras.py, MuJoCo osmesa) in each seat's render worker+frame_budget_ms = 4000 # 4 tiles of 800 x 360, osmesa on the CPU+columns = 2++[spec] # the rule constants (/spec adds the intentions, the phrase table, the cameras)+bout = "one FIE direct-elimination bout (t.39-t.40): the first to 15 touches wins; 9 minutes of fencing time (one period); at time the fencer ahead wins; at equal scores one more minute for a deciding touch with priority drawn by lot before it (seeded), the priority holder winning if still equal; a double touch counts for both except at 14-14 (not counted); in the extra minute a double leaves the scores equal. Unwillingness to fight (t.124): one minute of fencing time without a touch: the first time both fencers get a P-red card, a penalty touch each; the second time the fencer with the lower score gets the P-black card and loses the bout (at equal scores: the one who loses a lot, seeded); no card at 14-14; the minute restarts after every touch, double, annulled double and penalty touch, not after a phrase without a touch; it does not apply in the extra minute (observation `passivity`)"+phrase = "every phrase starts with both fencers on guard 1.95 m apart; each fencer has chosen one intention (`game spec` intentions) and starts it after 0, 10, 20, 30, 40 or 50 ms (each equally likely, drawn for each fencer and phrase from the seed, after both have chosen); the phrase ends at the first touch (the apparatus: the point's force along the blade above 7.35 N for 2 ms on the opponent's body; the other's touch within 45 ms is a double) or after 3 s without one; it takes its fencing time from the bout clock (a clock that ends during a phrase ends it without a touch, t.44). The phrases were measured in MuJoCo (D1, D8); `game spec` phrase_table gives, for every pair of intentions, how many of the 72 equally likely phrases (36 pairs of delays x both ends of the piste) end with a touch for you, for the opponent, a double or none"+duel = "both players choose their intention for the next phrase; the first player's choice is kept hidden from the other until the phrase is fenced"+observation = "the state: the score, the phrase number, the fencing time and the time left, the extra minute and the priority, the passivity minute and the P-cards, and every phrase so far (your intention and the opponent's, both start delays, the result, its fencing time, the score after it, cards); the image: 2 rows (side camera beside the piste, top camera above it) x 2 columns (the last phrase half-way and at its end) of 800 x 360 tiles, your robot red, the opponent blue, the points yellow"+scripted_opponent = "format bout: the computer fencer chooses its intention before each phrase from what it has seen of the bout (both fencers' intentions and the results), never from your choice for this phrase; it knows the phrase table. Level 1 reads you with a few simple models of a player (repeats, answers, copies, plays what just won, goes round the menu) but mostly keeps a slow habit (the best answer to your whole-bout mix); level 2 predicts your next intention from your patterns, also models how you read it, answers what it expects, and now and then plays the table's equilibrium mix"++[tiebreaks]+order = ["touches", "passivity", "time", "deciding_touch", "priority"]+text = "the first to 15 touches wins (FIE t.40.1); a second minute without a touch (unwillingness to fight, FIE t.124) loses the bout for the fencer with the lower score, at equal scores for the one who loses a lot (seeded); at the end of the 9 minutes the fencer ahead wins; at equal scores one more minute is fenced and the first touch decides; if the scores are still equal after it, the fencer with priority, drawn by lot (seeded) before the extra minute, wins (FIE t.40.3)"+last_resort_in_prompt = true++[[exploits]]+id = "E1"+text = "an unknown intention, a wrong type, an extra field (a start delay or an end chosen by the player) is refused and changes nothing"+test = "test_exploit_bad_intentions_refused"+[[exploits]]+id = "E2"+text = "the scripted fencer chooses its intention for a phrase without seeing the agent's: after the same bout so far, every choice of the agent meets the same intention"+test = "test_exploit_opponent_cannot_see_your_choice"+[[exploits]]+id = "E3"+text = "format duel: the first player's choice stays out of the other player's observation until the phrase is fenced"+test = "test_exploit_duel_choice_hidden"+[[exploits]]+id = "E4"+text = "`game spec` phrase_table is the table the bout plays (all 2916 phrases, 72 per pair over both ends), and every phrase of a bout is the table's phrase for its delays and ends"+test = "test_exploit_spec_is_the_simulator"+[[exploits]]+id = "E5"+text = "the start delays and the ends of the piste come from the seed and the phrase number, not from the intentions (uniform over 0-50 ms; each end with probability 1/2)"+test = "test_exploit_phrase_draws_seeded_not_chosen"+[[exploits]]+id = "E6"+text = "every bout has a winner (touches, passivity, time, the deciding touch or the priority), also when nobody ever touches"+test = "test_exploit_no_draws"+[[exploits]]+id = "E7"+text = "stalling does not pay: both fencers retreating every phrase get the P-red cards after a minute and the P-black card decides the bout after the next"+test = "test_exploit_passivity_cards"+[[exploits]]+id = "E8"+text = "a fixed intention every phrase, or a uniformly random one, loses the majority of its bouts against level 1"+test = "test_exploit_simple_programs_lose"+[[exploits]]+id = "E9"+text = "at 14-14 a double is not counted and the minute restarts; at 13-14 it ends the bout"+test = "test_exploit_double_at_14_14_not_counted"+[[exploits]]+id = "E10"+text = "a phrase whose touch would come after the end of time ends without it (t.44); equal scores at time start the extra minute with priority drawn"+test = "test_exploit_clock_ends_the_phrase"++[players]+reference = "reference" # Sport.players() names: reads only `game spec` and the state+reference_class = "builtin_players:Reference"+check = ["random"] # policies for the generic tests++[fairness]+policy = "rival" # the reference drawing from a stream of the seed and its seat+matches_per_order = 400 # N = 800: 95% CI about +-3.5 pp+max_advantage_pp = 5+mirror = "exact" # the phrase draws and the lots follow the first order, not the seat++[official]+seeds = [1, 2, 3, 101, 111, 121, 202, 212, 222]+first_any = true+levels = [1, 2]++[score] # the continuous score (core/score.py)+name = "touch_share"+text = "touches scored / touches scored by both fencers (a double counts for both; 0.5 if neither scored)"+from = "share"+forfeit = 0.0+range = [0, 1]++[reference] # tools/check stage 5, the reference check (docs/screening/README.md)+match = "reference_check:reference_match" # one bout of the reference against the scripted fencer, as step 4 plays it; camera = truth (no images to read)+seeds = 200 # seeds 1..200 per level: at the step-4 rates (61.5 %, 48.0 %) 20 seeds fail the check 1 time in 3, 200 seeds 1 in 300+camera_seeds = 200 # the same player as truth, so the same seeds++[golden]+episodes = "golden" # sports/fencing/golden/<case>/++[[tasks]]+format = "bout"+action_level = "low"+id = "fencing-bout-wallclock-program-standard" # the Season-1 task names ([[tasks]] id)+[[tasks]]+format = "duel"+action_level = "low"+id = "fencing-duel-wallclock-program-standard"++[broadcast] # spectators: the replay video's camera+camera = { name = "broadcast", pos = [0.0, -7.95, 1.75], lookat = [0.0, 0.0, 0.8], fovy_deg = 45, width = 960, height = 400 }++[capabilities] # docs/capabilities_zh.md+a1 = 0 # no perception: the state gives every phrase's intentions and result+a2 = 0 # the phrases' physics is measured; the agent does not predict it+a3 = 1 # what each intention does on this robot (the phrase table), not how to move it+a4 = 0 # turn-based: no real-time timing+b1 = 1 # FIE rules (15 touches, 14-14, the clock, unwillingness to fight, the extra minute, priority) shape the bout and the state, but no evidence yet that using them pays: a reference that stalls when ahead lost 5 points of touch share (screening report, section 6)+b2 = 2 # reading the opponent: the levels adapt to the agent's patterns; the reference without reading (the equilibrium mix) does clearly worse at level 1 (screening report, section 6)+b3 = 0+physics = ["contact"]++[check] # tools/check limits+stage_timeout_s = 28800 # stage 4: 800 rendered duels in the image (osmesa, 2 seats' 2 x 2 tiles per phrase) at about 23 s each, about 5 hdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/instruction.md b/tasks/roboolympics-fencing-bout-i02-standard/instruction.mdnew file mode 100644index 0000000000..cda2e5f6a6--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/instruction.md@@ -0,0 +1,69 @@+# Robot epee fencing: program play (bout)++You play robot epee fencing against a scripted opponent (you are seat `A`). Two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time.+This is RoboOlympics task `fencing-bout-wallclock-program-standard` (revision `fencing-7+core-0.2`), one frozen instance: the scripted opponent at level 2; the seed is fixed and never shown. The simulator service is at `http://localhost:8000`.++## Time+Nothing moves while you think: the world waits for the player whose turn it is. Each player has a chess clock of 60 minutes of real time, running only on its own turn (thinking, tool calls, your programs and your reviews all count). **If your clock runs out, you lose.**++After each of your actions (except one that ends the match), send `game ready "WHY" "PLAN"` (a short review) before the game goes on.+The match is graded when your session ends: stay until it is over. **If your session ends before the match is over, you lose the match** (a valid result, success 0), also if you never sent `game start`.++## Write a program+You may write a program that observes, measures in the images, computes your next action and sends it, without a+new model response for each action. You stay in the loop: watch its log, and stop, fix and restart it whenever+needed. Only you send `game start` and `game ready`.++- Use only the camera images, the service's replies and this document; no simulator internals or hidden state.+- One action at a time: an action sent before the previous one has returned is refused (HTTP 429).+- Your container: Python 3.12 with numpy, SciPy and Pillow; the network reaches only your model's API and the package registries. Keep your scripts, logs+ and notes in `/app/output/`.++## Interface+Use the `game` command, or the same calls as HTTP with JSON at `http://localhost:8000/<SEAT>/` (your seat is `$SEAT`):++| `game` command | HTTP | |+| --- | --- | --- |+| `game spec` | `GET /spec` | the actions (types, fields, ranges), the cameras with their intrinsics, the rule constants |+| `game status` | `GET /status` | the current state, no image |+| `game start` | `POST /start {}` | you are ready; the match begins when every seat has started |+| `game wait` | `POST /wait {"timeout_s": 60}` | block until it is your turn (or the match is over) |+| `game observe` | `POST /observe {}` | the state and the camera images (one PNG of tiles: `observation.tiles`) |+| `game act JSON` | `POST /act JSON` | one action |+| `game phrase INTENTION` | `POST /act {"type":"phrase", ...}` | one action (`game spec` lists the fields and ranges) |+| `game ready "WHY" "PLAN"` | `POST /ready {"why":"...","plan":"..."}` | your review after each of your actions |++Errors: 400 = an invalid action (nothing happens), 409 = not now (not your turn, or a review is due), 429 = one+action in flight, or more than 20 requests per second or 4 open requests from your seat (empty body: retry more slowly).++## Rules+- two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time.+- `bout`: one FIE direct-elimination bout (t.39-t.40): the first to 15 touches wins; 9 minutes of fencing time (one period); at time the fencer ahead wins; at equal scores one more minute for a deciding touch with priority drawn by lot before it (seeded), the priority holder winning if still equal; a double touch counts for both except at 14-14 (not counted); in the extra minute a double leaves the scores equal. Unwillingness to fight (t.124): one minute of fencing time without a touch: the first time both fencers get a P-red card, a penalty touch each; the second time the fencer with the lower score gets the P-black card and loses the bout (at equal scores: the one who loses a lot, seeded); no card at 14-14; the minute restarts after every touch, double, annulled double and penalty touch, not after a phrase without a touch; it does not apply in the extra minute (observation `passivity`)+- `phrase`: every phrase starts with both fencers on guard 1.95 m apart; each fencer has chosen one intention (`game spec` intentions) and starts it after 0, 10, 20, 30, 40 or 50 ms (each equally likely, drawn for each fencer and phrase from the seed, after both have chosen); the phrase ends at the first touch (the apparatus: the point's force along the blade above 7.35 N for 2 ms on the opponent's body; the other's touch within 45 ms is a double) or after 3 s without one; it takes its fencing time from the bout clock (a clock that ends during a phrase ends it without a touch, t.44). The phrases were measured in MuJoCo (D1, D8); `game spec` phrase_table gives, for every pair of intentions, how many of the 72 equally likely phrases (36 pairs of delays x both ends of the piste) end with a touch for you, for the opponent, a double or none+- `duel`: both players choose their intention for the next phrase; the first player's choice is kept hidden from the other until the phrase is fenced+- `observation`: the state: the score, the phrase number, the fencing time and the time left, the extra minute and the priority, the passivity minute and the P-cards, and every phrase so far (your intention and the opponent's, both start delays, the result, its fencing time, the score after it, cards); the image: 2 rows (side camera beside the piste, top camera above it) x 2 columns (the last phrase half-way and at its end) of 800 x 360 tiles, your robot red, the opponent blue, the points yellow+- `scripted_opponent`: format bout: the computer fencer chooses its intention before each phrase from what it has seen of the bout (both fencers' intentions and the results), never from your choice for this phrase; it knows the phrase table. Level 1 reads you with a few simple models of a player (repeats, answers, copies, plays what just won, goes round the menu) but mostly keeps a slow habit (the best answer to your whole-bout mix); level 2 predicts your next intention from your patterns, also models how you read it, answers what it expects, and now and then plays the table's equilibrium mix+- Winner: the first to 15 touches wins (FIE t.40.1); a second minute without a touch (unwillingness to fight, FIE t.124) loses the bout for the fencer with the lower score, at equal scores for the one who loses a lot (seeded); at the end of the 9 minutes the fencer ahead wins; at equal scores one more minute is fenced and the first touch decides; if the scores are still equal after it, the fencer with priority, drawn by lot (seeded) before the extra minute, wins (FIE t.40.3). There are no draws.+- Deviation D1 (rulebook t.22, t.28-t.31 (the bout's phrases and footwork)): the bout is fenced phrase by phrase: every phrase starts with both fencers on guard 1.95 m apart (pelvis to pelvis), each fencer chooses one of nine intentions (`game spec` intentions) executed by fixed skills on the robot, each starts its intention after 0, 10, ... or 50 ms (drawn per phrase), and the phrase ends at the first touch or after 3 s without one; distance, footwork between phrases and the length of the piste are not part of the bout (the screening found the robots' footwork too slow for a bout over the piste: docs/screening/fencing.md)+- Deviation D2 (rulebook t.91, m.19, Material Rules Annexe B): the robot's whole structure is the target (t.91: the whole body), its epee (guard, blade, grip) is not; the apparatus measures the force on the point along the blade (> 7.35 N for >= 2 ms, three consecutive 1 ms samples; lockout 45 ms, inside the 40-50 ms tolerance)+- Deviation D4 (rulebook t.39, t.40): the 9 minutes of fencing time are one period (no one-minute rests); every phrase takes its measured fencing time (to the halt, 3 s without a touch)+- Deviation D5 (rulebook t.38.1.b): at 14-14 a double touch is not counted (the pool bout's rule at 4-4 applied to the 15-touch bout; the 2026 rules have no clause for 14-14 in direct elimination)+- Deviation D8 (rulebook -): the fencer is the robot library's Unitree G1 (bodies/unitree_g1) with the epee on its right wrist mount, its legs, waist and free arm on NVIDIA's SONIC whole-body policy (tracking our en garde, step and lunge motions), its sword arm on the point skill; a lunge from guard covers about 0.25 m in 0.4 s, so the phrases are fenced from 1.95 m, where a lunge reaches the chest; you command it by intentions, not by motions+- Deviation D9 (rulebook t.124): unwillingness to fight as the FIE applies it to direct-elimination bouts (t.124.1): one minute of fencing time without a hit -> 'Halt!'; the first time a P-red card to both fencers, a penalty hit each; the second time the P-black card to the fencer with the lower score, who loses the bout, at equal scores to the fencer who loses a seeded lot (t.124.1.b.i: lots for fencers not in the FIE ranking); no P-card at 14-14 (t.124.3.a): the minute restarts; the minute restarts after each hit, double, annulled double and penalty hit (t.124.3.d), not after a phrase without a touch; t.124 does not apply in the extra minute (t.124.3.f)+- Deviation D11 (rulebook -): the two ends of the piste are not exactly alike in the simulation (the same phrase fenced from the other end ends differently in 205 of the 1431 pairs of mirrored phrases, about one in seven), so each phrase draws the end each fencer fences from, with probability 1/2 each: both fencers meet the same chances++## Geometry and physics+Everything you need is in `game spec`: the world frame, the release point, the cameras (pose, field of view, size,+`focal_px`, `principal_point_px`; pinhole: u = cx + f * x_right / depth, v = cy - f * y_up / depth) and the+execution scatter. The physics engine is the phrases: MuJoCo 3.3.7 (1 ms physics steps, 10 ms control steps), two Unitree G1 of the robot library (bodies/unitree_g1, 29 DOF; Unitree's motor torque-speed curves through the library's output stage) with epees, robot x robot, blade x body and blade x blade contacts (bodies/contacts.py), NVIDIA SONIC (GR00T-WholeBodyControl b042411) on the legs, waist and free arm, the point skill on the sword arm, fencing-6's apparatus and phrase referee; each of the 2916 phrases measured once in that world (it is deterministic: 2799 earlier measurements of 1953 of the phrases all ended as in that run, with the same result at the same step) and replayed from sports/fencing/phrases/table.json.++## External material+You may install packages you need (pip, apt), and you may read anything installed in your container, the simulator's and this benchmark's own source code included. Please solve the task yourself: do not search the web for, or download, a ready-made solution to it, such as published or reference solutions, recorded demonstrations, or policies trained for it. This is an honour rule; trials are reviewed. The network reaches your model's API and the package registries (PyPI, Debian / Ubuntu archives) only.++## Resource limits+Limits for your agent environment, your own container only (the simulator in the `sim` service is the benchmark's and does not count): at most **4 GiB of memory**, **512 processes** and **20 GiB** of new files under `/app`, `/tmp` and `/root`; your container has no GPU. These limits may be enforced (from protocol v1.2 on): when enforcement is on, exceeding one for 60 s within any 2 minutes, or a process killed for lack of memory, ends the trial as a failure (reward 0), whatever the deliverable. A monitor outside your container measures every few seconds; the current values are in `/run/rcb-limits/usage.json`. CPU is capped at 2 cores for your container; the cap only slows you down.++## Time limit+You have 7200 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task.++This is wall-clock time from the start of your session; the time you wait for the simulator service counts. When it is up you are stopped without warning and graded on what stands at that moment, as the sections above say. The service does not count this limit for you: the clocks it reports are the game's own. Your session started when you received this task. `/run/rcb-limits/usage.json`, rewritten every few seconds, gives the time left on this limit (`time_left_s`) and its end (`deadline_utc`), counted from a little before your session started, so it never gives you more time than you have: read it (or run `date`) before you decide that time is short, never guess. Waiting counts too: a tool call that sends input to a process that keeps running (an interactive interpreter, a simulator loop, a server) can wait for the whole wait or yield time you give it (for example Codex's `yield_time_ms`) even when the answer is printed at once, so give such calls a short wait and poll again if the output is not complete, or run one-shot scripts that exit when they are done. Installing packages is not cheating (`## External material` above).diff --git a/tasks/roboolympics-fencing-bout-i02-standard/solution/builtin_players.py b/tasks/roboolympics-fencing-bout-i02-standard/solution/builtin_players.pynew file mode 100644index 0000000000..9b95f8886e--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/solution/builtin_players.py@@ -0,0 +1,245 @@+"""fencing's built-in players (fencing-7, the phrase-level sport; the same action interface as a model's program:+core/client.py plays them over HTTP).++ Reference a reader of the opponent (since 2026-10-14; screening report, section 6 "fencing-7"): ten hypotheses+ about the opponent's next intention, each scored by how well it predicted the opponent's past choices+ (decayed log-score); the best one is answered with the logit answer (20 per net touch) by the phrase+ table of `game spec`, and in 10 % of the phrases a draw from the table's equilibrium mix. Five are the+ pattern reader of step 4 (2026-10-13): the opponent's mix; after its last intention; after its last two;+ after my last one; after the last pair (tables of decayed counts). Five model how the opponent reads me:+ it predicts MY next intention from my mix, after my last one, after my last two, after its last one or+ after the last pair, and answers that prediction (logit 40, 5 % spread). The pattern reader alone is+ the weak form of the capability-sensitivity check, the equilibrium mix the strong form. It reads only+ `game spec` and the state (the phrases so far), and draws from its own stream (the seed).+ Rival the reference drawing from a stream of the seed and its seat (the fairness policy: two references with+ the same seed would draw alike).+ Random a uniform intention every phrase (generic tests).+No simulator import: this file runs in the player's container as the task's oracle (numpy only)."""+from __future__ import annotations++import math++import numpy as np++PRIOR = 1.0+RESULT = {"you": 1, "opponent": -1, "double": 2, "double, not counted at 14-14": 2, "none": 0}+++def solve_zero_sum(M, max_iter=10000):+ """(value, x, y) of the zero-sum game where the row player maximises x' M y (simplex, Bland's rule)"""+ M = np.asarray(M, float)+ m, n = M.shape+ c = 1.0 - M.min()+ T = np.zeros((m + 1, n + m + 1))+ T[:m, :n] = M + c+ T[:m, n:n + m] = np.eye(m)+ T[:m, -1] = 1.0+ T[m, :n] = -1.0+ basis = list(range(n, n + m))+ for _ in range(max_iter):+ neg = np.flatnonzero(T[m, :-1] < -1e-12)+ if len(neg) == 0:+ break+ col = int(neg[0])+ colv = T[:m, col]+ pos = colv > 1e-12+ ratios = np.full(m, np.inf)+ ratios[pos] = T[:m, -1][pos] / colv[pos]+ ties = np.flatnonzero(ratios <= ratios.min() + 1e-12)+ r = int(min(ties, key=lambda k: basis[k]))+ T[r] /= T[r, col]+ for k in range(m + 1):+ if k != r and T[k, col] != 0.0:+ T[k] -= T[k, col] * T[r]+ basis[r] = col+ else:+ raise RuntimeError("simplex did not converge")+ z = T[m, -1]+ yp = np.zeros(n)+ for r, b in enumerate(basis):+ if b < n:+ yp[b] = T[r, -1]+ xp = np.clip(T[m, n:n + m], 0.0, None)+ return float(1.0 / z - c), xp / xp.sum(), yp / yp.sum()+++def table_from_spec(spec):+ """(intention names, my expected net touches per phrase T[mine, theirs], the equilibrium mix) from `game spec`"""+ names = list(spec["intentions"])+ pt = spec["phrase_table"]+ C = np.array([[pt["counts"][f"{a}|{b}"] for b in names] for a in names], float)+ P = (C + PRIOR) / (C.sum(-1, keepdims=True) + 4 * PRIOR)+ T = P[..., 0] - P[..., 1]+ _, x, _ = solve_zero_sum(T)+ return names, T, x+++class Reader:+ """the pattern reader (screening: game.py Context, beta 20, eps_eq 0.1)"""+ CONTEXTS = ("m", "o1", "o2", "me1", "pair")++ def __init__(self, T, eq, rng, beta=20.0, eps_eq=0.1, decay=0.9, prior=0.3, score_decay=0.8):+ self.P, self.eq, self.rng, self.n = T, eq, rng, len(eq)+ self.beta, self.eps_eq, self.decay, self.prior, self.score_decay = beta, eps_eq, decay, prior, score_decay+ self.hist = []+ self.tabs = {c: {} for c in self.CONTEXTS}+ self.score = {c: 0.0 for c in self.CONTEXTS}+ self._keys, self._preds = {}, {}+ self.used = "m"++ def _key(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "o1":+ return h[-1][1]+ if c == "o2":+ return (h[-2][1], h[-1][1]) if len(h) >= 2 else None+ if c == "me1":+ return h[-1][0]+ return (h[-1][1], h[-1][0])++ def _pred(self, c, key):+ t = self.tabs[c].get(key) if key is not None else None+ if t is None:+ return None+ p = t + self.prior+ return p / p.sum()++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ best, bs = "m", self.score["m"]+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ if p is not None and self.score[c] > bs + 1e-12:+ best, bs = c, self.score[c]+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def choose(self):+ p = self.dist()+ return int(min(np.searchsorted(np.cumsum(p), self.rng.random(), side="right"), len(p) - 1))++ def observe(self, mine, other, res):+ for c, p in self._preds.items():+ self.score[c] = self.score_decay * self.score[c] + math.log(p[other])+ self.hist.append((mine, other, res))+ for c, key in self._keys.items():+ if key is None:+ continue+ t = self.tabs[c].get(key)+ if t is None:+ t = self.tabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[other] += 1.0+++class MindReader(Reader):+ """the pattern reader plus five hypotheses that the opponent predicts my next intention (from the contexts MINE of+ my own play) and answers it"""+ MINE = ("m", "me1", "me2", "o1", "pair")++ def __init__(self, *a, beta_o=40.0, eps_o=0.05, **k):+ super().__init__(*a, **k)+ self.beta_o, self.eps_o = beta_o, eps_o+ self.mtabs = {c: {} for c in self.MINE}+ for c in self.MINE:+ self.score["tom_" + c] = 0.0+ self._mkeys = {}++ def _mkey(self, c):+ h = self.hist+ if c == "m":+ return 0+ if not h:+ return None+ if c == "me1":+ return h[-1][0]+ if c == "me2":+ return (h[-2][0], h[-1][0]) if len(h) >= 2 else None+ if c == "o1":+ return h[-1][1]+ return (h[-1][0], h[-1][1])++ def dist(self):+ self._keys = {c: self._key(c) for c in self.CONTEXTS}+ self._mkeys = {c: self._mkey(c) for c in self.MINE}+ marg = self._pred("m", 0)+ if marg is None:+ marg = np.full(self.n, 1.0 / self.n)+ self._preds = {"m": marg}+ for c in self.CONTEXTS[1:]:+ p = self._pred(c, self._keys[c])+ self._preds[c] = marg if p is None else p+ mmarg = self.mtabs["m"].get(0)+ for c in self.MINE:+ t = self.mtabs[c].get(self._mkeys[c]) if self._mkeys[c] is not None else None+ if t is None:+ t = mmarg+ q = np.full(self.n, 1.0 / self.n) if t is None else (t + self.prior) / (t + self.prior).sum()+ v = -self.P.T @ q # the opponent's net per intention against my predicted mix+ a = np.exp(self.beta_o * (v - v.max()))+ a /= a.sum()+ self._preds["tom_" + c] = self.eps_o / self.n + (1 - self.eps_o) * a+ best = max(self._preds, key=lambda c: (self.score[c], c == "m"))+ self.used = best+ v = self.P @ self._preds[best]+ core = np.exp(self.beta * (v - v.max()))+ core /= core.sum()+ return self.eps_eq * self.eq + (1.0 - self.eps_eq) * core++ def observe(self, mine, other, res):+ for c, key in self._mkeys.items():+ if key is None:+ continue+ t = self.mtabs[c].get(key)+ if t is None:+ t = self.mtabs[c][key] = np.zeros(self.n)+ t *= self.decay+ t[mine] += 1.0+ super().observe(mine, other, res)+++class Reference:+ def __init__(self, spec, seat, seed=0):+ self.names, T, eq = table_from_spec(spec)+ self.idx = {s: i for i, s in enumerate(self.names)}+ self.r = MindReader(T, eq, self._rng(seed, seat))+ self.seen = 0++ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12]) # by seed, not by seat: mirror runs match++ def act(self, view):+ ph = view["state"].get("phrases") or []+ for p in ph[self.seen:]:+ self.r.observe(self.idx[p["you"]], self.idx[p["opponent"]], RESULT[p["result"]])+ self.seen = len(ph)+ return {"type": "phrase", "intention": self.names[self.r.choose()]}++ def review(self, reply):+ return ("read the phrase's result", f"answer the opponent's next intention as predicted by '{self.r.used}'")+++class Rival(Reference):+ def _rng(self, seed, seat):+ return np.random.default_rng([int(seed), 12, sum(map(ord, str(seat)))])+++class Random:+ def __init__(self, spec, seat, seed=0):+ self.names = list(spec["intentions"])+ self.g = np.random.default_rng(int(seed) * 7919 + 17) # by seed, not by seat: mirror runs match++ def act(self, view):+ return {"type": "phrase", "intention": self.names[int(self.g.integers(len(self.names)))]}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/solution/oracle_play.py b/tasks/roboolympics-fencing-bout-i02-standard/solution/oracle_play.pynew file mode 100644index 0000000000..cc345a9a2b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/solution/oracle_play.py@@ -0,0 +1,5 @@+"""Harbor oracle on any seat: the sport's reference player (builtin_players:Reference, camera images and /spec only) over+HTTP through the core's client loop (ro_client.py = core/client.py)."""+import ro_client++ro_client.main(["builtin_players:Reference"])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/solution/ro_client.py b/tasks/roboolympics-fencing-bout-i02-standard/solution/ro_client.pynew file mode 100644index 0000000000..84258d872b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/solution/ro_client.py@@ -0,0 +1,147 @@+"""Contract ①, the player's side: a stdlib client of the match service and the loop that lets a built-in player (the+sport's reference player, scripted opponents, check policies) play over HTTP exactly as a model's program would.++A built-in player is an object made by factory(spec, seat, seed) with+ act(view) -> body | None view = {"state": <the seat's state>, "observation": <the /observe observation>}+ (body = the /act request; None = nothing now, realtime only)+ review(reply) -> (why, plan) optional; called after each own action (turn) or at each review (realtime)+ message(view) -> text | None optional (realtime, core 0.2.21): a team-channel message to the seat's teammates+ (POST /say; refused messages, e.g. faster than the channel allows, are dropped)++ python3 -m core.client MODULE:FACTORY (SIM_URL, SEAT; e.g. the task's solution/oracle_play.py)+"""+from __future__ import annotations++import importlib+import json+import os+import sys+import time+import urllib.error+import urllib.request+++class Seat:+ """One seat's calls. The service allows 20 requests per second and 4 open requests per seat: the client keeps+ under that (MIN_GAP_S between calls) and retries a request the HTTP layer refused before reading it (a bare 429+ or a reset connection), which never reached the match."""+ MIN_GAP_S = 0.06++ def __init__(self, base: str, seat: str, timeout: float = 600):+ self.base, self.seat, self.timeout, self.last = base.rstrip("/"), seat, timeout, 0.0++ def call(self, ep: str, body: dict | None = None, tries: int = 20) -> dict:+ for i in range(tries):+ time.sleep(max(0.0, self.last + self.MIN_GAP_S - time.monotonic()))+ self.last = time.monotonic()+ req = urllib.request.Request(f"{self.base}/{self.seat}/{ep}",+ data=None if body is None else json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=self.timeout) as r:+ return json.load(r)+ except urllib.error.HTTPError as e:+ raw = e.read()+ if e.code == 429 and not raw and i + 1 < tries: # the HTTP layer's limit, not the match's+ time.sleep(0.25 * (i + 1))+ continue+ try:+ out = json.loads(raw)+ except ValueError:+ out = {"error": str(e)}+ out["http_status"] = e.code+ return out+ except urllib.error.URLError as e:+ if isinstance(e.reason, (BrokenPipeError, ConnectionResetError, ConnectionRefusedError)) and \+ i + 1 < tries:+ time.sleep(0.25 * (i + 1))+ continue+ raise+ raise RuntimeError("the match service kept refusing")+++def wait_for(base: str, seat: str, deadline_s: float = 300) -> dict:+ t = time.time()+ while time.time() - t < deadline_s:+ try:+ out = Seat(base, seat, 10).call("spec")+ if "error" not in out:+ return out+ except OSError:+ pass+ time.sleep(1)+ raise RuntimeError("the match service did not answer")+++def review_of(player, reply) -> tuple[str, str]:+ f = getattr(player, "review", None)+ return f(reply) if f else ("played as planned", "go on with the same plan")+++REPLY_IMAGES = [0] # acts whose reply carried images of their result (core 0.2.8)+++def play_turn(c: Seat, player) -> dict:+ c.call("start", {})+ while True:+ st = c.call("wait", {"timeout_s": 60}).get("state") or {}+ if st.get("done"):+ return st+ if not st.get("your_turn"):+ continue+ if st.get("awaiting_review"):+ why, plan = review_of(player, st)+ c.call("ready", {"why": why, "plan": plan})+ continue+ view = c.call("observe", {})+ body = player.act({"state": view.get("state") or {}, "observation": view.get("observation") or {}})+ reply = c.call("act", body)+ REPLY_IMAGES[0] += bool((reply.get("observation") or {}).get("image_png_b64"))+ if (reply.get("state") or {}).get("done"):+ return reply["state"]+ if reply.get("http_status"):+ print("refused:", json.dumps(reply)[:300], file=sys.stderr)+ continue+ why, plan = review_of(player, reply)+ c.call("ready", {"why": why, "plan": plan})+++def play_realtime(c: Seat, player, every_s: float = 0.05) -> dict:+ c.call("start", {})+ while True:+ view = c.call("observe", {})+ now = view.get("now") or {}+ if now.get("done"):+ return now+ if now.get("world") == "frozen" and now.get("phase") == "review" and not now.get("ready", {}).get(c.seat):+ why, plan = review_of(player, now)+ c.call("ready", {"why": why, "plan": plan})+ continue+ if now.get("world") == "running":+ v = {"state": now, "observation": view.get("observation") or {}}+ body = player.act(v)+ if body is not None:+ c.call("act", body)+ say = getattr(player, "message", None)+ text = say(v) if say is not None else None+ if text:+ c.call("say", {"text": text})+ c.call("wait", {"dt": every_s})+++def main(argv):+ mod, _, name = argv[0].partition(":")+ sys.path.insert(0, os.getcwd())+ factory = getattr(importlib.import_module(mod), name or "Reference")+ base, seat = os.environ.get("SIM_URL", "http://sim:8000"), os.environ.get("SEAT", "A")+ spec = wait_for(base, seat)+ player = factory(spec, seat, int(os.environ.get("RO_PLAYER_SEED", "0")))+ c = Seat(base, seat)+ proto = spec.get("protocol", "")+ end = play_turn(c, player) if proto.startswith("eai-standard-turn") else play_realtime(c, player)+ print(json.dumps({"final_state": {k: end.get(k) for k in ("reason", "won", "winner", "scores") if k in end},+ "replies_with_images": REPLY_IMAGES[0]}))+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/tasks/roboolympics-fencing-bout-i02-standard/solution/solve.sh b/tasks/roboolympics-fencing-bout-i02-standard/solution/solve.shnew file mode 100755index 0000000000..91b1b08047--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/solution/solve.sh@@ -0,0 +1,6 @@+#!/bin/bash+# Oracle on any seat: the sport's reference player.+set -e+mkdir -p /app/output+python3 -c "import numpy, PIL" 2>/dev/null || pip install -q --no-cache-dir -r /opt/client-requirements.txt+cd /solution && python3 oracle_play.pydiff --git a/tasks/roboolympics-fencing-bout-i02-standard/task.toml b/tasks/roboolympics-fencing-bout-i02-standard/task.tomlnew file mode 100644index 0000000000..715902a57b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/task.toml@@ -0,0 +1,122 @@+# Exported by RoboOlympics tools/export_fexam.py from fencing-bout-wallclock-program-standard (sports/fencing/sport.toml): do not edit.+schema_version = "1.3"+artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },+ "/app/output/",+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/replay_check.json", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/video.json", service = "sim" },+ { source = "/data/broadcast.jsonl", service = "sim" },+]++[task]+name = "robot-coding-bench/roboolympics-fencing-bout-i02-standard"+description = "STANDARD (RoboOlympics / Embodied Agent Olympics, our own service): robot epee fencing, one bout against the scripted opponent at level 2, program play (eai-standard-turn/1.0: the world waits for the player whose turn it is; the player's chess clock of 60 minutes of real time runs on its own turns, reviews included, and a player whose clock runs out loses). Camera images and the player's own state only. Frozen development instance (seed and level fixed, not an official seed). two Unitree G1 humanoids (the robot library's, NVIDIA's SONIC whole-body policy on the legs, waist and free arm, the point skill on the sword arm) holding real epees fence one FIE direct-elimination bout (15 touches or 9 minutes of fencing time, no draws; unwillingness to fight, FIE t.124) phrase by phrase: every phrase starts on guard 1.95 m apart, both fencers choose one of nine tactical intentions (lunge, low lunge, point in line, reactive line, stop-hit, counter-attack, delayed lunge, retreat, draw), each starts after a random 0-50 ms, and the phrase is played out as it was measured in MuJoCo (2916 phrases: every pair of intentions and delays); format bout: you against a scripted fencer that reads your choices (levels 1-2, `game spec` opponent), format duel: two players choosing at the same time. Exported from RoboOlympics task fencing-bout-wallclock-program-standard by tools/export_fexam.py."+authors = [{ name = "RoboOlympics (CHIGUI0)" }]+keywords = ["robotics", "roboolympics", "sports", "fencing", "mujoco", "standard-mode", "vision", "turn-based"]++[metadata]+author_name = "RoboOlympics"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-g1"+family = "fencing_bout"+mode = "standard"+dynamics = "dynamic" # scene dynamics (docs/PROTOCOL.md §2.14): scripts/task_dynamics.toml+protocol = "eai-standard-turn/1.0"+instance_seed = 35+opponent_level = 2+chess_clock_s = 3600+revision = "fencing-7+core-0.2"+play = "program"+action_level = "low"+source_task = "roboolympics/fencing-bout-wallclock-program-standard"+source_commits = ["a6712a675343"]+exporter = "roboolympics tools/export_fexam.py"+player_mode = "unmetered"+official = false+expert_time_estimate_hours = 0.5+oracle = "full"+oracle_evidence = "in process (fencing-7): the oracle beats level 2 on this seed 15:13; over 40 player seeds the reference wins this instance 42.5 %, the equilibrium mix 50 % (fresh-seed means 48.0 %, 53.9 %); none of the nine constant intentions nor a random player wins it; live on vanilla Harbor 0.23.0 (2026-10-15, the exported task) the oracle won 15:13 in 32 phrases, replay identical (the world is deterministic)"++[metadata.resources]+# minimum compute to run this task (docs/PROTOCOL.md §2.9)+min_cpus = 3.0+min_memory_gb = 5.0+min_gpu_memory_gb = 0.0+gpu_required = false+gpu_class = "none"+verifier_min_cpus = 2.0+verifier_min_memory_gb = 3.0+verifier_min_gpu_memory_gb = 0.0+measured = "vanilla Harbor 0.23.0 on ws-3 (32 cores), 2026-10-15, oracle and nop of both tasks, docker stats every 5 s: the sim peaks at 4.0 CPUs (its cap) and 0.71 GiB (the replay in a fresh process and the video after the bout; a bout is about 20 s of service time), the oracle's container under 0.1 GiB (a model's harness needs more: RoboOlympics' agent default); turn-based, so fewer CPUs only slow it down; CPU only"++[metadata.resources.limits]+# agent-phase limits in GiB (docs/PROTOCOL.md §2.10); scope: trial = every container, agent = the agent's container;+# enforced from protocol v1.2 when RCB_LIMITS_ENFORCE=1 (a violation fails the trial), otherwise recorded only+scope = "agent"+max_gpu_memory_gb = 0.0+max_memory_gb = 4.0+max_processes = 512+max_disk_gb = 20.0+disk_paths = ["/app", "/tmp", "/root"]+disk_exclude = []+sustain_sec = 60.0+window_sec = 120.0+trial_max_gpu_memory_gb = 0.0+trial_max_memory_gb = 12.0+measured = "design defaults of RoboOlympics' exported matches (the agent 4 GiB under its 6 GiB cap; whole trial: + the sim's 8 GiB cap); measured peaks 2026-10-15: sim 0.71 GiB, oracle container under 0.1 GiB"++[metadata.resources.caps]+# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)+main = { cpus = 2.0, memory_gb = 6.0, pids = 8192 }+sim = { cpus = 4.0, memory_gb = 8.0, pids = 256 }++[metadata.seeds]+# the instances this task may run from (docs/PROTOCOL.md §2.13): the default, the ones a runner may draw+# from (a list, { from = A, to = B } or "any"), and the ones the reference solution under solution/ is for+default = 35+allowed = [35]+oracle = [35]++[verifier]+timeout_sec = 2040.0+environment_mode = "separate"+network_mode = "no-network"++# Resource limits (docs/PROTOCOL.md §2.10): seal the monitor's record first, before any other sidecar ends the episode.+[[verifier.collect]]+service = "rcb_monitor"+command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90"+timeout_sec = 120++# The agent's time is up: stop whatever it left running (a program would keep playing; the match is graded as it stands).+[[verifier.collect]]+service = "main"+command = "kill -9 -1 2>/dev/null; exit 0"+timeout_sec = 30++# Then SIGUSR1 ends the match: the service replays it in a fresh process, checks the replay and writes the verdict+# ("graded_ready"), then the spectator video.+[[verifier.collect]]+service = "sim"+command = "for i in $(seq 1 90); do [ -f /data/server.pid ] && break; sleep 2; done; kill -USR1 $(cat /data/server.pid); for i in $(seq 1 600); do grep -q '\"graded_ready\": true' /data/final.json 2>/dev/null && break; sleep 1; done; [ x$RCB_RENDER_VIDEO = x1 ] && for i in $(seq 1 960); do [ -f /data/video.json ] && break; sleep 1; done; cat /data/final.json | head -c 2000"+timeout_sec = 1860++[agent]+timeout_sec = 7200+# The agent reaches the model APIs, the package registries and the sim (localhost:8000, Harbor's egress control).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com", "pypi.org", "files.pythonhosted.org", "deb.debian.org", "security.debian.org", "archive.ubuntu.com", "security.ubuntu.com", "snapshot.ubuntu.com"]++[environment]+build_timeout_sec = 1200.0+cpus = 2+memory_mb = 6144++[verifier.environment]+build_timeout_sec = 600.0++[verifier.env]+RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/Dockerfile b/tasks/roboolympics-fencing-bout-i02-standard/tests/Dockerfilenew file mode 100644index 0000000000..cba0eb5085--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/Dockerfile@@ -0,0 +1,12 @@+# Separate verifier sandbox: grades the sim service's artifacts; needs nothing but Python.+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+COPY sport_grade.py /tests/sport_grade.py+COPY contract.json /tests/contract.json+COPY nocode_audit.py /tests/nocode_audit.py+COPY seeds.py /tests/seeds.py+COPY fexam_reward.py /tests/fexam_reward.py+RUN chmod +x /tests/test.sh+# resource limits: the verifier step and its copy of the limits (docs/PROTOCOL.md §2.10) # rcb-monitor+COPY rcb_limits.py rcb_limits.json /tests/diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/contract.json b/tasks/roboolympics-fencing-bout-i02-standard/tests/contract.jsonnew file mode 100644index 0000000000..bbf32b910c--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/contract.json@@ -0,0 +1,58 @@+{+ "format": "bout",+ "formats": {+ "bout": {+ "levels": [+ 1,+ 2+ ],+ "opponent": true,+ "preview": true,+ "seats": [+ "A"+ ]+ },+ "duel": {+ "first": [+ "A",+ "B"+ ],+ "preview": true,+ "seats": [+ "A",+ "B"+ ]+ }+ },+ "official": {+ "first_any": true,+ "levels": [+ 1,+ 2+ ],+ "seeds": [+ 1,+ 2,+ 3,+ 101,+ 111,+ 121,+ 202,+ 212,+ 222+ ]+ },+ "protocol": "turn",+ "score": {+ "forfeit": 0.0,+ "from": "share",+ "name": "touch_share",+ "range": [+ 0,+ 1+ ],+ "text": "touches scored / touches scored by both fencers (a double counts for both; 0.5 if neither scored)"+ },+ "sport": "fencing",+ "task": "fencing-bout-wallclock-program-standard"+}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/fexam_reward.py b/tasks/roboolympics-fencing-bout-i02-standard/tests/fexam_reward.pynew file mode 100644index 0000000000..527e256880--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/fexam_reward.py@@ -0,0 +1,19 @@+#!/usr/bin/env python3+"""The hub's reward fields on top of our grader's reward.json (tools/export_fexam.py): infra_error = the trial is not+a valid result (our technical_failure); realtime, slowdown, opponent_level from the sim's final.json. Numbers only."""+import json+from pathlib import Path++LOG, DATA = Path("/logs/verifier"), Path("/data")+r = json.loads((LOG / "reward.json").read_text()) if (LOG / "reward.json").exists() else {"success": 0, "grader_error": 1}+try:+ f = json.loads((DATA / "final.json").read_text())+except (OSError, ValueError):+ f = {}+r["infra_error"] = int(bool(r.get("technical_failure", 1)) or bool(r.get("grader_error")))+r["realtime"] = int(bool(f.get("slowdown"))) # a turn-based match has no slowdown+r["slowdown"] = float(f.get("slowdown") or 0)+r["opponent_level"] = int((f.get("cfg") or {}).get("level") or 0)+r["steps"] = int(f.get("steps") or 0)+(LOG / "reward.json").write_text(json.dumps({k: v for k, v in r.items() if isinstance(v, (int, float))}))+(LOG / "reward.txt").write_text(str(int(r.get("success", 0))) + "\n")diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/grade.py b/tasks/roboolympics-fencing-bout-i02-standard/tests/grade.pynew file mode 100644index 0000000000..f63442d2ca--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/grade.py@@ -0,0 +1,198 @@+"""The verifier (separate sandbox, no network, no simulator): reads what the sim wrote (/data/final.json,+/data/replay_check.json), checks the fresh-process replay agrees with the live match, applies the one validity rule+(technical failures void the trial; a player's own problems are a valid loss, among them a side that never started+in its start window or before the player sessions ended: reason no_show, no_show = 1, <seat>_no_show = 1, core 0.2.7;+and a single side whose session ended after the start and before the end of the match: reason abandoned, abandoned =+1; core 0.2.6) and the no-code audit of+direct play,+and writes reward.json = common fields + the sport's own fields (tests/sport_grade.py: evaluate(final) -> numbers).+The task's formats and official configurations come from tests/contract.json (generated from sport.toml).++Hidden official seeds (core 0.2.14, core/seeds.py): once the sport registers a hidden seed set (contract official+hidden_seeds: sha256, counts and commitments per cell = format x level), official_config needs the match seed to be+one of its cell: the commitment the sim recorded (final.json seed_proof; the replay must give the same one) must be in+the registered cell (hidden_seed = 1, hidden_seed_index = its position; else 0 and -1). A hidden seed is never written:+seed = -1 here and in every record. The public [official] seeds then no longer count as official.+Core 0.2.19: this holds over the sport's own official_config too (tests/sport_grade.py may replace the core's value+with a legacy per-format rule): with a registered set, official_config = 1 needs hidden_seed = 1 and the sport's+value 1, so the sport's rule can only lower it and a public-seed match is never official.+Continuous score (core 0.2.14, core/score.py): final.json continuous.by_side (the replay must agree) becomes+<seat>_continuous_score per seat and, for a single-side format, continuous_score; larger is better.++success: duel / team / multi -> the trial is valid (who won is in <seat>_won / <seat>_place);+ single against a scripted opponent -> valid and the seat's side won;+ single without an opponent (solo) -> valid, complete and the score reaches the success line."""+from __future__ import annotations++import importlib.util+import json+import os+import shutil+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+DATA = Path(os.environ.get("RCB_DATA", "/data"))+LOG = Path(os.environ.get("RCB_LOG", "/logs/verifier"))+COMPLETE = ("match_over", "ready_timeout", "clock", "abandoned", "no_show")+++def _load(name):+ p = HERE / f"{name}.py"+ if not p.exists():+ return None+ spec = importlib.util.spec_from_file_location(name, p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++try: # core/seeds.py; in a task, its copy next to this file (tests/seeds.py)+ from . import seeds as seedset+except ImportError:+ seedset = _load("seeds")+++def hidden_index(d, contract) -> int | None:+ """The match seed's position in its cell (format x level) of the sport's registered hidden official seed set+ (core 0.2.14, core/seeds.py): the commitment the sim recorded (final.json seed_proof; the seed and its salt are+ never written) must be in that cell's registered commitments. None if it is not one."""+ reg = (contract.get("official") or {}).get("hidden_seeds")+ proof = d.get("seed_proof") or {}+ if not reg or seedset is None:+ return None+ return seedset.index(contract.get("sport", ""), d.get("format") or "", (d.get("cfg") or {}).get("level"),+ proof.get("commitment"), reg)+++def official(d, contract) -> bool:+ """An official configuration: the seed (a registered hidden seed once the sport has a hidden set, else one of the+ public [official] seeds), the slowdown, the first player and the level."""+ off = contract.get("official", {})+ if ((contract.get("formats") or {}).get(d.get("format") or "") or {}).get("preview"):+ return False # a preview format ([formats.<f>] preview = true; core 0.2.21) is never official+ ok = True+ if off.get("hidden_seeds"):+ ok &= hidden_index(d, contract) is not None+ elif "seeds" in off:+ ok &= int(d.get("seed") or 0) in off["seeds"]+ if "slowdowns" in off:+ ok &= float(d.get("slowdown") or 0) in off["slowdowns"].get(d.get("play", "program"), [])+ if off.get("first_any"):+ ok &= d.get("first") in d["cfg"]["seats"] or d.get("first") in (d.get("sides") or {}).values()+ if "levels" in off and d["cfg"].get("level") is not None:+ ok &= int(d["cfg"]["level"]) in off["levels"]+ return bool(ok)+++def line_ok(score, line: dict) -> bool:+ if "score_at_least" in line:+ return score >= line["score_at_least"]+ if "score_at_most" in line:+ return score <= line["score_at_most"]+ return False+++def grade(d, r, contract, evaluate, audits=None):+ seats = d["cfg"]["seats"]+ side = d.get("sides") or {s: s for s in seats}+ cont = (d.get("continuous") or {}).get("by_side")+ replay = bool(d.get("deterministic") and r.get("state_sha") == d["state_sha"] and r.get("scores") == d["scores"]+ and r.get("winner") == d["match_winner"] and r.get("commands_sha") == d["commands_sha"]+ and r.get("source_sha") == d["source_sha"] and r.get("k") == d["steps"]+ and (cont is None or r.get("continuous") == cont)+ and (not d.get("seed_proof") or r.get("seed_commitment") == d["seed_proof"].get("commitment")))+ solo = bool(d.get("solo"))+ single = len(set(side.values())) == 1+ complete = d.get("reason") in COMPLETE and (single or d.get("match_winner") in side.values())+ errors = bool(d.get("errors") or any(d["meter_error"].values()) or any(d["proxy_error"].values()))+ valid = bool(d.get("valid_trial") and d.get("finalized") and replay and complete and not errors)+ direct = d.get("play") == "direct"+ audits = audits or {}+ bad = {s: bool(direct and d["player_modes"].get(s) == "model" and audits.get(s, (0, []))[1]) for s in seats}+ winner = d["match_winner"]+ if any(bad.values()): # a no-code violation loses the match (all of them: nobody wins)+ rest = sorted({side[s] for s in seats if not bad[s]})+ winner = rest[0] if len(rest) == 1 and not single else None+ fmt = (contract.get("formats") or {}).get(d.get("format") or "", {})+ if solo:+ score = d["scores"].get(side[seats[0]], 0)+ success = valid and d.get("reason") == "match_over" and not any(bad.values()) and \+ line_ok(score, fmt.get("success", {}))+ elif single:+ success = valid and winner == side[seats[0]]+ else:+ success = valid+ out = dict(success=int(success), valid_trial=int(valid), technical_failure=int(not valid), grader_error=0,+ missing_log=0, deterministic=int(replay), match_over=int(d.get("reason") == "match_over"),+ seed=int(d.get("seed") or 0), official_config=int(official(d, contract)),+ video_rendered=int(bool(d.get("video")) or (DATA / "replay.mp4").exists()), direct_play=int(direct),+ lowlevel_actions=int(d.get("action_level") == "low"), solo=int(solo),+ no_show=int(d.get("reason") == "no_show"), abandoned=int(d.get("reason") == "abandoned"))+ hidx = hidden_index(d, contract)+ out.update(hidden_seed=int(hidx is not None), hidden_seed_index=hidx if hidx is not None else -1)+ if cont is not None: # the continuous score (core 0.2.14): larger is better+ worst = float((contract.get("score") or {}).get("forfeit", 0.0))+ for s in seats:+ out[s + "_continuous_score"] = worst if bad[s] else float(cont.get(side[s], worst))+ if single:+ out["continuous_score"] = out[seats[0] + "_continuous_score"]+ ranking = d.get("ranking") or []+ for s in seats:+ out[s + "_won"] = int(valid and winner == side[s] and not bad[s])+ out[s + "_no_show"] = int(d.get("reason") == "no_show" and not (d.get("joined") or {}).get(s, True))+ if len(set(side.values())) > 2:+ out[s + "_place"] = ranking.index(side[s]) + 1 if valid and side[s] in ranking else 0+ out[s + "_transient_api_errors"] = int(d["transient_api_errors"].get(s, 0))+ out[s + "_unrecovered_api_errors"] = int(d["unrecovered_api_errors"].get(s, 0))+ if direct:+ out[s + "_nocode_tool_calls"] = int(audits.get(s, (0, []))[0])+ out[s + "_nocode_violations"] = len(audits.get(s, (0, []))[1])+ out[s + "_nocode_forfeit"] = int(bad[s])+ out.update(evaluate(d))+ if (contract.get("official") or {}).get("hidden_seeds"):+ # core 0.2.19: once the sport registered a hidden seed set (frozen), only a match on a registered hidden seed of+ # its cell is official, whatever the sport's own official_config says (its legacy public-seed rule); the+ # sport's rule (e.g. its slowdowns) can only lower the value+ out["official_config"] = int(out.get("official_config") == 1 and hidx is not None)+ return out+++def main():+ LOG.mkdir(parents=True, exist_ok=True)+ try:+ contract = json.loads((HERE / "contract.json").read_text())+ evaluate = _load("sport_grade").evaluate+ d, r = (json.loads((DATA / f).read_text()) for f in ("final.json", "replay_check.json"))+ audits = None+ if d.get("play") == "direct":+ nmod = _load("nocode_audit") # the players' no-code audit (players/nocode/)+ # calls the gateway blocked never reached the agent, so they are not judged (direct-native/1.1 rule)+ audits = {s: nmod.nocode_audit(DATA / f"think_calls_{s}.jsonl",+ skip_ids=nmod.gate_blocked_ids(DATA / f"direct_gate_{s}.jsonl"))+ for s in d["cfg"]["seats"]}+ (LOG / "nocode_audit.json").write_text(json.dumps({s: dict(tool_calls=a[0], violations=a[1][:50])+ for s, a in audits.items()}, indent=1))+ out = grade(d, r, contract, evaluate, audits)+ hs = (contract.get("official") or {}).get("hidden_seeds") or {}+ (LOG / "versions.json").write_text(json.dumps({+ "versions": d.get("versions"), "renderer": d.get("renderer"),+ "seed_set": {"sha256": hs.get("sha256"), "counts": hs.get("counts"), "index": hidden_index(d, contract)}+ if hs else None,+ "continuous_score": {k: (d.get("continuous") or {}).get(k) for k in ("name", "from", "higher_is_better")}+ if d.get("continuous") else None}))+ for f in ("final.json", "replay_check.json", "episode.jsonl", "replay.mp4"):+ if (DATA / f).exists():+ shutil.copy(DATA / f, LOG / f)+ except Exception as e: # noqa: BLE001+ print(type(e).__name__, str(e))+ out = dict(success=0, valid_trial=0, technical_failure=1, grader_error=1,+ missing_log=int(not (DATA / "final.json").exists()))+ assert all(isinstance(v, (int, float)) for v in out.values())+ (LOG / "reward.json").write_text(json.dumps(out))+ (LOG / "reward.txt").write_text(str(out["success"]) + "\n")+ print(out)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/nocode_audit.py b/tasks/roboolympics-fencing-bout-i02-standard/tests/nocode_audit.pynew file mode 100644index 0000000000..213aa5d559--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/nocode_audit.py@@ -0,0 +1,321 @@+"""The no-code audit of direct play (docs/benchmarks/roboolympics-modes.md, play switch `direct`), shared by every+sport: the generator copies it into tests/ of every task with declared switches; a grader applies it when final.json+says `play` = "direct".++Every tool call of every model response of the session (think_calls.jsonl, recorded by the metering proxy) must be a+literal `game` command or the opening of a saved camera image (or a planning note); anything else - a program, a+script, another shell command, a pipe, a redirection, command substitution, a file edit - forfeits the contest: a+valid trial that is lost (decided 2026-10-06), reported as `nocode_violations` with the calls in nocode_audit.json.++The audit window starts at the player's first `game start` (decided 2026-10-06): before it, self-inspection is also+allowed - listing the harness's tools, reading the instruction, the spec or other files (read-only commands and file+viewers, a code cell that calls no tool). Starting a program, writing a file or any other side effect is a violation+before `game start` too (a program started then would run during play).+"""+import json+import re+from pathlib import Path++VIEWS = re.compile(r"^/app/output/views/[A-Za-z0-9_.-]+\.png$")+WORD = re.compile(r"^[A-Za-z0-9_.+\-:/=,%]+$")+PLAN_TOOLS = {"TodoWrite", "update_plan"}+++READONLY = {"cat", "ls", "head", "tail", "wc", "pwd", "which", "file", "stat", "echo", "less", "more", "tree"}+INSPECT_TOOLS = {"Read", "Glob", "Grep", "LS", "TodoWrite", "update_plan", "view_image"}+++def literal_words(cmd: str):+ """The words of a command with literal arguments only, or None (see literal_game)."""+ return _words(cmd)+++def literal_game(cmd: str) -> bool:+ """`game WORD ...` with literal arguments only: quoted texts may hold anything but an unescaped $ or ` inside double+ quotes (a backslash there only makes the next character literal); outside quotes only plain words (no ; | & < > $+ ` ( ) { } newline ...)."""+ return _game_ok(_words(cmd))+++def _words(cmd: str):+ words, cur, quote, quoted, esc = [], "", None, False, False+ for ch in cmd.strip():+ if quote:+ if esc:+ cur += ch; esc = False+ elif quote == '"' and ch == "\\":+ esc = True+ elif ch == quote:+ quote = None+ elif quote == '"' and ch in '$`':+ return None+ else:+ cur += ch+ continue+ if ch in "\"'":+ quote, quoted = ch, True+ elif ch in " \t":+ if cur or quoted:+ words.append(cur)+ cur, quoted = "", False+ elif WORD.match(ch):+ cur += ch+ else:+ return None+ if quote:+ return None+ if cur or quoted:+ words.append(cur)+ return words+++def _game_ok(words) -> bool:+ return bool(words) and len(words) >= 2 and words[0] == "game"+++def _args(tool):+ a = tool.get("input") or tool.get("arguments") or tool.get("action") or (tool.get("function") or {}).get("arguments")+ if isinstance(a, str):+ try:+ a = json.loads(a)+ except ValueError:+ return {"_raw": a}+ return a if isinstance(a, dict) else {"_raw": a}+++def _shell(cmd):+ """The command a shell tool runs: codex wraps it as [bash, -lc, CMD]."""+ if isinstance(cmd, list):+ if len(cmd) == 3 and cmd[0] in ("bash", "sh", "/bin/bash", "/bin/sh") and cmd[1] in ("-lc", "-c"):+ return cmd[2]+ return None+ return cmd if isinstance(cmd, str) else None+++# Codex 0.158 with GPT-6 has no direct shell tool: every tool use is an `exec` cell of JavaScript that calls tools+# (tools.exec_command, tools.view_image). JavaScript is code, so only the two one-call cells below are allowed (a+# literal `game` command, or opening a saved camera image, and printing its result); anything else in a cell (loops,+# several calls, computation, other tools) is a violation.+_JS_LIT = r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|-?\d+(?:\.\d+)?'+_JS_CALL = re.compile(r'^\s*const\s+(\w+)\s*=\s*await\s+tools\.(\w+)\(\{(.*)\}\)\s*;?\s*$', re.S)+_JS_PAIR = re.compile(r'\s*(\w+)\s*:\s*(' + _JS_LIT + r')\s*(?:,|$)', re.S)+# the parameters each allowed tool may take (all literal), and what it must be called with+_JS_TOOLS = {"mcp__game__game": {"command"}, # direct-native: the `game` MCP tool (game_mcp.py)+ "exec_command": {"cmd", "workdir", "max_output_tokens", "yield_time_ms"},+ "view_image": {"path", "detail"},+ "write_stdin": {"session_id", "chars", "yield_time_ms", "max_output_tokens"}}+++def _js_value(lit):+ if lit[0] in "\"'":+ body = lit[1:-1]+ if lit[0] == "'":+ body = body.replace("\\'", "'").replace('"', '\\"')+ try:+ return json.loads('"' + body + '"')+ except ValueError:+ return None+ return float(lit)+++def _js_print_ok(stmt, var):+ """Printing the call's result, nothing else: text(r.output), text(JSON.stringify(r)), text("..." + JSON.stringify(r)),+ image(r.image_url[, "detail"])."""+ v = re.escape(var)+ lit = r'(?:"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')'+ pats = (rf'text\(\s*{v}\.output\s*\)', rf'text\(\s*JSON\.stringify\(\s*{v}\s*\)\s*\)',+ rf'text\(\s*{lit}\s*\+\s*JSON\.stringify\(\s*{v}\s*\)\s*\)', rf'image\(\s*{v}\.image_url\s*(?:,\s*{lit}\s*)?\)')+ return any(re.fullmatch(p + r'\s*;?\s*', stmt) for p in pats)+++_JS_FORBIDDEN = re.compile(r"tools\.|ALL_TOOLS|\bawait\b|\bwhile\b|\bdo\b|\bfunction\b|\beval\b|Function\(|\bimport\b|"+ r"\brequire\b|\batob\b|\bbtoa\b|Buffer|Uint8Array|ArrayBuffer|DataView|charCodeAt|"+ r"fromCharCode|codePointAt|setTimeout|setInterval|\bMath\.|\bnew\b|\bclass\b|\byield\b")+++def _js_light_display_ok(rest, var) -> bool:+ """Formatting the result for display without computing on it (direct-native, Codex): no further tool call, no loop+ other than over the result's content items, no arithmetic library, no access to the image bytes except passing+ them to image(); at most 800 characters."""+ body = re.sub(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|`(?:[^`\\]|\\.)*`', '""', rest)+ if len(rest) > 800 or _JS_FORBIDDEN.search(body):+ return False+ for m in re.finditer(r"\bfor\s*\(", body):+ if not re.match(rf"for\s*\(\s*(?:const|let|var)\s+\w+\s+of\s+\(?\s*{re.escape(var)}\s*\??\.\s*content", body[m.start():]):+ return False+ for m in re.finditer(r"\.data\b", body):+ if not re.search(r"image\(\s*[\w.]*$", body[:m.start()]):+ return False+ return True+++def _js_display_ok(rest, var) -> bool:+ """The statements after the call only display its result: text(r), text(r.output), text(JSON.stringify(r)),+ text("..." + JSON.stringify(r)), image(r.image_url[, "..."]), or the loop that shows an MCP result's content+ (`for (const c of (r.content || [])) { if (c.type === "image") image(c); else if (c.type === "text") text(c.text); }`)."""+ compact = re.sub(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'', "L", rest)+ compact = re.sub(r"\s+", "", compact)+ v = re.escape(var)+ c = r"(?P<c>\w+)"+ simple = (rf"text\({v}\);?", rf"text\({v}\.output\);?", rf"text\(JSON\.stringify\({v}\)\);?",+ rf"text\(L\+JSON\.stringify\({v}\)\);?", rf"image\({v}\.image_url(,L)?\);?")+ show = r"(?:image\((?P=c)(?:\.data)?\)|text\((?P=c)(?:\.text)?\))"+ loop = (rf"for\((?:const|let|var){c}of\(?{v}\.content(?:\|\|\[\])?\)?\)\{{"+ rf"(?:(?:else)?if\((?P=c)\.type===?L\){show};?)+(?:else{show};?)?\}};?")+ while compact:+ for pat in simple + (loop,):+ m = re.match(pat, compact)+ if m:+ compact = compact[m.end():]+ break+ else:+ return False+ return True+++def codex_exec_ok(src, cmd_ok=literal_game) -> bool:+ """One literal tool call (a `game` command, opening a camera image, or polling that command's output) and printing+ its result; no other code."""+ if not isinstance(src, str):+ return False+ lines = [x for x in src.strip().split("\n") if x.strip()]+ if not lines:+ return False+ m = _JS_CALL.match(lines[0])+ if not m or m.group(2) not in _JS_TOOLS:+ return False+ var, tool, body = m.group(1), m.group(2), m.group(3)+ args, pos = {}, 0+ while pos < len(body.strip()):+ pm = _JS_PAIR.match(body, pos)+ if not pm:+ return False+ args[pm.group(1)] = _js_value(pm.group(2)); pos = pm.end()+ if not set(args) <= _JS_TOOLS[tool] or any(v is None for v in args.values()):+ return False+ rest = "\n".join(lines[1:])+ if tool == "mcp__game__game": # direct-native: canonical display or light formatting of the result+ return (_js_display_ok(rest, var) or _js_light_display_ok(rest, var)) and _player_command(args.get("command"))+ if not _js_display_ok(rest, var):+ return False+ if tool == "exec_command":+ return isinstance(args.get("cmd"), str) and cmd_ok(args["cmd"])+ if tool == "view_image":+ return isinstance(args.get("path"), str) and bool(VIEWS.match(args["path"]))+ return args.get("chars", "") == "" # write_stdin: only polling a running command, never input+++def _player_command(cmd) -> bool:+ import shlex+ if not isinstance(cmd, str) or "\n" in cmd.strip():+ return False+ try:+ w = shlex.split(cmd)+ except ValueError:+ return False+ return len(w) >= 2 and w[0] == "game"+++def _readonly(cmd) -> bool:+ w = _words(cmd)+ return bool(w) and (w[0] in READONLY or _game_ok(w))+++def tool_name(tool):+ return tool.get("name") or (tool.get("function") or {}).get("name") or tool.get("type")+++def is_game_start(tool) -> bool:+ """A literal `game start` (shell call or Codex cell)."""+ name, a = tool_name(tool), _args(tool)+ cmd = None+ if name == "exec" and tool.get("type") == "custom_tool_call":+ m = _JS_CALL.match((tool.get("input") or "").strip().split("\n")[0]) if isinstance(tool.get("input"), str) else None+ if m and m.group(2) == "exec_command":+ pm = re.search(r'cmd\s*:\s*(' + _JS_LIT + ')', m.group(3))+ cmd = _js_value(pm.group(1)) if pm else None+ elif name in SHELL_TOOLS or name in ("game", "mcp__game__game", "game__game"):+ cmd = _shell(a.get("command", a.get("cmd")))+ w = _words(cmd) if isinstance(cmd, str) else None+ return bool(w) and w[:2] == ["game", "start"]+++def inspection_ok(tool) -> bool:+ """Before `game start`: read-only self-inspection (file viewers, read-only commands, a code cell calling no tool)."""+ if allowed(tool):+ return True+ name, a = tool_name(tool), _args(tool)+ if name in INSPECT_TOOLS:+ return True+ if name == "exec" and tool.get("type") == "custom_tool_call":+ src = tool.get("input")+ code = re.sub(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|`(?:[^`\\]|\\.)*`', '""', src) if isinstance(src, str) else ""+ if isinstance(src, str) and "tools." not in code and "await" not in code and "import" not in code:+ return True # pure JavaScript in the harness's sandbox: no tool, no side effect+ return codex_exec_ok(src, _readonly)+ if name in SHELL_TOOLS:+ cmd = _shell(a.get("command", a.get("cmd")))+ return isinstance(cmd, str) and _readonly(cmd)+ return False+++SHELL_TOOLS = ("Bash", "shell", "exec_command", "local_shell_call", "container.exec", "shell_command")+++def allowed(tool) -> bool:+ name = tool.get("name") or (tool.get("function") or {}).get("name") or tool.get("type")+ a = _args(tool)+ if name in PLAN_TOOLS:+ return True+ if name == "wait" and set(a) <= {"cell_id", "yield_time_ms", "max_tokens"}: # Codex: wait for a running cell+ return True+ if name in ("game", "mcp__game__game", "game__game"): # direct-player (harbor_agents/direct_loop.py): its only tool; no shell+ return _player_command(a.get("command")) # runs it, the line is data for the harness's parser+ if name == "exec" and tool.get("type") == "custom_tool_call": # Codex code mode (see above)+ return codex_exec_ok(tool.get("input"))+ if name in ("Read", "view_image"):+ return isinstance(a.get("file_path", a.get("path")), str) and bool(VIEWS.match(a.get("file_path", a.get("path"))))+ if name in ("Bash", "shell", "exec_command", "local_shell_call", "container.exec", "shell_command"):+ cmd = _shell(a.get("command", a.get("cmd")))+ return isinstance(cmd, str) and literal_game(cmd)+ return False+++def gate_blocked_ids(path):+ """Item ids the gateway (direct_gate.py) blocked, from its log; empty if there is none."""+ ids = set()+ try:+ for line in Path(path).read_text().splitlines():+ e = json.loads(line)+ if e.get("ev") == "blocked" and e.get("item_id"):+ ids.add(e["item_id"])+ except (OSError, ValueError):+ pass+ return ids+++def nocode_audit(path, skip_ids=()):+ """(tool calls, violations [(seq, tool name, arguments excerpt)]) of the session's model responses. skip_ids: the+ item ids the gateway blocked (they never reached the agent, so they are not judged)."""++ n, bad = 0, []+ try:+ lines = Path(path).read_text().splitlines()+ except OSError:+ return 0, []+ started = False # the window opens at the first `game start`+ for line in lines:+ try:+ rec = json.loads(line)+ except ValueError:+ continue+ for tool in rec.get("tool_calls") or []:+ if tool.get("id") in skip_ids: # blocked by the gateway (direct-native/1.1): it never ran+ continue+ n += 1+ ok = allowed(tool) if started else inspection_ok(tool)+ started = started or is_game_start(tool)+ if not ok:+ bad.append({"seq": rec.get("seq"), "tool": tool.get("name") or (tool.get("function") or {}).get("name")+ or tool.get("type"), "args": json.dumps(_args(tool))[:300]})+ return n, baddiff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/rcb_limits.json b/tasks/roboolympics-fencing-bout-i02-standard/tests/rcb_limits.jsonnew file mode 100644index 0000000000..56290adc7b--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/rcb_limits.json@@ -0,0 +1,39 @@+{+ "agent_timeout_sec": 7200,+ "caps": {+ "main": {+ "cpus": 2.0,+ "memory_gb": 6.0,+ "pids": 8192+ },+ "sim": {+ "cpus": 4.0,+ "memory_gb": 8.0,+ "pids": 256+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": false,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 0.0,+ "max_memory_gb": 4.0,+ "max_processes": 512,+ "mode": "standard",+ "scope": "agent",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "roboolympics-fencing-bout-i02-standard",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 0.0,+ "trial_max_memory_gb": 12.0,+ "window_sec": 120.0+}diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/rcb_limits.py b/tasks/roboolympics-fencing-bout-i02-standard/tests/rcb_limits.pynew file mode 100644index 0000000000..3c996ca1f2--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/rcb_limits.py@@ -0,0 +1,536 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The session log (robot_coding_bench #233): sanitize() also compares the agent's /app/output/rcb_session_log.jsonl with+the monitor's append-only copy of it (session_log/ in the record) and, when the agent's file is missing or is not what+was written (removed, truncated, rewritten), gives the grader the copy instead (session_log_source()); verify() adds+session_log_tampered (0/1) and session_log_from_monitor (0/1) to reward.json. Only the graders' cost fields read the log.++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ sl = read_json(os.path.join(log, SESSION_LOG_STATUS)) # sanitize()'s session-log comparison (#233)+ if isinstance(sl, dict):+ add["session_log_tampered"] = int(bool(sl.get("tampered")))+ add["session_log_from_monitor"] = int(bool(sl.get("from_monitor")))+ detail["session_log"] = sl+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ try:+ msg = session_log_source(log, max_log)+ if msg:+ done.append(msg)+ except Exception as e: # never keep the grader from running+ done.append(f"session log: not compared with the monitor's copy ({type(e).__name__}: {e})")+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++SESSION_LOG_STATUS = "session_log.json" # in /logs/verifier: what session_log_source() did, read back by verify()+++def session_log_source(log, max_log=MAX_SESSION_LOG, record=None):+ """The session log the grader reads (#233). The monitor copies what the agent's tooling appends to it, append-only,+ into its record (session_log/<segment>.jsonl; a new segment each time the file was truncated, replaced or+ rewritten). The agent's file stays when it is the copy plus at most what was appended after the last tick; else+ (removed, truncated, rewritten, or the copy has segments) the grader gets the copy: the segments' lines in order,+ in a later segment a line an earlier one already gave left out (a rewrite copies the file again). No copy (no monitor on the runner, or no log+ written): nothing changes, nothing is written. Else writes /logs/verifier/session_log.json; returns a line for the+ log, or None."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ d = os.path.join(record, "session_log")+ segs = sorted((int(n.split(".")[0]) for n in (os.listdir(d) if os.path.isdir(d) else ())+ if n.endswith(".jsonl") and n.split(".")[0].isdigit()))+ events = [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)]+ tamper = [e for e in events if e.get("event") in ("session_log_rewritten", "session_log_removed")]+ status = {"from_monitor": 0, "tampered": int(bool(tamper)), "monitor_copy": bool(segs), "events": tamper[:20]}+ msg = None+ if segs:+ copies = []+ for n in segs:+ with open(os.path.join(d, "%d.jsonl" % n), "rb") as f:+ copies.append(f.read(max_log))+ agent = None+ if os.path.isfile(log) and not os.path.islink(log):+ with open(log, "rb") as f:+ agent = f.read(max_log)+ if len(segs) == 1 and not tamper and agent is not None and agent.startswith(copies[0]):+ pass # the agent's file is what was written (and maybe a last tick more)+ else:+ given, out = {}, [] # line -> most times one earlier segment had it+ for c in copies:+ again, lines, here = dict(given), c.splitlines(True), {}+ for line in lines:+ here[line] = here.get(line, 0) + 1+ if again.get(line):+ again[line] -= 1 # the rewrite's copy of a line given before+ continue+ out.append(line)+ for line, k in here.items():+ given[line] = max(given.get(line, 0), k)+ data = b"".join(out)[:max_log]+ if os.path.lexists(log):+ os.unlink(log)+ with open(log, "wb") as f:+ f.write(data)+ status.update(from_monitor=1, tampered=1, agent_bytes=None if agent is None else len(agent),+ copy_bytes=len(data))+ msg = (f"replaced {log} with the monitor's copy ({len(data)} bytes; the agent's file was "+ + ("missing" if agent is None else f"{len(agent)} bytes, not what was written") + ")")+ if not segs and not tamper:+ return None # no copy (no monitor, or no log written): nothing to say+ logs = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ try:+ os.makedirs(logs, exist_ok=True)+ with open(os.path.join(logs, SESSION_LOG_STATUS), "w") as f:+ json.dump(status, f, indent=1)+ except OSError:+ pass+ return msg+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/seeds.py b/tasks/roboolympics-fencing-bout-i02-standard/tests/seeds.pynew file mode 100644index 0000000000..c6a2ae4c83--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/seeds.py@@ -0,0 +1,178 @@+"""Hidden official seeds (core 0.2.14, docs/framework_zh.md §6.4): a sport frozen for a season plays its official+matches on a seed set that only the organisers hold. The repository has its commitments, never the seeds.++ cells the set is partitioned by format x level: one cell per format ("duel") or per format and level of a+ format with levels ("match/L1", "match/L2", ...; cell_of); every cell has its own seeds, none shared+ private set {"schema": PRIVATE, "sport", "created", "cells": {cell: [{"seed": int, "salt": 32 hex}, ...]}}: outside+ git, on the official run host only (tools/seeds.py: $RO_SEEDS_DIR/<sport>.hidden_seeds.json, 0600)+ commitments one per seed, in cell order: sha256("ro-hidden-seeds/1|<sport>|<seed>|<salt>"); the salt (128 random+ bits) makes a commitment say nothing about its seed+ registration set_sha256 (the sport and every cell's commitments) and the count per cell: sport.toml+ [official.hidden_seeds] sha256, counts; the commitments are public (sports/<sport>/seed_commitments.json)++At run time the runner hands one seed, its salt and its index to the sim service only (RO_SEED, RO_SEED_SALT,+RO_SEED_INDEX); the players' containers never see them. In such a match the core writes the seed nowhere: the+episode header, final.json, replay_check.json and the broadcast log carry seed -1 and the commitment only+(final.json seed_proof), the sport's own fields and the players' observations and /spec are scrubbed (scrub()), and+the fresh-process replay takes the seed from the same environment and checks it against the commitment. The salt is+never written either (with it, a six-digit seed would follow from its commitment by brute force). The verifier finds+the commitment in the cell of the match's format and level (index()): hidden_seed, hidden_seed_index. The private set+plus the index is the only record of the seed; after the season the set may be published and anyone can recompute+set_sha256 from it.++Standard library only: the generator copies this file next to the verifier (tests/seeds.py)."""+from __future__ import annotations++import hashlib+import re+import secrets++SCHEMA = "ro-hidden-seeds/1" # the commitment of one seed+SET_SCHEMA = "ro-hidden-seeds/2" # the registered digest of a partitioned set+PRIVATE = "ro-hidden-seeds-private/2"+PUBLIC = "ro-hidden-seeds-public/2"+SEED_RANGE = (100000, 999999) # six digits: an int32 for any simulator+HIDDEN = -1 # the seed as written in the records of a hidden-seed match+HEX = re.compile(r"^[0-9a-f]{64}$")+CELL = re.compile(r"^[a-z0-9][a-z0-9_-]*(/L\d+)?$") # a format name of sport.toml, "/L<level>"+KEEP = {"step", "k", "steps", "t_sim"}+COMMITMENTS = "seed_commitments.json" # sports/<sport>/<this>: the public part (public())+++def commitment(sport: str, seed: int, salt: str) -> str:+ return hashlib.sha256(f"{SCHEMA}|{sport}|{int(seed)}|{salt}".encode()).hexdigest()+++def set_sha256(sport: str, cells: dict) -> str:+ """The registered digest of a seed set: its sport and every cell's commitments, cells in sorted order."""+ text = SET_SCHEMA + "\n" + sport + "\n"+ for c in sorted(cells):+ text += f"[{c}]\n" + "".join(x + "\n" for x in cells[c])+ return hashlib.sha256(text.encode()).hexdigest()+++def cell_of(fmt: str, level, cells) -> str | None:+ """The cell of a match: "<format>/L<level>" when the set has it, else "<format>" when it has that, else None."""+ if level is not None and f"{fmt}/L{int(level)}" in cells:+ return f"{fmt}/L{int(level)}"+ return fmt if fmt in cells else None+++def new(sport: str, counts: dict, avoid=(), created: str = "") -> dict:+ """A fresh private set: counts = {cell: n}; every seed distinct across cells and none of `avoid`."""+ if not counts or any(int(n) < 1 or not CELL.match(c) for c, n in counts.items()):+ raise ValueError("cells: {\"<format>\" or \"<format>/L<level>\": count >= 1}")+ lo, hi = SEED_RANGE+ used, cells = {int(x) for x in avoid}, {}+ for c in sorted(counts):+ cells[c] = []+ while len(cells[c]) < int(counts[c]):+ s = lo + secrets.randbelow(hi - lo + 1)+ if s not in used:+ used.add(s)+ cells[c].append({"seed": s, "salt": secrets.token_hex(16)})+ return {"schema": PRIVATE, "sport": sport, "created": created, "cells": cells}+++def from_seeds(sport: str, cells: dict, created: str = "") -> dict:+ """A private set of given seeds ({cell: [int, ...]}) with fresh salts."""+ out = {c: [{"seed": int(s), "salt": secrets.token_hex(16)} for s in v] for c, v in cells.items()}+ p = {"schema": PRIVATE, "sport": sport, "created": created, "cells": out}+ check_private(p)+ return p+++def check_private(p: dict) -> None:+ if p.get("schema") != PRIVATE or not p.get("sport") or not p.get("cells"):+ raise ValueError(f"not a private seed set (schema {PRIVATE}, sport, cells)")+ seen = set()+ for c, entries in p["cells"].items():+ if not CELL.match(c) or not entries:+ raise ValueError(f"bad cell {c!r}")+ for e in entries:+ if not isinstance(e.get("seed"), int) or not re.fullmatch(r"[0-9a-f]{32}", str(e.get("salt", ""))):+ raise ValueError(f"bad entry in {c}: seed int, salt 32 hex")+ if e["seed"] in seen:+ raise ValueError(f"seed {e['seed']} twice (cells never share a seed)")+ seen.add(e["seed"])+++def public(p: dict) -> dict:+ """The public part of a private set: what goes into the repository."""+ check_private(p)+ cells = {c: [commitment(p["sport"], e["seed"], e["salt"]) for e in v] for c, v in sorted(p["cells"].items())}+ return {"schema": PUBLIC, "sport": p["sport"], "counts": {c: len(v) for c, v in cells.items()},+ "sha256": set_sha256(p["sport"], cells), "cells": cells}+++def registered(sport: str, reg: dict) -> dict:+ """The cells of a registration {sha256, counts, cells}, after checking that they are the registered ones (their+ digest and counts); ValueError otherwise."""+ cells = reg.get("cells") or {}+ counts = reg.get("counts") or {}+ if set(cells) != set(counts) or not cells:+ raise ValueError("hidden seeds: the cells of the commitments and of the counts differ")+ flat = [x for v in cells.values() for x in v]+ if not all(isinstance(x, str) and HEX.match(x) for x in flat) or len(set(flat)) != len(flat):+ raise ValueError("hidden seeds: commitments must be distinct sha256 hex digests")+ for c, v in cells.items():+ if len(v) != int(counts[c]):+ raise ValueError(f"hidden seeds: cell {c} has {len(v)} commitments, count {counts[c]}")+ if set_sha256(sport, cells) != reg.get("sha256"):+ raise ValueError("hidden seeds: the commitments do not hash to the registered sha256")+ return cells+++def index(sport: str, fmt: str, level, commit: str | None, reg: dict) -> int | None:+ """The position of a match's commitment in the cell of its format and level, None if it is not there (or the+ registration is inconsistent: then nothing is a member)."""+ if not commit:+ return None+ try:+ cells = registered(sport, reg)+ except (ValueError, TypeError):+ return None+ cell = cell_of(fmt, level, cells)+ if cell is None or commit not in cells[cell]:+ return None+ return cells[cell].index(commit)+++def resolve(p: dict, cell: str, i: int, reg: dict | None = None) -> tuple[int, str]:+ """(seed, salt) of entry i of a cell of a private set; with a registration, also checks that the set is the+ registered one."""+ check_private(p)+ if cell not in p["cells"]:+ raise KeyError(f"no cell {cell!r} (cells: {', '.join(sorted(p['cells']))})")+ if not 0 <= i < len(p["cells"][cell]):+ raise IndexError(f"cell {cell} has {len(p['cells'][cell])} seeds (0..{len(p['cells'][cell]) - 1}); asked {i}")+ if reg is not None and public(p)["sha256"] != reg.get("sha256"):+ raise ValueError("this private seed set is not the registered one (sha256 differs)")+ e = p["cells"][cell][i]+ return int(e["seed"]), str(e["salt"])+++def scrub(obj, seed: int, salt: str = ""):+ """A copy of obj (JSON-like) without the seed: values under a key named "seed" or "*_seed" become HIDDEN, and so+ does any integer equal to the seed or any string equal to it or to the salt. For a hidden-seed match."""+ seed = int(seed)++ def go(x, key=""):+ if (key == "seed" or key.endswith("_seed")) and not isinstance(x, (dict, list, tuple)):+ return HIDDEN+ if key in KEEP: # the core's step counters: never the seed, may reach six digits+ return x+ if isinstance(x, dict):+ return {k: go(v, str(k)) for k, v in x.items()}+ if isinstance(x, (list, tuple)):+ return [go(v) for v in x]+ if isinstance(x, bool):+ return x+ if isinstance(x, int) and x == seed:+ return HIDDEN+ if isinstance(x, float) and x == seed:+ return float(HIDDEN)+ if isinstance(x, str) and (x == str(seed) or (salt and x == salt)):+ return str(HIDDEN)+ return x+ return go(obj)diff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/sport_grade.py b/tasks/roboolympics-fencing-bout-i02-standard/tests/sport_grade.pynew file mode 100644index 0000000000..a6c7b75098--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/sport_grade.py@@ -0,0 +1,77 @@+"""fencing's part of reward.json (the common part is core/grading.py: success, valid_trial, technical_failure,+deterministic, seed, official_config, video_rendered, <seat>_won, <seat>_transient/unrecovered_api_errors, ...):+numbers only, from final.json (and the seat's metering summary think_usage_<seat>.json, a declared artifact of the+sim). fencing-7 (the phrase-level sport): the bout's phrases instead of fencing-6's halts; the legacy reward names+of both tasks are kept where they still mean something (README.md)."""+import json+import os+from collections import Counter+from pathlib import Path++DATA = Path(os.environ.get("RCB_DATA", "/data"))+COUNTS = ("n_act", "n_observe", "n_reviews", "refused_busy", "refused_turn", "refused_not_model")+++def _usage(seat):+ try:+ return json.loads((DATA / f"think_usage_{seat}.json").read_text())+ except (OSError, ValueError):+ return {}+++def _bout(f):+ ph = f.get("phrases") or []+ return {"bout_over": int(f.get("how") in ("touches", "passivity", "time", "deciding_touch", "priority")),+ "extra_minute": int(bool(f.get("extra_minute"))), "phrases": len(ph),+ "doubles": sum(1 for r in ph if r.get("res") == "double"),+ "doubles_not_counted": sum(1 for r in ph if r.get("annulled")),+ "no_touch_phrases": sum(1 for r in ph if r.get("res") == "none"),+ "p_cards": int(f.get("p_cards") or 0), "fencing_time_s": float(f.get("fencing_time_s") or 0.0)}+++def _intentions(f, side, prefix):+ c = Counter((r.get("intentions") or {}).get(side) for r in f.get("phrases") or [])+ names = ("lunge", "low", "line", "rline", "stop", "counter", "delay", "retreat", "draw")+ return {f"{prefix}intention_{n}": int(c.get(n, 0)) for n in names}+++def evaluate(d):+ f = d.get("sport_fields") or {}+ seats = d["cfg"]["seats"]+ scores = d.get("scores") or {}+ stats = d.get("seats") or {}+ out = _bout(f)+ if len(seats) == 1: # the bout against the scripted fencer (side B)+ s = seats[0]+ st, u = stats.get(s, {}), _usage(s)+ errs = d.get("errors") or []+ won = d.get("match_winner") == s and out["bout_over"] == 1+ rp = d.get("replay_scores") or {}+ pf, pa = int(scores.get(s, 0)), int(scores.get("B", 0))+ out.update(+ won=int(won), level=int(f.get("level") or 0), won_on_priority=int(won and f.get("how") == "priority"),+ sim_error=int(d.get("reason") == "technical_error" or any(e.get("where") != "replay" for e in errs)),+ replay_error=int(not d.get("deterministic") or any(e.get("where") == "replay" for e in errs)),+ meter_error=int(bool((d.get("meter_error") or {}).get(s))),+ proxy_error=int(bool((d.get("proxy_error") or {}).get(s))), finalized=int(bool(d.get("finalized"))),+ touches_for=pf, touches_against=pa, points_for=pf, points_against=pa,+ replay_touches_for=int(rp.get(s, -1)), replay_touches_against=int(rp.get("B", -1)),+ clock_forfeit=int(f.get("how") == "clock"), clock_used_s=float((d.get("clock_used_s") or {}).get(s, 0.0)),+ elapsed_s=float(d.get("elapsed_s") or 0.0), metered_requests=int(u.get("requests", 0)),+ metered_output_tokens=int(u.get("output_tokens", 0)), metered_input_tokens=int(u.get("input_tokens", 0)),+ rate_limit_retries=int(u.get("rate_limit_retries", 0)),+ transient_api_errors=int((d.get("transient_api_errors") or {}).get(s, 0)),+ unrecovered_api_errors=int((d.get("unrecovered_api_errors") or {}).get(s, 0)),+ **{k: int(st.get(k, 0)) for k in COUNTS}, **_intentions(f, s, ""), **_intentions(f, "B", "opponent_"))+ return out+ out.update(won_on_priority=int(bool(d.get("valid_trial")) and f.get("how") == "priority"),+ clock_forfeit=int(f.get("how") == "clock"), abandoned=int(f.get("how") == "abandoned"),+ first_player_A=int(f.get("first_player") == "A"), elapsed_s=float(d.get("elapsed_s") or 0.0))+ for s in seats:+ st = stats.get(s, {})+ out[s + "_points"] = int(scores.get(s, 0))+ out[s + "_clock_used_s"] = float((d.get("clock_used_s") or {}).get(s, 0.0))+ for k in COUNTS:+ out[s + "_" + k] = int(st.get(k, 0))+ out.update(_intentions(f, s, s + "_"))+ return outdiff --git a/tasks/roboolympics-fencing-bout-i02-standard/tests/test.sh b/tasks/roboolympics-fencing-bout-i02-standard/tests/test.shnew file mode 100755index 0000000000..7b1faa5b84--- /dev/null+++ b/tasks/roboolympics-fencing-bout-i02-standard/tests/test.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+mkdir -p /logs/verifier+rm -rf /logs/verifier/*+trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resource limits, after the grader (docs/PROTOCOL.md §2.10)+p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # the agent's files are untrusted input: no link out of /app/output, no FIFO or device (docs/PROTOCOL.md §2.6)+python /tests/grade.py 2> /logs/verifier/grade.log+python /tests/fexam_reward.py 2>> /logs/verifier/grade.log