PeterXie666 commited on
Commit
8376aa1
·
verified ·
1 Parent(s): dc91c99

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_opus/lerobot_replay.py +744 -0
  2. leaf/code/models-20261115-g56sol_canary_20261114/lerobot_export.py +431 -0
  3. leaf/code/supp-20261113-rc_test1_20261106/lerobot_export.py +431 -0
  4. leaf/code/supp-20261113-rc_test1_20261106/lerobot_replay.py +744 -0
  5. leaf/code/v1.5/backfill-20261102-lf1_opus_r2/lerobot_replay.py +744 -0
  6. leaf/code/v1.5/backfill-20261102-lhp_gpt/lerobot_export.py +431 -0
  7. leaf/code/v1.5/backfill-20261102-lhp_gpt/lerobot_replay.py +744 -0
  8. leaf/code/v1.5/backfill-20261102-lhp_opus_r2/lerobot_export.py +431 -0
  9. leaf/code/v1.5/backfill-20261102-lhp_opus_r2/lerobot_replay.py +744 -0
  10. leaf/code/v1.5/backfill-20261102-tw2_opus/lerobot_export.py +431 -0
  11. leaf/final/episode_001471_image.png +3 -0
  12. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json +15 -0
  13. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_high.json +36 -0
  14. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +27 -0
  15. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +18 -0
  16. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_card_edge.py +364 -0
  17. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_wide.py +435 -0
  18. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l4_diagonal.py +524 -0
  19. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py +954 -0
  20. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_tray_delivery.py +883 -0
  21. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/__init__.py +53 -0
  22. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_under_table_tool.py +50 -0
  23. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/__init__.py +10 -0
  24. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l2_turntable.py +469 -0
  25. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l3_card_shelf.py +587 -0
  26. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l5_iterative.py +136 -0
  27. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l5_slippery_lift.py +262 -0
  28. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_parts_cart.py +253 -0
  29. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/mismatch_plan.py +149 -0
  30. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py +61 -0
  31. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/camera.py +100 -0
  32. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l3_card_shelf.py +587 -0
  33. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/model_gateway.py +562 -0
  34. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/validate_ladder_fix.py +168 -0
  35. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json +15 -0
  36. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json +15 -0
  37. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json +23 -0
  38. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json +23 -0
  39. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json +23 -0
  40. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json +36 -0
  41. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json +36 -0
  42. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/run_agent.py +220 -0
  43. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l3_card_edge.py +364 -0
  44. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l4_diagonal.py +524 -0
  45. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l6_count.py +562 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json +15 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +18 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/real/executor.py +138 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l1_height.py +448 -0
leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_opus/lerobot_replay.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
2
+ against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
3
+ LeRobot export (scripts/lerobot_export.py).
4
+
5
+ python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
6
+ python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
7
+
8
+ Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
9
+ commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
10
+ is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
11
+ like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
12
+ outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
13
+ ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
14
+ hashes equal the current files are expected to match (check_code()).
15
+
16
+ Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
17
+ proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
18
+ protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
19
+ per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
20
+ fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
21
+ agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
22
+ frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
23
+ sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
24
+ final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
25
+ annotation.json episode annotation (build_annotation)
26
+ and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
27
+ """
28
+ import argparse
29
+ import ast
30
+ import hashlib
31
+ import importlib
32
+ import json
33
+ import math
34
+ import os
35
+ import pkgutil
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections import defaultdict
41
+
42
+ import numpy as np
43
+
44
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
45
+ sys.path.insert(0, LFF_ROOT)
46
+
47
+ from lffbench import envs # noqa: E402
48
+ from lffbench import tasks as task_pkg # noqa: E402
49
+ from lffbench.agent import camera as C # noqa: E402
50
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
51
+ from lffbench.task_base import TASKS # noqa: E402
52
+
53
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
54
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
55
+
56
+ # per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
57
+ # task's outcome() check after `finish` (the arm holds still; not an agent action)
58
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
59
+ FPS = 20
60
+ SCHEMA = "lff-replay-1"
61
+
62
+ # error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
63
+ ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
64
+ ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
65
+ "n_missed_strikes", "n_open_gripper_pushes")
66
+
67
+
68
+ def load_jsonl(p):
69
+ out = []
70
+ if not os.path.exists(p):
71
+ return out
72
+ with open(p) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if line:
76
+ try:
77
+ out.append(json.loads(line))
78
+ except ValueError:
79
+ pass
80
+ return out
81
+
82
+
83
+ def norm_json(o):
84
+ return json.loads(json.dumps(o, default=_json_default))
85
+
86
+
87
+ def sha256(p):
88
+ with open(p, "rb") as f:
89
+ return hashlib.sha256(f.read()).hexdigest()
90
+
91
+
92
+ def check_code(run_dir):
93
+ """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
94
+ p = os.path.join(run_dir, "contract.json")
95
+ if not os.path.exists(p):
96
+ return [("contract.json", None, None)]
97
+ files = json.load(open(p))["contract"].get("server_code_files", {})
98
+ bad = []
99
+ for f, h in files.items():
100
+ q = os.path.join(LFF_ROOT, f)
101
+ cur = sha256(q) if os.path.exists(q) else None
102
+ if cur != h:
103
+ bad.append((f, h, cur))
104
+ return bad
105
+
106
+
107
+ def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
108
+ """Differences between two JSON values (numbers compared with an absolute tolerance)."""
109
+ out = [] if out is None else out
110
+ if len(out) >= limit:
111
+ return out
112
+ if isinstance(a, dict) and isinstance(b, dict):
113
+ for k in sorted(set(a) | set(b)):
114
+ if k not in a or k not in b:
115
+ out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
116
+ else:
117
+ diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
118
+ elif isinstance(a, list) and isinstance(b, list):
119
+ if len(a) != len(b):
120
+ out.append((path, f"len {len(a)}", f"len {len(b)}"))
121
+ else:
122
+ for i, (x, y) in enumerate(zip(a, b)):
123
+ diff_json(x, y, f"{path}[{i}]", tol, out, limit)
124
+ elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
125
+ if a != b:
126
+ out.append((path, a, b))
127
+ elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
128
+ out.append((path, a, b))
129
+ return out
130
+
131
+
132
+ def error_event(o):
133
+ """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
134
+ if not isinstance(o, dict):
135
+ return None
136
+ keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
137
+ if not keys:
138
+ return None
139
+ return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
140
+
141
+
142
+ # ====================================================================================================== logs -> notes
143
+
144
+ class RunLog:
145
+ """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
146
+ narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
147
+
148
+ def __init__(self, run_dir, manifest=None):
149
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
150
+ self.run = os.path.basename(self.run_dir)
151
+ self.batch = os.path.basename(os.path.dirname(self.run_dir))
152
+ self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
153
+ self.start = next(e for e in self.ev if e["ev"] == "session_start")
154
+ self.calls, self.dones, self.harness_status = {}, [], []
155
+ last = None
156
+ for e in self.ev:
157
+ if e["ev"] == "call":
158
+ self.calls[(int(e["attempt"]), int(e["step"]))] = e
159
+ last = e
160
+ elif e["ev"] == "done":
161
+ self.dones.append(e)
162
+ last = e
163
+ elif e["ev"] == "http" and last is not None and "think_s" not in last:
164
+ ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
165
+ (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
166
+ if ok:
167
+ last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
168
+ self.manifest = manifest or {}
169
+ self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
170
+ p = os.path.join(self.run_dir, "harness.json")
171
+ self.harness = json.load(open(p)) if os.path.exists(p) else {}
172
+ self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
173
+ self._narration()
174
+
175
+ # ---------------------------------------------------------------- agent narration
176
+ def _narration(self):
177
+ """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
178
+ finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
179
+ self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
180
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
181
+ attempt = 1
182
+
183
+ def take():
184
+ nonlocal buf
185
+ out = {k: v for k, v in buf.items() if v}
186
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
187
+ return out
188
+
189
+ last_msg = ""
190
+ for t in self.traj:
191
+ if t.get("kind") == "header":
192
+ self.headers.append(t.get("agent") or {})
193
+ continue
194
+ if t.get("kind") != "step":
195
+ continue
196
+ if (t.get("message") or "").strip():
197
+ buf["messages"].append(t["message"].strip())
198
+ last_msg = t["message"].strip()
199
+ if (t.get("reasoning_content") or "").strip():
200
+ buf["reasoning"].append(t["reasoning_content"].strip())
201
+ res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
202
+ for c in t.get("tool_calls") or []:
203
+ fn, args = c.get("function_name"), c.get("arguments") or {}
204
+ if fn == "shell":
205
+ buf["shell"].append(str(args.get("command", ""))[:2000])
206
+ elif fn == "view_images":
207
+ buf["viewed"].extend(args.get("paths") or [])
208
+ elif fn == "robot":
209
+ cmd = str(args.get("command", "")).strip()
210
+ r = res.get(c.get("tool_call_id")) or {}
211
+ try:
212
+ rep = json.loads(r.get("content") or "{}")
213
+ except ValueError:
214
+ rep = {}
215
+ word = cmd.split()[0] if cmd else ""
216
+ m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
217
+ if word in ("move_eef", "observe") and m:
218
+ a, s = int(m.group(1)), int(m.group(2))
219
+ n = take()
220
+ n["command"] = cmd
221
+ self.notes[(a, s)] = n
222
+ attempt = a
223
+ elif word in ("finish", "done"):
224
+ n = take()
225
+ n["command"] = cmd
226
+ n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
227
+ self.finish_notes.setdefault(attempt, n)
228
+ if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
229
+ attempt += 1
230
+ # status / help / errors: their narration stays in the buffer for the next command
231
+ self.final_report = last_msg
232
+
233
+ # ---------------------------------------------------------------- run-level labels
234
+ def attempts(self):
235
+ out = []
236
+ for e in self.dones:
237
+ o = e.get("outcome") or {}
238
+ if isinstance(o, str):
239
+ try:
240
+ o = ast.literal_eval(o)
241
+ except (ValueError, SyntaxError):
242
+ o = {}
243
+ out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
244
+ reason=e.get("reason") or ""))
245
+ return sorted(out, key=lambda x: x["attempt"])
246
+
247
+ def condition(self):
248
+ s, en = self.start, self.entry
249
+ mem = s.get("memory", en.get("mem"))
250
+ chain = en.get("chain")
251
+ if mem == "full":
252
+ cond = "with_history"
253
+ elif chain:
254
+ cond = "memory_free_retry"
255
+ else:
256
+ cond = "independent_single_attempt"
257
+ return cond, chain
258
+
259
+ def outcome_class(self):
260
+ """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
261
+ att = self.attempts()
262
+ if not att or self.start.get("memory") != "full":
263
+ return None, "".join("S" if a["success"] else "F" for a in att)
264
+ hist = "".join("S" if a["success"] else "F" for a in att)
265
+ if att[0]["success"]:
266
+ ev = error_event(att[0]["outcome"])
267
+ cls = "S?" if ev is None else ("IR" if ev else "CS")
268
+ else:
269
+ cls = "XR" if any(a["success"] for a in att) else "F"
270
+ return cls, hist
271
+
272
+ def agent_info(self):
273
+ h, en = self.harness, self.entry
274
+ hdr = self.headers[0] if self.headers else {}
275
+ return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
276
+ harness_version=h.get("version") or hdr.get("version"),
277
+ harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
278
+ model=h.get("model") or en.get("model") or hdr.get("model_name"),
279
+ effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
280
+ provider=h.get("provider") or en.get("provider"),
281
+ codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
282
+ jail=en.get("jail"))
283
+
284
+
285
+ # ====================================================================================================== recording
286
+
287
+ class EpisodeSink:
288
+ """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
289
+
290
+ def __init__(self, path):
291
+ self.path = path
292
+ os.makedirs(path, exist_ok=True)
293
+ self.w = None
294
+ self.num = defaultdict(list)
295
+ self.n = 0
296
+
297
+ def add(self, st, imgs):
298
+ import imageio
299
+ if self.w is None:
300
+ self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
301
+ pixelformat="rgb24", macro_block_size=1,
302
+ ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
303
+ for k in ("agentview", "wrist")]
304
+ for w, im in zip(self.w, imgs):
305
+ w.append_data(im)
306
+ for k, v in st.items():
307
+ self.num[k].append(v)
308
+ self.n += 1
309
+
310
+ def close(self, final_state, final_imgs):
311
+ from PIL import Image
312
+ if self.w is not None:
313
+ for w in self.w:
314
+ w.close()
315
+ arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
316
+ np.savez(os.path.join(self.path, "frames.npz"), **arr)
317
+ if self.num.get("sim_state"):
318
+ np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
319
+ np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
320
+ for k, im in zip(("agentview", "wrist"), final_imgs):
321
+ Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
322
+
323
+
324
+ class Recorder:
325
+ """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
326
+
327
+ def __init__(self, rp, res):
328
+ self.rp, self.res = rp, int(res)
329
+ self.active = False
330
+ self.sink = None
331
+ self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
332
+ env = rp.task.env
333
+ self.env, self.rob = env, env.robots[0]
334
+ self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
335
+ orig = env.step
336
+
337
+ def step(a):
338
+ if self.active and self.sink is not None:
339
+ self.capture(np.asarray(a, np.float64))
340
+ out = orig(a)
341
+ if self.active and self.sink is not None:
342
+ self.rp.poll_events(self.sink.n - 1)
343
+ return out
344
+
345
+ env.step = step
346
+
347
+ @property
348
+ def n(self):
349
+ return self.sink.n if self.sink is not None else 0
350
+
351
+ def state(self):
352
+ import robosuite.utils.transform_utils as T
353
+ env, rob = self.env, self.rob
354
+ d = env.sim.data
355
+ eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
356
+ q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
357
+ gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
358
+ try:
359
+ flat = np.asarray(env.sim.get_state().flatten(), np.float64)
360
+ except Exception:
361
+ flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
362
+ sk = self.rp.task.sk
363
+ return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
364
+ gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
365
+ joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
366
+ gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
367
+ eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
368
+ sim_time=np.float64(d.time), sim_state=flat)
369
+
370
+ def images(self):
371
+ return [envs.render(self.env, c, self.res) for c in self.cams]
372
+
373
+ def capture(self, a):
374
+ st = self.state()
375
+ st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
376
+ phase=np.int64(self.cur["phase"]))
377
+ self.sink.add(st, self.images())
378
+
379
+
380
+ class RunReplay:
381
+ def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
382
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
383
+ self.run_name = os.path.basename(self.run_dir)
384
+ self.log = RunLog(self.run_dir, manifest)
385
+ self.ev = self.log.ev
386
+ self.start = self.log.start
387
+ cp = os.path.join(self.run_dir, "contract.json")
388
+ self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
389
+ spec = self.contract.get("image_spec") or {}
390
+ self.image_res = int(spec.get("width", 512))
391
+ self.code_diff = check_code(self.run_dir)
392
+ s = self.start
393
+ self.task = TASKS[s["task"]](cam_res=self.image_res)
394
+ inst = self.task.sample_instance(s["seed"])
395
+ logged = s.get("inst") or {}
396
+ sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
397
+ self.inst_diff = diff_json(sampled, logged, "inst")
398
+ if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
399
+ inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
400
+ self.inst_diff = []
401
+ self.inst = inst
402
+ self.protocol = getattr(self.task, "protocol", "cross")
403
+ self.k = int(s.get("k") or self.task.max_attempts)
404
+ self.attempt = 1
405
+ self.mismatch = [] # (where, what, logged, replayed)
406
+ self.n_checked = 0
407
+ self.max_dev_m = 0.0
408
+ self.unfinished = None
409
+ self.rec = Recorder(self, res) if record else None
410
+ self.res = int(res)
411
+ self.out_root = out_root
412
+ self.n_mon = 0
413
+ self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
414
+ self.episodes = [] # summaries of the written episodes
415
+ self.task.reset_instance(self.inst)
416
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
417
+ sim = self.task.env.sim
418
+ bid = sim.model.body_name2id("robot0_base")
419
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
420
+ if self.rec:
421
+ self._open_episode()
422
+
423
+ # ------------------------------------------------------------------ episodes
424
+ def _ep_dir(self):
425
+ return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
426
+
427
+ def _open_episode(self):
428
+ self.rec.sink = EpisodeSink(self._ep_dir())
429
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
430
+ self.rec.active = True
431
+ self.events, self.spans, self.ep_attempts = [], [], []
432
+ self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
433
+
434
+ def close_episode(self):
435
+ if not self.rec:
436
+ self.ep_attempts = []
437
+ return
438
+ sink = self.rec.sink
439
+ st = self.rec.state()
440
+ imgs = self.rec.images()
441
+ st.pop("sim_state", None)
442
+ sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
443
+ ann = build_annotation(self, sink)
444
+ with open(os.path.join(sink.path, "annotation.json"), "w") as f:
445
+ json.dump(ann, f, indent=1, default=_json_default)
446
+ self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
447
+ attempts=[a["attempt"] for a in self.ep_attempts]))
448
+ self.rec.active = False
449
+ self.rec.sink = None
450
+ self.ep_index += 1
451
+
452
+ # ------------------------------------------------------------------ monitor events (task-side error events)
453
+ def poll_events(self, frame):
454
+ mon = getattr(self.task, "mon", None)
455
+ evs = mon.get("events") if isinstance(mon, dict) else None
456
+ if not isinstance(evs, list):
457
+ return
458
+ if len(evs) < self.n_mon: # monitor was rebuilt
459
+ self.n_mon = 0
460
+ for e in evs[self.n_mon:]:
461
+ self.events.append(dict(frame=int(frame), attempt=self.attempt,
462
+ event=norm_json(e) if isinstance(e, dict) else str(e)))
463
+ self.n_mon = len(evs)
464
+
465
+ # ------------------------------------------------------------------ state as the server reports it
466
+ def proprio_la(self):
467
+ p = self.ex.proprio()
468
+ pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
469
+ return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
470
+
471
+ def compare(self, where, rep_logged, rep):
472
+ self.n_checked += 1
473
+ for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
474
+ if k not in rep_logged or k not in rep:
475
+ continue
476
+ a, b = rep_logged[k], rep[k]
477
+ if k == "eef_pos":
478
+ dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
479
+ self.max_dev_m = max(self.max_dev_m, dev)
480
+ if dev > 1.5e-4:
481
+ self.mismatch.append((where, k, a, b))
482
+ elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
483
+ self.mismatch.append((where, k, a, b))
484
+ if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
485
+ self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
486
+
487
+ def _span(self, e, f0, kind):
488
+ if self.rec:
489
+ self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
490
+ frame_end=self.rec.n))
491
+
492
+ # ------------------------------------------------------------------ commands (robot_server._handle_v2)
493
+ def move_eef(self, e):
494
+ args = e.get("args") or {}
495
+ where = f"a{e['attempt']}s{e['step']}"
496
+ logged = e.get("report") or {}
497
+ f0 = self.rec.n if self.rec else 0
498
+ p = self.ex.proprio()
499
+ if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
500
+ self._span(e, f0, "error")
501
+ return self.compare(where, logged, dict(ok=False))
502
+ off = self.base_off
503
+ try:
504
+ cur = np.asarray(p["eef_pos"], float) - off
505
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
506
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
507
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
508
+ except (TypeError, ValueError):
509
+ self._span(e, f0, "error")
510
+ return self.compare(where, logged, dict(ok=False))
511
+ grip = args.get("gripper")
512
+ if grip not in (None, "open", "close"):
513
+ self._span(e, f0, "error")
514
+ return self.compare(where, logged, dict(ok=False))
515
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
516
+ tgt_w = np.asarray(tgt) + off
517
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
518
+ self._span(e, f0, "rejected")
519
+ return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
520
+ raw = {}
521
+ if self.rec:
522
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
523
+ if moving:
524
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
525
+ if speed is not None:
526
+ mv["speed"] = speed
527
+ raw.update(self.ex.call("move_to", mv).report)
528
+ if grip is not None:
529
+ if self.rec:
530
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
531
+ raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
532
+ rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
533
+ self.compare(where, logged, rep)
534
+ lr = e.get("raw") or {}
535
+ for k in ("holding_object", "touched_object"):
536
+ if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
537
+ self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
538
+ self._span(e, f0, "move_eef")
539
+
540
+ def observe(self, e):
541
+ f0 = self.rec.n if self.rec else 0
542
+ self._span(e, f0, "observe")
543
+
544
+ def done(self, e):
545
+ f0 = self.rec.n if self.rec else 0
546
+ if self.rec:
547
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
548
+ out = self.task.outcome(self.inst)
549
+ succ = bool(out["success"])
550
+ where = f"a{e['attempt']}done"
551
+ if succ != bool(e.get("success") in (True, "True")):
552
+ self.mismatch.append((where, "success", e.get("success"), succ))
553
+ lo = e.get("outcome") or {}
554
+ ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
555
+ if isinstance(lo, dict):
556
+ for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
557
+ self.mismatch.append((where,) + d)
558
+ info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
559
+ feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
560
+ think_s=e.get("think_s"))
561
+ try:
562
+ info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
563
+ except Exception as ex_:
564
+ info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
565
+ if self.rec:
566
+ info["judge_frames"] = [f0, self.rec.n]
567
+ self.ep_attempts.append(info)
568
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
569
+ if self.protocol == "cross" or last:
570
+ self.close_episode()
571
+ if last:
572
+ return True
573
+ self.attempt += 1
574
+ if self.protocol == "cross":
575
+ self.task.reset_instance(self.inst)
576
+ self.n_mon = 0
577
+ if self.rec:
578
+ self._open_episode()
579
+ elif self.rec:
580
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
581
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
582
+ return False
583
+
584
+ def run(self):
585
+ t0 = time.time()
586
+ finished = False
587
+ for e in self.ev:
588
+ if e["ev"] == "call":
589
+ if e.get("cmd") == "move_eef":
590
+ self.move_eef(e)
591
+ elif e.get("cmd") == "observe":
592
+ self.observe(e)
593
+ else:
594
+ self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
595
+ elif e["ev"] == "done":
596
+ finished = self.done(e)
597
+ if finished:
598
+ break
599
+ self.unfinished = not finished
600
+ if not finished and self.rec and self.rec.sink is not None:
601
+ # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
602
+ if self.rec.n or self.ep_attempts:
603
+ self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
604
+ finish_reason="", feedback_shown="", auto_ended=False))
605
+ self.close_episode()
606
+ else:
607
+ shutil.rmtree(self.rec.sink.path, ignore_errors=True)
608
+ self.rec.sink = None
609
+ self.wall_s = time.time() - t0
610
+ return self
611
+
612
+ def summary(self):
613
+ return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
614
+ protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
615
+ n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
616
+ unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
617
+ first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
618
+
619
+
620
+ # ====================================================================================================== annotation
621
+
622
+ def task_info(task, inst):
623
+ cls = type(task)
624
+ return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
625
+ category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
626
+ max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
627
+ instruction=cls.instruction)
628
+
629
+
630
+ def build_annotation(rp, sink):
631
+ """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
632
+ failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
633
+ task-side error events with frame indices."""
634
+ log = rp.log
635
+ s = rp.start
636
+ cond, chain = log.condition()
637
+ cls, hist = log.outcome_class()
638
+ att_all = log.attempts()
639
+ attempts = []
640
+ for a in rp.ep_attempts:
641
+ a = dict(a)
642
+ n = a["attempt"]
643
+ later = [x for x in att_all if x["attempt"] > n]
644
+ a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
645
+ a["is_last_attempt_of_run"] = not later
646
+ fn = log.finish_notes.get(n)
647
+ if fn:
648
+ a["agent_finish"] = fn
649
+ a["error_event_in_attempt"] = error_event(a.get("outcome"))
650
+ attempts.append(a)
651
+ # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
652
+ for a in attempts:
653
+ nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
654
+ if a.get("success") is False and nxt:
655
+ note = log.notes[nxt[0]]
656
+ a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
657
+ commands = []
658
+ for sp in rp.spans:
659
+ e = log.calls.get((sp["attempt"], sp["step"])) or {}
660
+ rep = e.get("report") or {}
661
+ c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
662
+ frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
663
+ args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
664
+ stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
665
+ gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
666
+ touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
667
+ agent_obs_images=rep.get("images"))
668
+ note = log.notes.get((sp["attempt"], sp["step"]))
669
+ if note:
670
+ c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
671
+ commands.append(c)
672
+ t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
673
+ return dict(
674
+ schema=SCHEMA,
675
+ source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
676
+ episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
677
+ memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
678
+ feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
679
+ k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
680
+ contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
681
+ if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
682
+ agent=log.agent_info(),
683
+ task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
684
+ instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
685
+ run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
686
+ run_success=any(x["success"] for x in att_all) if att_all else None,
687
+ agent_final_report=log.final_report[:6000] or None,
688
+ mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
689
+ attempts=attempts,
690
+ commands=commands,
691
+ task_events=rp.events,
692
+ frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
693
+ phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
694
+ joint_pos=rp.ep_initial["joint_pos"],
695
+ gripper_qpos=rp.ep_initial["gripper_qpos"])),
696
+ )
697
+
698
+
699
+ # ====================================================================================================== CLI
700
+
701
+ def load_manifest(run_dir):
702
+ p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
703
+ return json.load(open(p)) if os.path.exists(p) else {}
704
+
705
+
706
+ def main():
707
+ ap = argparse.ArgumentParser()
708
+ ap.add_argument("mode", choices=["check", "record"])
709
+ ap.add_argument("runs", nargs="+")
710
+ ap.add_argument("--json", default="")
711
+ ap.add_argument("--out", default="")
712
+ ap.add_argument("--res", type=int, default=256)
713
+ ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
714
+ a = ap.parse_args()
715
+ rows = []
716
+ for r in a.runs:
717
+ r = r.rstrip("/")
718
+ try:
719
+ if a.mode == "check":
720
+ s = RunReplay(r, manifest=load_manifest(r)).run().summary()
721
+ else:
722
+ batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
723
+ rd = os.path.join(a.out, batch, name)
724
+ if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
725
+ print(json.dumps(dict(run=name, skipped="exists")), flush=True)
726
+ continue
727
+ shutil.rmtree(rd, ignore_errors=True)
728
+ rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
729
+ s = rp.summary()
730
+ s["episodes"] = rp.episodes
731
+ with open(os.path.join(rd, "replay.json"), "w") as f:
732
+ json.dump(s, f, indent=1)
733
+ except Exception:
734
+ import traceback
735
+ s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
736
+ rows.append(s)
737
+ print(json.dumps(s), flush=True)
738
+ if a.json:
739
+ with open(a.json, "w") as f:
740
+ json.dump(rows, f, indent=1)
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
leaf/code/models-20261115-g56sol_canary_20261114/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/code/supp-20261113-rc_test1_20261106/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/code/supp-20261113-rc_test1_20261106/lerobot_replay.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
2
+ against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
3
+ LeRobot export (scripts/lerobot_export.py).
4
+
5
+ python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
6
+ python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
7
+
8
+ Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
9
+ commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
10
+ is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
11
+ like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
12
+ outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
13
+ ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
14
+ hashes equal the current files are expected to match (check_code()).
15
+
16
+ Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
17
+ proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
18
+ protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
19
+ per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
20
+ fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
21
+ agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
22
+ frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
23
+ sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
24
+ final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
25
+ annotation.json episode annotation (build_annotation)
26
+ and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
27
+ """
28
+ import argparse
29
+ import ast
30
+ import hashlib
31
+ import importlib
32
+ import json
33
+ import math
34
+ import os
35
+ import pkgutil
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections import defaultdict
41
+
42
+ import numpy as np
43
+
44
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
45
+ sys.path.insert(0, LFF_ROOT)
46
+
47
+ from lffbench import envs # noqa: E402
48
+ from lffbench import tasks as task_pkg # noqa: E402
49
+ from lffbench.agent import camera as C # noqa: E402
50
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
51
+ from lffbench.task_base import TASKS # noqa: E402
52
+
53
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
54
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
55
+
56
+ # per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
57
+ # task's outcome() check after `finish` (the arm holds still; not an agent action)
58
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
59
+ FPS = 20
60
+ SCHEMA = "lff-replay-1"
61
+
62
+ # error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
63
+ ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
64
+ ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
65
+ "n_missed_strikes", "n_open_gripper_pushes")
66
+
67
+
68
+ def load_jsonl(p):
69
+ out = []
70
+ if not os.path.exists(p):
71
+ return out
72
+ with open(p) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if line:
76
+ try:
77
+ out.append(json.loads(line))
78
+ except ValueError:
79
+ pass
80
+ return out
81
+
82
+
83
+ def norm_json(o):
84
+ return json.loads(json.dumps(o, default=_json_default))
85
+
86
+
87
+ def sha256(p):
88
+ with open(p, "rb") as f:
89
+ return hashlib.sha256(f.read()).hexdigest()
90
+
91
+
92
+ def check_code(run_dir):
93
+ """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
94
+ p = os.path.join(run_dir, "contract.json")
95
+ if not os.path.exists(p):
96
+ return [("contract.json", None, None)]
97
+ files = json.load(open(p))["contract"].get("server_code_files", {})
98
+ bad = []
99
+ for f, h in files.items():
100
+ q = os.path.join(LFF_ROOT, f)
101
+ cur = sha256(q) if os.path.exists(q) else None
102
+ if cur != h:
103
+ bad.append((f, h, cur))
104
+ return bad
105
+
106
+
107
+ def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
108
+ """Differences between two JSON values (numbers compared with an absolute tolerance)."""
109
+ out = [] if out is None else out
110
+ if len(out) >= limit:
111
+ return out
112
+ if isinstance(a, dict) and isinstance(b, dict):
113
+ for k in sorted(set(a) | set(b)):
114
+ if k not in a or k not in b:
115
+ out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
116
+ else:
117
+ diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
118
+ elif isinstance(a, list) and isinstance(b, list):
119
+ if len(a) != len(b):
120
+ out.append((path, f"len {len(a)}", f"len {len(b)}"))
121
+ else:
122
+ for i, (x, y) in enumerate(zip(a, b)):
123
+ diff_json(x, y, f"{path}[{i}]", tol, out, limit)
124
+ elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
125
+ if a != b:
126
+ out.append((path, a, b))
127
+ elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
128
+ out.append((path, a, b))
129
+ return out
130
+
131
+
132
+ def error_event(o):
133
+ """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
134
+ if not isinstance(o, dict):
135
+ return None
136
+ keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
137
+ if not keys:
138
+ return None
139
+ return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
140
+
141
+
142
+ # ====================================================================================================== logs -> notes
143
+
144
+ class RunLog:
145
+ """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
146
+ narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
147
+
148
+ def __init__(self, run_dir, manifest=None):
149
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
150
+ self.run = os.path.basename(self.run_dir)
151
+ self.batch = os.path.basename(os.path.dirname(self.run_dir))
152
+ self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
153
+ self.start = next(e for e in self.ev if e["ev"] == "session_start")
154
+ self.calls, self.dones, self.harness_status = {}, [], []
155
+ last = None
156
+ for e in self.ev:
157
+ if e["ev"] == "call":
158
+ self.calls[(int(e["attempt"]), int(e["step"]))] = e
159
+ last = e
160
+ elif e["ev"] == "done":
161
+ self.dones.append(e)
162
+ last = e
163
+ elif e["ev"] == "http" and last is not None and "think_s" not in last:
164
+ ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
165
+ (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
166
+ if ok:
167
+ last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
168
+ self.manifest = manifest or {}
169
+ self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
170
+ p = os.path.join(self.run_dir, "harness.json")
171
+ self.harness = json.load(open(p)) if os.path.exists(p) else {}
172
+ self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
173
+ self._narration()
174
+
175
+ # ---------------------------------------------------------------- agent narration
176
+ def _narration(self):
177
+ """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
178
+ finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
179
+ self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
180
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
181
+ attempt = 1
182
+
183
+ def take():
184
+ nonlocal buf
185
+ out = {k: v for k, v in buf.items() if v}
186
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
187
+ return out
188
+
189
+ last_msg = ""
190
+ for t in self.traj:
191
+ if t.get("kind") == "header":
192
+ self.headers.append(t.get("agent") or {})
193
+ continue
194
+ if t.get("kind") != "step":
195
+ continue
196
+ if (t.get("message") or "").strip():
197
+ buf["messages"].append(t["message"].strip())
198
+ last_msg = t["message"].strip()
199
+ if (t.get("reasoning_content") or "").strip():
200
+ buf["reasoning"].append(t["reasoning_content"].strip())
201
+ res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
202
+ for c in t.get("tool_calls") or []:
203
+ fn, args = c.get("function_name"), c.get("arguments") or {}
204
+ if fn == "shell":
205
+ buf["shell"].append(str(args.get("command", ""))[:2000])
206
+ elif fn == "view_images":
207
+ buf["viewed"].extend(args.get("paths") or [])
208
+ elif fn == "robot":
209
+ cmd = str(args.get("command", "")).strip()
210
+ r = res.get(c.get("tool_call_id")) or {}
211
+ try:
212
+ rep = json.loads(r.get("content") or "{}")
213
+ except ValueError:
214
+ rep = {}
215
+ word = cmd.split()[0] if cmd else ""
216
+ m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
217
+ if word in ("move_eef", "observe") and m:
218
+ a, s = int(m.group(1)), int(m.group(2))
219
+ n = take()
220
+ n["command"] = cmd
221
+ self.notes[(a, s)] = n
222
+ attempt = a
223
+ elif word in ("finish", "done"):
224
+ n = take()
225
+ n["command"] = cmd
226
+ n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
227
+ self.finish_notes.setdefault(attempt, n)
228
+ if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
229
+ attempt += 1
230
+ # status / help / errors: their narration stays in the buffer for the next command
231
+ self.final_report = last_msg
232
+
233
+ # ---------------------------------------------------------------- run-level labels
234
+ def attempts(self):
235
+ out = []
236
+ for e in self.dones:
237
+ o = e.get("outcome") or {}
238
+ if isinstance(o, str):
239
+ try:
240
+ o = ast.literal_eval(o)
241
+ except (ValueError, SyntaxError):
242
+ o = {}
243
+ out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
244
+ reason=e.get("reason") or ""))
245
+ return sorted(out, key=lambda x: x["attempt"])
246
+
247
+ def condition(self):
248
+ s, en = self.start, self.entry
249
+ mem = s.get("memory", en.get("mem"))
250
+ chain = en.get("chain")
251
+ if mem == "full":
252
+ cond = "with_history"
253
+ elif chain:
254
+ cond = "memory_free_retry"
255
+ else:
256
+ cond = "independent_single_attempt"
257
+ return cond, chain
258
+
259
+ def outcome_class(self):
260
+ """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
261
+ att = self.attempts()
262
+ if not att or self.start.get("memory") != "full":
263
+ return None, "".join("S" if a["success"] else "F" for a in att)
264
+ hist = "".join("S" if a["success"] else "F" for a in att)
265
+ if att[0]["success"]:
266
+ ev = error_event(att[0]["outcome"])
267
+ cls = "S?" if ev is None else ("IR" if ev else "CS")
268
+ else:
269
+ cls = "XR" if any(a["success"] for a in att) else "F"
270
+ return cls, hist
271
+
272
+ def agent_info(self):
273
+ h, en = self.harness, self.entry
274
+ hdr = self.headers[0] if self.headers else {}
275
+ return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
276
+ harness_version=h.get("version") or hdr.get("version"),
277
+ harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
278
+ model=h.get("model") or en.get("model") or hdr.get("model_name"),
279
+ effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
280
+ provider=h.get("provider") or en.get("provider"),
281
+ codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
282
+ jail=en.get("jail"))
283
+
284
+
285
+ # ====================================================================================================== recording
286
+
287
+ class EpisodeSink:
288
+ """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
289
+
290
+ def __init__(self, path):
291
+ self.path = path
292
+ os.makedirs(path, exist_ok=True)
293
+ self.w = None
294
+ self.num = defaultdict(list)
295
+ self.n = 0
296
+
297
+ def add(self, st, imgs):
298
+ import imageio
299
+ if self.w is None:
300
+ self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
301
+ pixelformat="rgb24", macro_block_size=1,
302
+ ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
303
+ for k in ("agentview", "wrist")]
304
+ for w, im in zip(self.w, imgs):
305
+ w.append_data(im)
306
+ for k, v in st.items():
307
+ self.num[k].append(v)
308
+ self.n += 1
309
+
310
+ def close(self, final_state, final_imgs):
311
+ from PIL import Image
312
+ if self.w is not None:
313
+ for w in self.w:
314
+ w.close()
315
+ arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
316
+ np.savez(os.path.join(self.path, "frames.npz"), **arr)
317
+ if self.num.get("sim_state"):
318
+ np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
319
+ np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
320
+ for k, im in zip(("agentview", "wrist"), final_imgs):
321
+ Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
322
+
323
+
324
+ class Recorder:
325
+ """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
326
+
327
+ def __init__(self, rp, res):
328
+ self.rp, self.res = rp, int(res)
329
+ self.active = False
330
+ self.sink = None
331
+ self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
332
+ env = rp.task.env
333
+ self.env, self.rob = env, env.robots[0]
334
+ self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
335
+ orig = env.step
336
+
337
+ def step(a):
338
+ if self.active and self.sink is not None:
339
+ self.capture(np.asarray(a, np.float64))
340
+ out = orig(a)
341
+ if self.active and self.sink is not None:
342
+ self.rp.poll_events(self.sink.n - 1)
343
+ return out
344
+
345
+ env.step = step
346
+
347
+ @property
348
+ def n(self):
349
+ return self.sink.n if self.sink is not None else 0
350
+
351
+ def state(self):
352
+ import robosuite.utils.transform_utils as T
353
+ env, rob = self.env, self.rob
354
+ d = env.sim.data
355
+ eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
356
+ q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
357
+ gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
358
+ try:
359
+ flat = np.asarray(env.sim.get_state().flatten(), np.float64)
360
+ except Exception:
361
+ flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
362
+ sk = self.rp.task.sk
363
+ return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
364
+ gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
365
+ joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
366
+ gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
367
+ eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
368
+ sim_time=np.float64(d.time), sim_state=flat)
369
+
370
+ def images(self):
371
+ return [envs.render(self.env, c, self.res) for c in self.cams]
372
+
373
+ def capture(self, a):
374
+ st = self.state()
375
+ st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
376
+ phase=np.int64(self.cur["phase"]))
377
+ self.sink.add(st, self.images())
378
+
379
+
380
+ class RunReplay:
381
+ def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
382
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
383
+ self.run_name = os.path.basename(self.run_dir)
384
+ self.log = RunLog(self.run_dir, manifest)
385
+ self.ev = self.log.ev
386
+ self.start = self.log.start
387
+ cp = os.path.join(self.run_dir, "contract.json")
388
+ self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
389
+ spec = self.contract.get("image_spec") or {}
390
+ self.image_res = int(spec.get("width", 512))
391
+ self.code_diff = check_code(self.run_dir)
392
+ s = self.start
393
+ self.task = TASKS[s["task"]](cam_res=self.image_res)
394
+ inst = self.task.sample_instance(s["seed"])
395
+ logged = s.get("inst") or {}
396
+ sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
397
+ self.inst_diff = diff_json(sampled, logged, "inst")
398
+ if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
399
+ inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
400
+ self.inst_diff = []
401
+ self.inst = inst
402
+ self.protocol = getattr(self.task, "protocol", "cross")
403
+ self.k = int(s.get("k") or self.task.max_attempts)
404
+ self.attempt = 1
405
+ self.mismatch = [] # (where, what, logged, replayed)
406
+ self.n_checked = 0
407
+ self.max_dev_m = 0.0
408
+ self.unfinished = None
409
+ self.rec = Recorder(self, res) if record else None
410
+ self.res = int(res)
411
+ self.out_root = out_root
412
+ self.n_mon = 0
413
+ self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
414
+ self.episodes = [] # summaries of the written episodes
415
+ self.task.reset_instance(self.inst)
416
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
417
+ sim = self.task.env.sim
418
+ bid = sim.model.body_name2id("robot0_base")
419
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
420
+ if self.rec:
421
+ self._open_episode()
422
+
423
+ # ------------------------------------------------------------------ episodes
424
+ def _ep_dir(self):
425
+ return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
426
+
427
+ def _open_episode(self):
428
+ self.rec.sink = EpisodeSink(self._ep_dir())
429
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
430
+ self.rec.active = True
431
+ self.events, self.spans, self.ep_attempts = [], [], []
432
+ self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
433
+
434
+ def close_episode(self):
435
+ if not self.rec:
436
+ self.ep_attempts = []
437
+ return
438
+ sink = self.rec.sink
439
+ st = self.rec.state()
440
+ imgs = self.rec.images()
441
+ st.pop("sim_state", None)
442
+ sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
443
+ ann = build_annotation(self, sink)
444
+ with open(os.path.join(sink.path, "annotation.json"), "w") as f:
445
+ json.dump(ann, f, indent=1, default=_json_default)
446
+ self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
447
+ attempts=[a["attempt"] for a in self.ep_attempts]))
448
+ self.rec.active = False
449
+ self.rec.sink = None
450
+ self.ep_index += 1
451
+
452
+ # ------------------------------------------------------------------ monitor events (task-side error events)
453
+ def poll_events(self, frame):
454
+ mon = getattr(self.task, "mon", None)
455
+ evs = mon.get("events") if isinstance(mon, dict) else None
456
+ if not isinstance(evs, list):
457
+ return
458
+ if len(evs) < self.n_mon: # monitor was rebuilt
459
+ self.n_mon = 0
460
+ for e in evs[self.n_mon:]:
461
+ self.events.append(dict(frame=int(frame), attempt=self.attempt,
462
+ event=norm_json(e) if isinstance(e, dict) else str(e)))
463
+ self.n_mon = len(evs)
464
+
465
+ # ------------------------------------------------------------------ state as the server reports it
466
+ def proprio_la(self):
467
+ p = self.ex.proprio()
468
+ pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
469
+ return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
470
+
471
+ def compare(self, where, rep_logged, rep):
472
+ self.n_checked += 1
473
+ for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
474
+ if k not in rep_logged or k not in rep:
475
+ continue
476
+ a, b = rep_logged[k], rep[k]
477
+ if k == "eef_pos":
478
+ dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
479
+ self.max_dev_m = max(self.max_dev_m, dev)
480
+ if dev > 1.5e-4:
481
+ self.mismatch.append((where, k, a, b))
482
+ elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
483
+ self.mismatch.append((where, k, a, b))
484
+ if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
485
+ self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
486
+
487
+ def _span(self, e, f0, kind):
488
+ if self.rec:
489
+ self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
490
+ frame_end=self.rec.n))
491
+
492
+ # ------------------------------------------------------------------ commands (robot_server._handle_v2)
493
+ def move_eef(self, e):
494
+ args = e.get("args") or {}
495
+ where = f"a{e['attempt']}s{e['step']}"
496
+ logged = e.get("report") or {}
497
+ f0 = self.rec.n if self.rec else 0
498
+ p = self.ex.proprio()
499
+ if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
500
+ self._span(e, f0, "error")
501
+ return self.compare(where, logged, dict(ok=False))
502
+ off = self.base_off
503
+ try:
504
+ cur = np.asarray(p["eef_pos"], float) - off
505
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
506
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
507
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
508
+ except (TypeError, ValueError):
509
+ self._span(e, f0, "error")
510
+ return self.compare(where, logged, dict(ok=False))
511
+ grip = args.get("gripper")
512
+ if grip not in (None, "open", "close"):
513
+ self._span(e, f0, "error")
514
+ return self.compare(where, logged, dict(ok=False))
515
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
516
+ tgt_w = np.asarray(tgt) + off
517
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
518
+ self._span(e, f0, "rejected")
519
+ return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
520
+ raw = {}
521
+ if self.rec:
522
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
523
+ if moving:
524
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
525
+ if speed is not None:
526
+ mv["speed"] = speed
527
+ raw.update(self.ex.call("move_to", mv).report)
528
+ if grip is not None:
529
+ if self.rec:
530
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
531
+ raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
532
+ rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
533
+ self.compare(where, logged, rep)
534
+ lr = e.get("raw") or {}
535
+ for k in ("holding_object", "touched_object"):
536
+ if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
537
+ self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
538
+ self._span(e, f0, "move_eef")
539
+
540
+ def observe(self, e):
541
+ f0 = self.rec.n if self.rec else 0
542
+ self._span(e, f0, "observe")
543
+
544
+ def done(self, e):
545
+ f0 = self.rec.n if self.rec else 0
546
+ if self.rec:
547
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
548
+ out = self.task.outcome(self.inst)
549
+ succ = bool(out["success"])
550
+ where = f"a{e['attempt']}done"
551
+ if succ != bool(e.get("success") in (True, "True")):
552
+ self.mismatch.append((where, "success", e.get("success"), succ))
553
+ lo = e.get("outcome") or {}
554
+ ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
555
+ if isinstance(lo, dict):
556
+ for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
557
+ self.mismatch.append((where,) + d)
558
+ info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
559
+ feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
560
+ think_s=e.get("think_s"))
561
+ try:
562
+ info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
563
+ except Exception as ex_:
564
+ info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
565
+ if self.rec:
566
+ info["judge_frames"] = [f0, self.rec.n]
567
+ self.ep_attempts.append(info)
568
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
569
+ if self.protocol == "cross" or last:
570
+ self.close_episode()
571
+ if last:
572
+ return True
573
+ self.attempt += 1
574
+ if self.protocol == "cross":
575
+ self.task.reset_instance(self.inst)
576
+ self.n_mon = 0
577
+ if self.rec:
578
+ self._open_episode()
579
+ elif self.rec:
580
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
581
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
582
+ return False
583
+
584
+ def run(self):
585
+ t0 = time.time()
586
+ finished = False
587
+ for e in self.ev:
588
+ if e["ev"] == "call":
589
+ if e.get("cmd") == "move_eef":
590
+ self.move_eef(e)
591
+ elif e.get("cmd") == "observe":
592
+ self.observe(e)
593
+ else:
594
+ self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
595
+ elif e["ev"] == "done":
596
+ finished = self.done(e)
597
+ if finished:
598
+ break
599
+ self.unfinished = not finished
600
+ if not finished and self.rec and self.rec.sink is not None:
601
+ # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
602
+ if self.rec.n or self.ep_attempts:
603
+ self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
604
+ finish_reason="", feedback_shown="", auto_ended=False))
605
+ self.close_episode()
606
+ else:
607
+ shutil.rmtree(self.rec.sink.path, ignore_errors=True)
608
+ self.rec.sink = None
609
+ self.wall_s = time.time() - t0
610
+ return self
611
+
612
+ def summary(self):
613
+ return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
614
+ protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
615
+ n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
616
+ unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
617
+ first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
618
+
619
+
620
+ # ====================================================================================================== annotation
621
+
622
+ def task_info(task, inst):
623
+ cls = type(task)
624
+ return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
625
+ category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
626
+ max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
627
+ instruction=cls.instruction)
628
+
629
+
630
+ def build_annotation(rp, sink):
631
+ """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
632
+ failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
633
+ task-side error events with frame indices."""
634
+ log = rp.log
635
+ s = rp.start
636
+ cond, chain = log.condition()
637
+ cls, hist = log.outcome_class()
638
+ att_all = log.attempts()
639
+ attempts = []
640
+ for a in rp.ep_attempts:
641
+ a = dict(a)
642
+ n = a["attempt"]
643
+ later = [x for x in att_all if x["attempt"] > n]
644
+ a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
645
+ a["is_last_attempt_of_run"] = not later
646
+ fn = log.finish_notes.get(n)
647
+ if fn:
648
+ a["agent_finish"] = fn
649
+ a["error_event_in_attempt"] = error_event(a.get("outcome"))
650
+ attempts.append(a)
651
+ # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
652
+ for a in attempts:
653
+ nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
654
+ if a.get("success") is False and nxt:
655
+ note = log.notes[nxt[0]]
656
+ a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
657
+ commands = []
658
+ for sp in rp.spans:
659
+ e = log.calls.get((sp["attempt"], sp["step"])) or {}
660
+ rep = e.get("report") or {}
661
+ c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
662
+ frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
663
+ args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
664
+ stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
665
+ gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
666
+ touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
667
+ agent_obs_images=rep.get("images"))
668
+ note = log.notes.get((sp["attempt"], sp["step"]))
669
+ if note:
670
+ c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
671
+ commands.append(c)
672
+ t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
673
+ return dict(
674
+ schema=SCHEMA,
675
+ source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
676
+ episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
677
+ memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
678
+ feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
679
+ k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
680
+ contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
681
+ if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
682
+ agent=log.agent_info(),
683
+ task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
684
+ instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
685
+ run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
686
+ run_success=any(x["success"] for x in att_all) if att_all else None,
687
+ agent_final_report=log.final_report[:6000] or None,
688
+ mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
689
+ attempts=attempts,
690
+ commands=commands,
691
+ task_events=rp.events,
692
+ frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
693
+ phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
694
+ joint_pos=rp.ep_initial["joint_pos"],
695
+ gripper_qpos=rp.ep_initial["gripper_qpos"])),
696
+ )
697
+
698
+
699
+ # ====================================================================================================== CLI
700
+
701
+ def load_manifest(run_dir):
702
+ p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
703
+ return json.load(open(p)) if os.path.exists(p) else {}
704
+
705
+
706
+ def main():
707
+ ap = argparse.ArgumentParser()
708
+ ap.add_argument("mode", choices=["check", "record"])
709
+ ap.add_argument("runs", nargs="+")
710
+ ap.add_argument("--json", default="")
711
+ ap.add_argument("--out", default="")
712
+ ap.add_argument("--res", type=int, default=256)
713
+ ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
714
+ a = ap.parse_args()
715
+ rows = []
716
+ for r in a.runs:
717
+ r = r.rstrip("/")
718
+ try:
719
+ if a.mode == "check":
720
+ s = RunReplay(r, manifest=load_manifest(r)).run().summary()
721
+ else:
722
+ batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
723
+ rd = os.path.join(a.out, batch, name)
724
+ if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
725
+ print(json.dumps(dict(run=name, skipped="exists")), flush=True)
726
+ continue
727
+ shutil.rmtree(rd, ignore_errors=True)
728
+ rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
729
+ s = rp.summary()
730
+ s["episodes"] = rp.episodes
731
+ with open(os.path.join(rd, "replay.json"), "w") as f:
732
+ json.dump(s, f, indent=1)
733
+ except Exception:
734
+ import traceback
735
+ s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
736
+ rows.append(s)
737
+ print(json.dumps(s), flush=True)
738
+ if a.json:
739
+ with open(a.json, "w") as f:
740
+ json.dump(rows, f, indent=1)
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
leaf/code/v1.5/backfill-20261102-lf1_opus_r2/lerobot_replay.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
2
+ against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
3
+ LeRobot export (scripts/lerobot_export.py).
4
+
5
+ python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
6
+ python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
7
+
8
+ Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
9
+ commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
10
+ is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
11
+ like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
12
+ outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
13
+ ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
14
+ hashes equal the current files are expected to match (check_code()).
15
+
16
+ Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
17
+ proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
18
+ protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
19
+ per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
20
+ fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
21
+ agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
22
+ frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
23
+ sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
24
+ final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
25
+ annotation.json episode annotation (build_annotation)
26
+ and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
27
+ """
28
+ import argparse
29
+ import ast
30
+ import hashlib
31
+ import importlib
32
+ import json
33
+ import math
34
+ import os
35
+ import pkgutil
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections import defaultdict
41
+
42
+ import numpy as np
43
+
44
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
45
+ sys.path.insert(0, LFF_ROOT)
46
+
47
+ from lffbench import envs # noqa: E402
48
+ from lffbench import tasks as task_pkg # noqa: E402
49
+ from lffbench.agent import camera as C # noqa: E402
50
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
51
+ from lffbench.task_base import TASKS # noqa: E402
52
+
53
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
54
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
55
+
56
+ # per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
57
+ # task's outcome() check after `finish` (the arm holds still; not an agent action)
58
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
59
+ FPS = 20
60
+ SCHEMA = "lff-replay-1"
61
+
62
+ # error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
63
+ ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
64
+ ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
65
+ "n_missed_strikes", "n_open_gripper_pushes")
66
+
67
+
68
+ def load_jsonl(p):
69
+ out = []
70
+ if not os.path.exists(p):
71
+ return out
72
+ with open(p) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if line:
76
+ try:
77
+ out.append(json.loads(line))
78
+ except ValueError:
79
+ pass
80
+ return out
81
+
82
+
83
+ def norm_json(o):
84
+ return json.loads(json.dumps(o, default=_json_default))
85
+
86
+
87
+ def sha256(p):
88
+ with open(p, "rb") as f:
89
+ return hashlib.sha256(f.read()).hexdigest()
90
+
91
+
92
+ def check_code(run_dir):
93
+ """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
94
+ p = os.path.join(run_dir, "contract.json")
95
+ if not os.path.exists(p):
96
+ return [("contract.json", None, None)]
97
+ files = json.load(open(p))["contract"].get("server_code_files", {})
98
+ bad = []
99
+ for f, h in files.items():
100
+ q = os.path.join(LFF_ROOT, f)
101
+ cur = sha256(q) if os.path.exists(q) else None
102
+ if cur != h:
103
+ bad.append((f, h, cur))
104
+ return bad
105
+
106
+
107
+ def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
108
+ """Differences between two JSON values (numbers compared with an absolute tolerance)."""
109
+ out = [] if out is None else out
110
+ if len(out) >= limit:
111
+ return out
112
+ if isinstance(a, dict) and isinstance(b, dict):
113
+ for k in sorted(set(a) | set(b)):
114
+ if k not in a or k not in b:
115
+ out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
116
+ else:
117
+ diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
118
+ elif isinstance(a, list) and isinstance(b, list):
119
+ if len(a) != len(b):
120
+ out.append((path, f"len {len(a)}", f"len {len(b)}"))
121
+ else:
122
+ for i, (x, y) in enumerate(zip(a, b)):
123
+ diff_json(x, y, f"{path}[{i}]", tol, out, limit)
124
+ elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
125
+ if a != b:
126
+ out.append((path, a, b))
127
+ elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
128
+ out.append((path, a, b))
129
+ return out
130
+
131
+
132
+ def error_event(o):
133
+ """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
134
+ if not isinstance(o, dict):
135
+ return None
136
+ keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
137
+ if not keys:
138
+ return None
139
+ return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
140
+
141
+
142
+ # ====================================================================================================== logs -> notes
143
+
144
+ class RunLog:
145
+ """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
146
+ narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
147
+
148
+ def __init__(self, run_dir, manifest=None):
149
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
150
+ self.run = os.path.basename(self.run_dir)
151
+ self.batch = os.path.basename(os.path.dirname(self.run_dir))
152
+ self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
153
+ self.start = next(e for e in self.ev if e["ev"] == "session_start")
154
+ self.calls, self.dones, self.harness_status = {}, [], []
155
+ last = None
156
+ for e in self.ev:
157
+ if e["ev"] == "call":
158
+ self.calls[(int(e["attempt"]), int(e["step"]))] = e
159
+ last = e
160
+ elif e["ev"] == "done":
161
+ self.dones.append(e)
162
+ last = e
163
+ elif e["ev"] == "http" and last is not None and "think_s" not in last:
164
+ ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
165
+ (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
166
+ if ok:
167
+ last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
168
+ self.manifest = manifest or {}
169
+ self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
170
+ p = os.path.join(self.run_dir, "harness.json")
171
+ self.harness = json.load(open(p)) if os.path.exists(p) else {}
172
+ self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
173
+ self._narration()
174
+
175
+ # ---------------------------------------------------------------- agent narration
176
+ def _narration(self):
177
+ """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
178
+ finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
179
+ self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
180
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
181
+ attempt = 1
182
+
183
+ def take():
184
+ nonlocal buf
185
+ out = {k: v for k, v in buf.items() if v}
186
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
187
+ return out
188
+
189
+ last_msg = ""
190
+ for t in self.traj:
191
+ if t.get("kind") == "header":
192
+ self.headers.append(t.get("agent") or {})
193
+ continue
194
+ if t.get("kind") != "step":
195
+ continue
196
+ if (t.get("message") or "").strip():
197
+ buf["messages"].append(t["message"].strip())
198
+ last_msg = t["message"].strip()
199
+ if (t.get("reasoning_content") or "").strip():
200
+ buf["reasoning"].append(t["reasoning_content"].strip())
201
+ res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
202
+ for c in t.get("tool_calls") or []:
203
+ fn, args = c.get("function_name"), c.get("arguments") or {}
204
+ if fn == "shell":
205
+ buf["shell"].append(str(args.get("command", ""))[:2000])
206
+ elif fn == "view_images":
207
+ buf["viewed"].extend(args.get("paths") or [])
208
+ elif fn == "robot":
209
+ cmd = str(args.get("command", "")).strip()
210
+ r = res.get(c.get("tool_call_id")) or {}
211
+ try:
212
+ rep = json.loads(r.get("content") or "{}")
213
+ except ValueError:
214
+ rep = {}
215
+ word = cmd.split()[0] if cmd else ""
216
+ m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
217
+ if word in ("move_eef", "observe") and m:
218
+ a, s = int(m.group(1)), int(m.group(2))
219
+ n = take()
220
+ n["command"] = cmd
221
+ self.notes[(a, s)] = n
222
+ attempt = a
223
+ elif word in ("finish", "done"):
224
+ n = take()
225
+ n["command"] = cmd
226
+ n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
227
+ self.finish_notes.setdefault(attempt, n)
228
+ if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
229
+ attempt += 1
230
+ # status / help / errors: their narration stays in the buffer for the next command
231
+ self.final_report = last_msg
232
+
233
+ # ---------------------------------------------------------------- run-level labels
234
+ def attempts(self):
235
+ out = []
236
+ for e in self.dones:
237
+ o = e.get("outcome") or {}
238
+ if isinstance(o, str):
239
+ try:
240
+ o = ast.literal_eval(o)
241
+ except (ValueError, SyntaxError):
242
+ o = {}
243
+ out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
244
+ reason=e.get("reason") or ""))
245
+ return sorted(out, key=lambda x: x["attempt"])
246
+
247
+ def condition(self):
248
+ s, en = self.start, self.entry
249
+ mem = s.get("memory", en.get("mem"))
250
+ chain = en.get("chain")
251
+ if mem == "full":
252
+ cond = "with_history"
253
+ elif chain:
254
+ cond = "memory_free_retry"
255
+ else:
256
+ cond = "independent_single_attempt"
257
+ return cond, chain
258
+
259
+ def outcome_class(self):
260
+ """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
261
+ att = self.attempts()
262
+ if not att or self.start.get("memory") != "full":
263
+ return None, "".join("S" if a["success"] else "F" for a in att)
264
+ hist = "".join("S" if a["success"] else "F" for a in att)
265
+ if att[0]["success"]:
266
+ ev = error_event(att[0]["outcome"])
267
+ cls = "S?" if ev is None else ("IR" if ev else "CS")
268
+ else:
269
+ cls = "XR" if any(a["success"] for a in att) else "F"
270
+ return cls, hist
271
+
272
+ def agent_info(self):
273
+ h, en = self.harness, self.entry
274
+ hdr = self.headers[0] if self.headers else {}
275
+ return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
276
+ harness_version=h.get("version") or hdr.get("version"),
277
+ harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
278
+ model=h.get("model") or en.get("model") or hdr.get("model_name"),
279
+ effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
280
+ provider=h.get("provider") or en.get("provider"),
281
+ codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
282
+ jail=en.get("jail"))
283
+
284
+
285
+ # ====================================================================================================== recording
286
+
287
+ class EpisodeSink:
288
+ """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
289
+
290
+ def __init__(self, path):
291
+ self.path = path
292
+ os.makedirs(path, exist_ok=True)
293
+ self.w = None
294
+ self.num = defaultdict(list)
295
+ self.n = 0
296
+
297
+ def add(self, st, imgs):
298
+ import imageio
299
+ if self.w is None:
300
+ self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
301
+ pixelformat="rgb24", macro_block_size=1,
302
+ ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
303
+ for k in ("agentview", "wrist")]
304
+ for w, im in zip(self.w, imgs):
305
+ w.append_data(im)
306
+ for k, v in st.items():
307
+ self.num[k].append(v)
308
+ self.n += 1
309
+
310
+ def close(self, final_state, final_imgs):
311
+ from PIL import Image
312
+ if self.w is not None:
313
+ for w in self.w:
314
+ w.close()
315
+ arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
316
+ np.savez(os.path.join(self.path, "frames.npz"), **arr)
317
+ if self.num.get("sim_state"):
318
+ np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
319
+ np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
320
+ for k, im in zip(("agentview", "wrist"), final_imgs):
321
+ Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
322
+
323
+
324
+ class Recorder:
325
+ """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
326
+
327
+ def __init__(self, rp, res):
328
+ self.rp, self.res = rp, int(res)
329
+ self.active = False
330
+ self.sink = None
331
+ self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
332
+ env = rp.task.env
333
+ self.env, self.rob = env, env.robots[0]
334
+ self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
335
+ orig = env.step
336
+
337
+ def step(a):
338
+ if self.active and self.sink is not None:
339
+ self.capture(np.asarray(a, np.float64))
340
+ out = orig(a)
341
+ if self.active and self.sink is not None:
342
+ self.rp.poll_events(self.sink.n - 1)
343
+ return out
344
+
345
+ env.step = step
346
+
347
+ @property
348
+ def n(self):
349
+ return self.sink.n if self.sink is not None else 0
350
+
351
+ def state(self):
352
+ import robosuite.utils.transform_utils as T
353
+ env, rob = self.env, self.rob
354
+ d = env.sim.data
355
+ eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
356
+ q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
357
+ gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
358
+ try:
359
+ flat = np.asarray(env.sim.get_state().flatten(), np.float64)
360
+ except Exception:
361
+ flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
362
+ sk = self.rp.task.sk
363
+ return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
364
+ gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
365
+ joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
366
+ gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
367
+ eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
368
+ sim_time=np.float64(d.time), sim_state=flat)
369
+
370
+ def images(self):
371
+ return [envs.render(self.env, c, self.res) for c in self.cams]
372
+
373
+ def capture(self, a):
374
+ st = self.state()
375
+ st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
376
+ phase=np.int64(self.cur["phase"]))
377
+ self.sink.add(st, self.images())
378
+
379
+
380
+ class RunReplay:
381
+ def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
382
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
383
+ self.run_name = os.path.basename(self.run_dir)
384
+ self.log = RunLog(self.run_dir, manifest)
385
+ self.ev = self.log.ev
386
+ self.start = self.log.start
387
+ cp = os.path.join(self.run_dir, "contract.json")
388
+ self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
389
+ spec = self.contract.get("image_spec") or {}
390
+ self.image_res = int(spec.get("width", 512))
391
+ self.code_diff = check_code(self.run_dir)
392
+ s = self.start
393
+ self.task = TASKS[s["task"]](cam_res=self.image_res)
394
+ inst = self.task.sample_instance(s["seed"])
395
+ logged = s.get("inst") or {}
396
+ sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
397
+ self.inst_diff = diff_json(sampled, logged, "inst")
398
+ if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
399
+ inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
400
+ self.inst_diff = []
401
+ self.inst = inst
402
+ self.protocol = getattr(self.task, "protocol", "cross")
403
+ self.k = int(s.get("k") or self.task.max_attempts)
404
+ self.attempt = 1
405
+ self.mismatch = [] # (where, what, logged, replayed)
406
+ self.n_checked = 0
407
+ self.max_dev_m = 0.0
408
+ self.unfinished = None
409
+ self.rec = Recorder(self, res) if record else None
410
+ self.res = int(res)
411
+ self.out_root = out_root
412
+ self.n_mon = 0
413
+ self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
414
+ self.episodes = [] # summaries of the written episodes
415
+ self.task.reset_instance(self.inst)
416
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
417
+ sim = self.task.env.sim
418
+ bid = sim.model.body_name2id("robot0_base")
419
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
420
+ if self.rec:
421
+ self._open_episode()
422
+
423
+ # ------------------------------------------------------------------ episodes
424
+ def _ep_dir(self):
425
+ return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
426
+
427
+ def _open_episode(self):
428
+ self.rec.sink = EpisodeSink(self._ep_dir())
429
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
430
+ self.rec.active = True
431
+ self.events, self.spans, self.ep_attempts = [], [], []
432
+ self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
433
+
434
+ def close_episode(self):
435
+ if not self.rec:
436
+ self.ep_attempts = []
437
+ return
438
+ sink = self.rec.sink
439
+ st = self.rec.state()
440
+ imgs = self.rec.images()
441
+ st.pop("sim_state", None)
442
+ sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
443
+ ann = build_annotation(self, sink)
444
+ with open(os.path.join(sink.path, "annotation.json"), "w") as f:
445
+ json.dump(ann, f, indent=1, default=_json_default)
446
+ self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
447
+ attempts=[a["attempt"] for a in self.ep_attempts]))
448
+ self.rec.active = False
449
+ self.rec.sink = None
450
+ self.ep_index += 1
451
+
452
+ # ------------------------------------------------------------------ monitor events (task-side error events)
453
+ def poll_events(self, frame):
454
+ mon = getattr(self.task, "mon", None)
455
+ evs = mon.get("events") if isinstance(mon, dict) else None
456
+ if not isinstance(evs, list):
457
+ return
458
+ if len(evs) < self.n_mon: # monitor was rebuilt
459
+ self.n_mon = 0
460
+ for e in evs[self.n_mon:]:
461
+ self.events.append(dict(frame=int(frame), attempt=self.attempt,
462
+ event=norm_json(e) if isinstance(e, dict) else str(e)))
463
+ self.n_mon = len(evs)
464
+
465
+ # ------------------------------------------------------------------ state as the server reports it
466
+ def proprio_la(self):
467
+ p = self.ex.proprio()
468
+ pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
469
+ return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
470
+
471
+ def compare(self, where, rep_logged, rep):
472
+ self.n_checked += 1
473
+ for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
474
+ if k not in rep_logged or k not in rep:
475
+ continue
476
+ a, b = rep_logged[k], rep[k]
477
+ if k == "eef_pos":
478
+ dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
479
+ self.max_dev_m = max(self.max_dev_m, dev)
480
+ if dev > 1.5e-4:
481
+ self.mismatch.append((where, k, a, b))
482
+ elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
483
+ self.mismatch.append((where, k, a, b))
484
+ if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
485
+ self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
486
+
487
+ def _span(self, e, f0, kind):
488
+ if self.rec:
489
+ self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
490
+ frame_end=self.rec.n))
491
+
492
+ # ------------------------------------------------------------------ commands (robot_server._handle_v2)
493
+ def move_eef(self, e):
494
+ args = e.get("args") or {}
495
+ where = f"a{e['attempt']}s{e['step']}"
496
+ logged = e.get("report") or {}
497
+ f0 = self.rec.n if self.rec else 0
498
+ p = self.ex.proprio()
499
+ if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
500
+ self._span(e, f0, "error")
501
+ return self.compare(where, logged, dict(ok=False))
502
+ off = self.base_off
503
+ try:
504
+ cur = np.asarray(p["eef_pos"], float) - off
505
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
506
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
507
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
508
+ except (TypeError, ValueError):
509
+ self._span(e, f0, "error")
510
+ return self.compare(where, logged, dict(ok=False))
511
+ grip = args.get("gripper")
512
+ if grip not in (None, "open", "close"):
513
+ self._span(e, f0, "error")
514
+ return self.compare(where, logged, dict(ok=False))
515
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
516
+ tgt_w = np.asarray(tgt) + off
517
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
518
+ self._span(e, f0, "rejected")
519
+ return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
520
+ raw = {}
521
+ if self.rec:
522
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
523
+ if moving:
524
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
525
+ if speed is not None:
526
+ mv["speed"] = speed
527
+ raw.update(self.ex.call("move_to", mv).report)
528
+ if grip is not None:
529
+ if self.rec:
530
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
531
+ raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
532
+ rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
533
+ self.compare(where, logged, rep)
534
+ lr = e.get("raw") or {}
535
+ for k in ("holding_object", "touched_object"):
536
+ if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
537
+ self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
538
+ self._span(e, f0, "move_eef")
539
+
540
+ def observe(self, e):
541
+ f0 = self.rec.n if self.rec else 0
542
+ self._span(e, f0, "observe")
543
+
544
+ def done(self, e):
545
+ f0 = self.rec.n if self.rec else 0
546
+ if self.rec:
547
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
548
+ out = self.task.outcome(self.inst)
549
+ succ = bool(out["success"])
550
+ where = f"a{e['attempt']}done"
551
+ if succ != bool(e.get("success") in (True, "True")):
552
+ self.mismatch.append((where, "success", e.get("success"), succ))
553
+ lo = e.get("outcome") or {}
554
+ ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
555
+ if isinstance(lo, dict):
556
+ for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
557
+ self.mismatch.append((where,) + d)
558
+ info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
559
+ feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
560
+ think_s=e.get("think_s"))
561
+ try:
562
+ info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
563
+ except Exception as ex_:
564
+ info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
565
+ if self.rec:
566
+ info["judge_frames"] = [f0, self.rec.n]
567
+ self.ep_attempts.append(info)
568
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
569
+ if self.protocol == "cross" or last:
570
+ self.close_episode()
571
+ if last:
572
+ return True
573
+ self.attempt += 1
574
+ if self.protocol == "cross":
575
+ self.task.reset_instance(self.inst)
576
+ self.n_mon = 0
577
+ if self.rec:
578
+ self._open_episode()
579
+ elif self.rec:
580
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
581
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
582
+ return False
583
+
584
+ def run(self):
585
+ t0 = time.time()
586
+ finished = False
587
+ for e in self.ev:
588
+ if e["ev"] == "call":
589
+ if e.get("cmd") == "move_eef":
590
+ self.move_eef(e)
591
+ elif e.get("cmd") == "observe":
592
+ self.observe(e)
593
+ else:
594
+ self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
595
+ elif e["ev"] == "done":
596
+ finished = self.done(e)
597
+ if finished:
598
+ break
599
+ self.unfinished = not finished
600
+ if not finished and self.rec and self.rec.sink is not None:
601
+ # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
602
+ if self.rec.n or self.ep_attempts:
603
+ self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
604
+ finish_reason="", feedback_shown="", auto_ended=False))
605
+ self.close_episode()
606
+ else:
607
+ shutil.rmtree(self.rec.sink.path, ignore_errors=True)
608
+ self.rec.sink = None
609
+ self.wall_s = time.time() - t0
610
+ return self
611
+
612
+ def summary(self):
613
+ return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
614
+ protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
615
+ n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
616
+ unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
617
+ first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
618
+
619
+
620
+ # ====================================================================================================== annotation
621
+
622
+ def task_info(task, inst):
623
+ cls = type(task)
624
+ return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
625
+ category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
626
+ max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
627
+ instruction=cls.instruction)
628
+
629
+
630
+ def build_annotation(rp, sink):
631
+ """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
632
+ failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
633
+ task-side error events with frame indices."""
634
+ log = rp.log
635
+ s = rp.start
636
+ cond, chain = log.condition()
637
+ cls, hist = log.outcome_class()
638
+ att_all = log.attempts()
639
+ attempts = []
640
+ for a in rp.ep_attempts:
641
+ a = dict(a)
642
+ n = a["attempt"]
643
+ later = [x for x in att_all if x["attempt"] > n]
644
+ a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
645
+ a["is_last_attempt_of_run"] = not later
646
+ fn = log.finish_notes.get(n)
647
+ if fn:
648
+ a["agent_finish"] = fn
649
+ a["error_event_in_attempt"] = error_event(a.get("outcome"))
650
+ attempts.append(a)
651
+ # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
652
+ for a in attempts:
653
+ nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
654
+ if a.get("success") is False and nxt:
655
+ note = log.notes[nxt[0]]
656
+ a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
657
+ commands = []
658
+ for sp in rp.spans:
659
+ e = log.calls.get((sp["attempt"], sp["step"])) or {}
660
+ rep = e.get("report") or {}
661
+ c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
662
+ frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
663
+ args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
664
+ stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
665
+ gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
666
+ touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
667
+ agent_obs_images=rep.get("images"))
668
+ note = log.notes.get((sp["attempt"], sp["step"]))
669
+ if note:
670
+ c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
671
+ commands.append(c)
672
+ t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
673
+ return dict(
674
+ schema=SCHEMA,
675
+ source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
676
+ episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
677
+ memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
678
+ feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
679
+ k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
680
+ contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
681
+ if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
682
+ agent=log.agent_info(),
683
+ task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
684
+ instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
685
+ run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
686
+ run_success=any(x["success"] for x in att_all) if att_all else None,
687
+ agent_final_report=log.final_report[:6000] or None,
688
+ mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
689
+ attempts=attempts,
690
+ commands=commands,
691
+ task_events=rp.events,
692
+ frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
693
+ phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
694
+ joint_pos=rp.ep_initial["joint_pos"],
695
+ gripper_qpos=rp.ep_initial["gripper_qpos"])),
696
+ )
697
+
698
+
699
+ # ====================================================================================================== CLI
700
+
701
+ def load_manifest(run_dir):
702
+ p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
703
+ return json.load(open(p)) if os.path.exists(p) else {}
704
+
705
+
706
+ def main():
707
+ ap = argparse.ArgumentParser()
708
+ ap.add_argument("mode", choices=["check", "record"])
709
+ ap.add_argument("runs", nargs="+")
710
+ ap.add_argument("--json", default="")
711
+ ap.add_argument("--out", default="")
712
+ ap.add_argument("--res", type=int, default=256)
713
+ ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
714
+ a = ap.parse_args()
715
+ rows = []
716
+ for r in a.runs:
717
+ r = r.rstrip("/")
718
+ try:
719
+ if a.mode == "check":
720
+ s = RunReplay(r, manifest=load_manifest(r)).run().summary()
721
+ else:
722
+ batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
723
+ rd = os.path.join(a.out, batch, name)
724
+ if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
725
+ print(json.dumps(dict(run=name, skipped="exists")), flush=True)
726
+ continue
727
+ shutil.rmtree(rd, ignore_errors=True)
728
+ rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
729
+ s = rp.summary()
730
+ s["episodes"] = rp.episodes
731
+ with open(os.path.join(rd, "replay.json"), "w") as f:
732
+ json.dump(s, f, indent=1)
733
+ except Exception:
734
+ import traceback
735
+ s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
736
+ rows.append(s)
737
+ print(json.dumps(s), flush=True)
738
+ if a.json:
739
+ with open(a.json, "w") as f:
740
+ json.dump(rows, f, indent=1)
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
leaf/code/v1.5/backfill-20261102-lhp_gpt/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/code/v1.5/backfill-20261102-lhp_gpt/lerobot_replay.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
2
+ against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
3
+ LeRobot export (scripts/lerobot_export.py).
4
+
5
+ python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
6
+ python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
7
+
8
+ Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
9
+ commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
10
+ is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
11
+ like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
12
+ outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
13
+ ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
14
+ hashes equal the current files are expected to match (check_code()).
15
+
16
+ Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
17
+ proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
18
+ protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
19
+ per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
20
+ fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
21
+ agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
22
+ frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
23
+ sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
24
+ final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
25
+ annotation.json episode annotation (build_annotation)
26
+ and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
27
+ """
28
+ import argparse
29
+ import ast
30
+ import hashlib
31
+ import importlib
32
+ import json
33
+ import math
34
+ import os
35
+ import pkgutil
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections import defaultdict
41
+
42
+ import numpy as np
43
+
44
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
45
+ sys.path.insert(0, LFF_ROOT)
46
+
47
+ from lffbench import envs # noqa: E402
48
+ from lffbench import tasks as task_pkg # noqa: E402
49
+ from lffbench.agent import camera as C # noqa: E402
50
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
51
+ from lffbench.task_base import TASKS # noqa: E402
52
+
53
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
54
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
55
+
56
+ # per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
57
+ # task's outcome() check after `finish` (the arm holds still; not an agent action)
58
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
59
+ FPS = 20
60
+ SCHEMA = "lff-replay-1"
61
+
62
+ # error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
63
+ ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
64
+ ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
65
+ "n_missed_strikes", "n_open_gripper_pushes")
66
+
67
+
68
+ def load_jsonl(p):
69
+ out = []
70
+ if not os.path.exists(p):
71
+ return out
72
+ with open(p) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if line:
76
+ try:
77
+ out.append(json.loads(line))
78
+ except ValueError:
79
+ pass
80
+ return out
81
+
82
+
83
+ def norm_json(o):
84
+ return json.loads(json.dumps(o, default=_json_default))
85
+
86
+
87
+ def sha256(p):
88
+ with open(p, "rb") as f:
89
+ return hashlib.sha256(f.read()).hexdigest()
90
+
91
+
92
+ def check_code(run_dir):
93
+ """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
94
+ p = os.path.join(run_dir, "contract.json")
95
+ if not os.path.exists(p):
96
+ return [("contract.json", None, None)]
97
+ files = json.load(open(p))["contract"].get("server_code_files", {})
98
+ bad = []
99
+ for f, h in files.items():
100
+ q = os.path.join(LFF_ROOT, f)
101
+ cur = sha256(q) if os.path.exists(q) else None
102
+ if cur != h:
103
+ bad.append((f, h, cur))
104
+ return bad
105
+
106
+
107
+ def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
108
+ """Differences between two JSON values (numbers compared with an absolute tolerance)."""
109
+ out = [] if out is None else out
110
+ if len(out) >= limit:
111
+ return out
112
+ if isinstance(a, dict) and isinstance(b, dict):
113
+ for k in sorted(set(a) | set(b)):
114
+ if k not in a or k not in b:
115
+ out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
116
+ else:
117
+ diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
118
+ elif isinstance(a, list) and isinstance(b, list):
119
+ if len(a) != len(b):
120
+ out.append((path, f"len {len(a)}", f"len {len(b)}"))
121
+ else:
122
+ for i, (x, y) in enumerate(zip(a, b)):
123
+ diff_json(x, y, f"{path}[{i}]", tol, out, limit)
124
+ elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
125
+ if a != b:
126
+ out.append((path, a, b))
127
+ elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
128
+ out.append((path, a, b))
129
+ return out
130
+
131
+
132
+ def error_event(o):
133
+ """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
134
+ if not isinstance(o, dict):
135
+ return None
136
+ keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
137
+ if not keys:
138
+ return None
139
+ return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
140
+
141
+
142
+ # ====================================================================================================== logs -> notes
143
+
144
+ class RunLog:
145
+ """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
146
+ narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
147
+
148
+ def __init__(self, run_dir, manifest=None):
149
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
150
+ self.run = os.path.basename(self.run_dir)
151
+ self.batch = os.path.basename(os.path.dirname(self.run_dir))
152
+ self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
153
+ self.start = next(e for e in self.ev if e["ev"] == "session_start")
154
+ self.calls, self.dones, self.harness_status = {}, [], []
155
+ last = None
156
+ for e in self.ev:
157
+ if e["ev"] == "call":
158
+ self.calls[(int(e["attempt"]), int(e["step"]))] = e
159
+ last = e
160
+ elif e["ev"] == "done":
161
+ self.dones.append(e)
162
+ last = e
163
+ elif e["ev"] == "http" and last is not None and "think_s" not in last:
164
+ ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
165
+ (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
166
+ if ok:
167
+ last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
168
+ self.manifest = manifest or {}
169
+ self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
170
+ p = os.path.join(self.run_dir, "harness.json")
171
+ self.harness = json.load(open(p)) if os.path.exists(p) else {}
172
+ self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
173
+ self._narration()
174
+
175
+ # ---------------------------------------------------------------- agent narration
176
+ def _narration(self):
177
+ """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
178
+ finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
179
+ self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
180
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
181
+ attempt = 1
182
+
183
+ def take():
184
+ nonlocal buf
185
+ out = {k: v for k, v in buf.items() if v}
186
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
187
+ return out
188
+
189
+ last_msg = ""
190
+ for t in self.traj:
191
+ if t.get("kind") == "header":
192
+ self.headers.append(t.get("agent") or {})
193
+ continue
194
+ if t.get("kind") != "step":
195
+ continue
196
+ if (t.get("message") or "").strip():
197
+ buf["messages"].append(t["message"].strip())
198
+ last_msg = t["message"].strip()
199
+ if (t.get("reasoning_content") or "").strip():
200
+ buf["reasoning"].append(t["reasoning_content"].strip())
201
+ res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
202
+ for c in t.get("tool_calls") or []:
203
+ fn, args = c.get("function_name"), c.get("arguments") or {}
204
+ if fn == "shell":
205
+ buf["shell"].append(str(args.get("command", ""))[:2000])
206
+ elif fn == "view_images":
207
+ buf["viewed"].extend(args.get("paths") or [])
208
+ elif fn == "robot":
209
+ cmd = str(args.get("command", "")).strip()
210
+ r = res.get(c.get("tool_call_id")) or {}
211
+ try:
212
+ rep = json.loads(r.get("content") or "{}")
213
+ except ValueError:
214
+ rep = {}
215
+ word = cmd.split()[0] if cmd else ""
216
+ m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
217
+ if word in ("move_eef", "observe") and m:
218
+ a, s = int(m.group(1)), int(m.group(2))
219
+ n = take()
220
+ n["command"] = cmd
221
+ self.notes[(a, s)] = n
222
+ attempt = a
223
+ elif word in ("finish", "done"):
224
+ n = take()
225
+ n["command"] = cmd
226
+ n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
227
+ self.finish_notes.setdefault(attempt, n)
228
+ if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
229
+ attempt += 1
230
+ # status / help / errors: their narration stays in the buffer for the next command
231
+ self.final_report = last_msg
232
+
233
+ # ---------------------------------------------------------------- run-level labels
234
+ def attempts(self):
235
+ out = []
236
+ for e in self.dones:
237
+ o = e.get("outcome") or {}
238
+ if isinstance(o, str):
239
+ try:
240
+ o = ast.literal_eval(o)
241
+ except (ValueError, SyntaxError):
242
+ o = {}
243
+ out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
244
+ reason=e.get("reason") or ""))
245
+ return sorted(out, key=lambda x: x["attempt"])
246
+
247
+ def condition(self):
248
+ s, en = self.start, self.entry
249
+ mem = s.get("memory", en.get("mem"))
250
+ chain = en.get("chain")
251
+ if mem == "full":
252
+ cond = "with_history"
253
+ elif chain:
254
+ cond = "memory_free_retry"
255
+ else:
256
+ cond = "independent_single_attempt"
257
+ return cond, chain
258
+
259
+ def outcome_class(self):
260
+ """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
261
+ att = self.attempts()
262
+ if not att or self.start.get("memory") != "full":
263
+ return None, "".join("S" if a["success"] else "F" for a in att)
264
+ hist = "".join("S" if a["success"] else "F" for a in att)
265
+ if att[0]["success"]:
266
+ ev = error_event(att[0]["outcome"])
267
+ cls = "S?" if ev is None else ("IR" if ev else "CS")
268
+ else:
269
+ cls = "XR" if any(a["success"] for a in att) else "F"
270
+ return cls, hist
271
+
272
+ def agent_info(self):
273
+ h, en = self.harness, self.entry
274
+ hdr = self.headers[0] if self.headers else {}
275
+ return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
276
+ harness_version=h.get("version") or hdr.get("version"),
277
+ harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
278
+ model=h.get("model") or en.get("model") or hdr.get("model_name"),
279
+ effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
280
+ provider=h.get("provider") or en.get("provider"),
281
+ codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
282
+ jail=en.get("jail"))
283
+
284
+
285
+ # ====================================================================================================== recording
286
+
287
+ class EpisodeSink:
288
+ """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
289
+
290
+ def __init__(self, path):
291
+ self.path = path
292
+ os.makedirs(path, exist_ok=True)
293
+ self.w = None
294
+ self.num = defaultdict(list)
295
+ self.n = 0
296
+
297
+ def add(self, st, imgs):
298
+ import imageio
299
+ if self.w is None:
300
+ self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
301
+ pixelformat="rgb24", macro_block_size=1,
302
+ ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
303
+ for k in ("agentview", "wrist")]
304
+ for w, im in zip(self.w, imgs):
305
+ w.append_data(im)
306
+ for k, v in st.items():
307
+ self.num[k].append(v)
308
+ self.n += 1
309
+
310
+ def close(self, final_state, final_imgs):
311
+ from PIL import Image
312
+ if self.w is not None:
313
+ for w in self.w:
314
+ w.close()
315
+ arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
316
+ np.savez(os.path.join(self.path, "frames.npz"), **arr)
317
+ if self.num.get("sim_state"):
318
+ np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
319
+ np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
320
+ for k, im in zip(("agentview", "wrist"), final_imgs):
321
+ Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
322
+
323
+
324
+ class Recorder:
325
+ """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
326
+
327
+ def __init__(self, rp, res):
328
+ self.rp, self.res = rp, int(res)
329
+ self.active = False
330
+ self.sink = None
331
+ self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
332
+ env = rp.task.env
333
+ self.env, self.rob = env, env.robots[0]
334
+ self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
335
+ orig = env.step
336
+
337
+ def step(a):
338
+ if self.active and self.sink is not None:
339
+ self.capture(np.asarray(a, np.float64))
340
+ out = orig(a)
341
+ if self.active and self.sink is not None:
342
+ self.rp.poll_events(self.sink.n - 1)
343
+ return out
344
+
345
+ env.step = step
346
+
347
+ @property
348
+ def n(self):
349
+ return self.sink.n if self.sink is not None else 0
350
+
351
+ def state(self):
352
+ import robosuite.utils.transform_utils as T
353
+ env, rob = self.env, self.rob
354
+ d = env.sim.data
355
+ eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
356
+ q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
357
+ gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
358
+ try:
359
+ flat = np.asarray(env.sim.get_state().flatten(), np.float64)
360
+ except Exception:
361
+ flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
362
+ sk = self.rp.task.sk
363
+ return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
364
+ gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
365
+ joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
366
+ gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
367
+ eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
368
+ sim_time=np.float64(d.time), sim_state=flat)
369
+
370
+ def images(self):
371
+ return [envs.render(self.env, c, self.res) for c in self.cams]
372
+
373
+ def capture(self, a):
374
+ st = self.state()
375
+ st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
376
+ phase=np.int64(self.cur["phase"]))
377
+ self.sink.add(st, self.images())
378
+
379
+
380
+ class RunReplay:
381
+ def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
382
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
383
+ self.run_name = os.path.basename(self.run_dir)
384
+ self.log = RunLog(self.run_dir, manifest)
385
+ self.ev = self.log.ev
386
+ self.start = self.log.start
387
+ cp = os.path.join(self.run_dir, "contract.json")
388
+ self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
389
+ spec = self.contract.get("image_spec") or {}
390
+ self.image_res = int(spec.get("width", 512))
391
+ self.code_diff = check_code(self.run_dir)
392
+ s = self.start
393
+ self.task = TASKS[s["task"]](cam_res=self.image_res)
394
+ inst = self.task.sample_instance(s["seed"])
395
+ logged = s.get("inst") or {}
396
+ sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
397
+ self.inst_diff = diff_json(sampled, logged, "inst")
398
+ if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
399
+ inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
400
+ self.inst_diff = []
401
+ self.inst = inst
402
+ self.protocol = getattr(self.task, "protocol", "cross")
403
+ self.k = int(s.get("k") or self.task.max_attempts)
404
+ self.attempt = 1
405
+ self.mismatch = [] # (where, what, logged, replayed)
406
+ self.n_checked = 0
407
+ self.max_dev_m = 0.0
408
+ self.unfinished = None
409
+ self.rec = Recorder(self, res) if record else None
410
+ self.res = int(res)
411
+ self.out_root = out_root
412
+ self.n_mon = 0
413
+ self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
414
+ self.episodes = [] # summaries of the written episodes
415
+ self.task.reset_instance(self.inst)
416
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
417
+ sim = self.task.env.sim
418
+ bid = sim.model.body_name2id("robot0_base")
419
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
420
+ if self.rec:
421
+ self._open_episode()
422
+
423
+ # ------------------------------------------------------------------ episodes
424
+ def _ep_dir(self):
425
+ return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
426
+
427
+ def _open_episode(self):
428
+ self.rec.sink = EpisodeSink(self._ep_dir())
429
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
430
+ self.rec.active = True
431
+ self.events, self.spans, self.ep_attempts = [], [], []
432
+ self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
433
+
434
+ def close_episode(self):
435
+ if not self.rec:
436
+ self.ep_attempts = []
437
+ return
438
+ sink = self.rec.sink
439
+ st = self.rec.state()
440
+ imgs = self.rec.images()
441
+ st.pop("sim_state", None)
442
+ sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
443
+ ann = build_annotation(self, sink)
444
+ with open(os.path.join(sink.path, "annotation.json"), "w") as f:
445
+ json.dump(ann, f, indent=1, default=_json_default)
446
+ self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
447
+ attempts=[a["attempt"] for a in self.ep_attempts]))
448
+ self.rec.active = False
449
+ self.rec.sink = None
450
+ self.ep_index += 1
451
+
452
+ # ------------------------------------------------------------------ monitor events (task-side error events)
453
+ def poll_events(self, frame):
454
+ mon = getattr(self.task, "mon", None)
455
+ evs = mon.get("events") if isinstance(mon, dict) else None
456
+ if not isinstance(evs, list):
457
+ return
458
+ if len(evs) < self.n_mon: # monitor was rebuilt
459
+ self.n_mon = 0
460
+ for e in evs[self.n_mon:]:
461
+ self.events.append(dict(frame=int(frame), attempt=self.attempt,
462
+ event=norm_json(e) if isinstance(e, dict) else str(e)))
463
+ self.n_mon = len(evs)
464
+
465
+ # ------------------------------------------------------------------ state as the server reports it
466
+ def proprio_la(self):
467
+ p = self.ex.proprio()
468
+ pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
469
+ return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
470
+
471
+ def compare(self, where, rep_logged, rep):
472
+ self.n_checked += 1
473
+ for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
474
+ if k not in rep_logged or k not in rep:
475
+ continue
476
+ a, b = rep_logged[k], rep[k]
477
+ if k == "eef_pos":
478
+ dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
479
+ self.max_dev_m = max(self.max_dev_m, dev)
480
+ if dev > 1.5e-4:
481
+ self.mismatch.append((where, k, a, b))
482
+ elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
483
+ self.mismatch.append((where, k, a, b))
484
+ if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
485
+ self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
486
+
487
+ def _span(self, e, f0, kind):
488
+ if self.rec:
489
+ self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
490
+ frame_end=self.rec.n))
491
+
492
+ # ------------------------------------------------------------------ commands (robot_server._handle_v2)
493
+ def move_eef(self, e):
494
+ args = e.get("args") or {}
495
+ where = f"a{e['attempt']}s{e['step']}"
496
+ logged = e.get("report") or {}
497
+ f0 = self.rec.n if self.rec else 0
498
+ p = self.ex.proprio()
499
+ if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
500
+ self._span(e, f0, "error")
501
+ return self.compare(where, logged, dict(ok=False))
502
+ off = self.base_off
503
+ try:
504
+ cur = np.asarray(p["eef_pos"], float) - off
505
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
506
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
507
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
508
+ except (TypeError, ValueError):
509
+ self._span(e, f0, "error")
510
+ return self.compare(where, logged, dict(ok=False))
511
+ grip = args.get("gripper")
512
+ if grip not in (None, "open", "close"):
513
+ self._span(e, f0, "error")
514
+ return self.compare(where, logged, dict(ok=False))
515
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
516
+ tgt_w = np.asarray(tgt) + off
517
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
518
+ self._span(e, f0, "rejected")
519
+ return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
520
+ raw = {}
521
+ if self.rec:
522
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
523
+ if moving:
524
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
525
+ if speed is not None:
526
+ mv["speed"] = speed
527
+ raw.update(self.ex.call("move_to", mv).report)
528
+ if grip is not None:
529
+ if self.rec:
530
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
531
+ raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
532
+ rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
533
+ self.compare(where, logged, rep)
534
+ lr = e.get("raw") or {}
535
+ for k in ("holding_object", "touched_object"):
536
+ if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
537
+ self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
538
+ self._span(e, f0, "move_eef")
539
+
540
+ def observe(self, e):
541
+ f0 = self.rec.n if self.rec else 0
542
+ self._span(e, f0, "observe")
543
+
544
+ def done(self, e):
545
+ f0 = self.rec.n if self.rec else 0
546
+ if self.rec:
547
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
548
+ out = self.task.outcome(self.inst)
549
+ succ = bool(out["success"])
550
+ where = f"a{e['attempt']}done"
551
+ if succ != bool(e.get("success") in (True, "True")):
552
+ self.mismatch.append((where, "success", e.get("success"), succ))
553
+ lo = e.get("outcome") or {}
554
+ ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
555
+ if isinstance(lo, dict):
556
+ for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
557
+ self.mismatch.append((where,) + d)
558
+ info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
559
+ feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
560
+ think_s=e.get("think_s"))
561
+ try:
562
+ info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
563
+ except Exception as ex_:
564
+ info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
565
+ if self.rec:
566
+ info["judge_frames"] = [f0, self.rec.n]
567
+ self.ep_attempts.append(info)
568
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
569
+ if self.protocol == "cross" or last:
570
+ self.close_episode()
571
+ if last:
572
+ return True
573
+ self.attempt += 1
574
+ if self.protocol == "cross":
575
+ self.task.reset_instance(self.inst)
576
+ self.n_mon = 0
577
+ if self.rec:
578
+ self._open_episode()
579
+ elif self.rec:
580
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
581
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
582
+ return False
583
+
584
+ def run(self):
585
+ t0 = time.time()
586
+ finished = False
587
+ for e in self.ev:
588
+ if e["ev"] == "call":
589
+ if e.get("cmd") == "move_eef":
590
+ self.move_eef(e)
591
+ elif e.get("cmd") == "observe":
592
+ self.observe(e)
593
+ else:
594
+ self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
595
+ elif e["ev"] == "done":
596
+ finished = self.done(e)
597
+ if finished:
598
+ break
599
+ self.unfinished = not finished
600
+ if not finished and self.rec and self.rec.sink is not None:
601
+ # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
602
+ if self.rec.n or self.ep_attempts:
603
+ self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
604
+ finish_reason="", feedback_shown="", auto_ended=False))
605
+ self.close_episode()
606
+ else:
607
+ shutil.rmtree(self.rec.sink.path, ignore_errors=True)
608
+ self.rec.sink = None
609
+ self.wall_s = time.time() - t0
610
+ return self
611
+
612
+ def summary(self):
613
+ return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
614
+ protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
615
+ n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
616
+ unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
617
+ first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
618
+
619
+
620
+ # ====================================================================================================== annotation
621
+
622
+ def task_info(task, inst):
623
+ cls = type(task)
624
+ return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
625
+ category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
626
+ max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
627
+ instruction=cls.instruction)
628
+
629
+
630
+ def build_annotation(rp, sink):
631
+ """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
632
+ failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
633
+ task-side error events with frame indices."""
634
+ log = rp.log
635
+ s = rp.start
636
+ cond, chain = log.condition()
637
+ cls, hist = log.outcome_class()
638
+ att_all = log.attempts()
639
+ attempts = []
640
+ for a in rp.ep_attempts:
641
+ a = dict(a)
642
+ n = a["attempt"]
643
+ later = [x for x in att_all if x["attempt"] > n]
644
+ a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
645
+ a["is_last_attempt_of_run"] = not later
646
+ fn = log.finish_notes.get(n)
647
+ if fn:
648
+ a["agent_finish"] = fn
649
+ a["error_event_in_attempt"] = error_event(a.get("outcome"))
650
+ attempts.append(a)
651
+ # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
652
+ for a in attempts:
653
+ nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
654
+ if a.get("success") is False and nxt:
655
+ note = log.notes[nxt[0]]
656
+ a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
657
+ commands = []
658
+ for sp in rp.spans:
659
+ e = log.calls.get((sp["attempt"], sp["step"])) or {}
660
+ rep = e.get("report") or {}
661
+ c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
662
+ frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
663
+ args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
664
+ stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
665
+ gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
666
+ touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
667
+ agent_obs_images=rep.get("images"))
668
+ note = log.notes.get((sp["attempt"], sp["step"]))
669
+ if note:
670
+ c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
671
+ commands.append(c)
672
+ t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
673
+ return dict(
674
+ schema=SCHEMA,
675
+ source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
676
+ episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
677
+ memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
678
+ feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
679
+ k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
680
+ contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
681
+ if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
682
+ agent=log.agent_info(),
683
+ task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
684
+ instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
685
+ run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
686
+ run_success=any(x["success"] for x in att_all) if att_all else None,
687
+ agent_final_report=log.final_report[:6000] or None,
688
+ mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
689
+ attempts=attempts,
690
+ commands=commands,
691
+ task_events=rp.events,
692
+ frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
693
+ phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
694
+ joint_pos=rp.ep_initial["joint_pos"],
695
+ gripper_qpos=rp.ep_initial["gripper_qpos"])),
696
+ )
697
+
698
+
699
+ # ====================================================================================================== CLI
700
+
701
+ def load_manifest(run_dir):
702
+ p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
703
+ return json.load(open(p)) if os.path.exists(p) else {}
704
+
705
+
706
+ def main():
707
+ ap = argparse.ArgumentParser()
708
+ ap.add_argument("mode", choices=["check", "record"])
709
+ ap.add_argument("runs", nargs="+")
710
+ ap.add_argument("--json", default="")
711
+ ap.add_argument("--out", default="")
712
+ ap.add_argument("--res", type=int, default=256)
713
+ ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
714
+ a = ap.parse_args()
715
+ rows = []
716
+ for r in a.runs:
717
+ r = r.rstrip("/")
718
+ try:
719
+ if a.mode == "check":
720
+ s = RunReplay(r, manifest=load_manifest(r)).run().summary()
721
+ else:
722
+ batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
723
+ rd = os.path.join(a.out, batch, name)
724
+ if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
725
+ print(json.dumps(dict(run=name, skipped="exists")), flush=True)
726
+ continue
727
+ shutil.rmtree(rd, ignore_errors=True)
728
+ rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
729
+ s = rp.summary()
730
+ s["episodes"] = rp.episodes
731
+ with open(os.path.join(rd, "replay.json"), "w") as f:
732
+ json.dump(s, f, indent=1)
733
+ except Exception:
734
+ import traceback
735
+ s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
736
+ rows.append(s)
737
+ print(json.dumps(s), flush=True)
738
+ if a.json:
739
+ with open(a.json, "w") as f:
740
+ json.dump(rows, f, indent=1)
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
leaf/code/v1.5/backfill-20261102-lhp_opus_r2/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/code/v1.5/backfill-20261102-lhp_opus_r2/lerobot_replay.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
2
+ against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
3
+ LeRobot export (scripts/lerobot_export.py).
4
+
5
+ python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
6
+ python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
7
+
8
+ Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
9
+ commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
10
+ is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
11
+ like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
12
+ outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
13
+ ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
14
+ hashes equal the current files are expected to match (check_code()).
15
+
16
+ Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
17
+ proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
18
+ protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
19
+ per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
20
+ fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
21
+ agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
22
+ frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
23
+ sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
24
+ final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
25
+ annotation.json episode annotation (build_annotation)
26
+ and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
27
+ """
28
+ import argparse
29
+ import ast
30
+ import hashlib
31
+ import importlib
32
+ import json
33
+ import math
34
+ import os
35
+ import pkgutil
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections import defaultdict
41
+
42
+ import numpy as np
43
+
44
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
45
+ sys.path.insert(0, LFF_ROOT)
46
+
47
+ from lffbench import envs # noqa: E402
48
+ from lffbench import tasks as task_pkg # noqa: E402
49
+ from lffbench.agent import camera as C # noqa: E402
50
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
51
+ from lffbench.task_base import TASKS # noqa: E402
52
+
53
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
54
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
55
+
56
+ # per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
57
+ # task's outcome() check after `finish` (the arm holds still; not an agent action)
58
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
59
+ FPS = 20
60
+ SCHEMA = "lff-replay-1"
61
+
62
+ # error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
63
+ ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
64
+ ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
65
+ "n_missed_strikes", "n_open_gripper_pushes")
66
+
67
+
68
+ def load_jsonl(p):
69
+ out = []
70
+ if not os.path.exists(p):
71
+ return out
72
+ with open(p) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if line:
76
+ try:
77
+ out.append(json.loads(line))
78
+ except ValueError:
79
+ pass
80
+ return out
81
+
82
+
83
+ def norm_json(o):
84
+ return json.loads(json.dumps(o, default=_json_default))
85
+
86
+
87
+ def sha256(p):
88
+ with open(p, "rb") as f:
89
+ return hashlib.sha256(f.read()).hexdigest()
90
+
91
+
92
+ def check_code(run_dir):
93
+ """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
94
+ p = os.path.join(run_dir, "contract.json")
95
+ if not os.path.exists(p):
96
+ return [("contract.json", None, None)]
97
+ files = json.load(open(p))["contract"].get("server_code_files", {})
98
+ bad = []
99
+ for f, h in files.items():
100
+ q = os.path.join(LFF_ROOT, f)
101
+ cur = sha256(q) if os.path.exists(q) else None
102
+ if cur != h:
103
+ bad.append((f, h, cur))
104
+ return bad
105
+
106
+
107
+ def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
108
+ """Differences between two JSON values (numbers compared with an absolute tolerance)."""
109
+ out = [] if out is None else out
110
+ if len(out) >= limit:
111
+ return out
112
+ if isinstance(a, dict) and isinstance(b, dict):
113
+ for k in sorted(set(a) | set(b)):
114
+ if k not in a or k not in b:
115
+ out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
116
+ else:
117
+ diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
118
+ elif isinstance(a, list) and isinstance(b, list):
119
+ if len(a) != len(b):
120
+ out.append((path, f"len {len(a)}", f"len {len(b)}"))
121
+ else:
122
+ for i, (x, y) in enumerate(zip(a, b)):
123
+ diff_json(x, y, f"{path}[{i}]", tol, out, limit)
124
+ elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
125
+ if a != b:
126
+ out.append((path, a, b))
127
+ elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
128
+ out.append((path, a, b))
129
+ return out
130
+
131
+
132
+ def error_event(o):
133
+ """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
134
+ if not isinstance(o, dict):
135
+ return None
136
+ keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
137
+ if not keys:
138
+ return None
139
+ return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
140
+
141
+
142
+ # ====================================================================================================== logs -> notes
143
+
144
+ class RunLog:
145
+ """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
146
+ narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
147
+
148
+ def __init__(self, run_dir, manifest=None):
149
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
150
+ self.run = os.path.basename(self.run_dir)
151
+ self.batch = os.path.basename(os.path.dirname(self.run_dir))
152
+ self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
153
+ self.start = next(e for e in self.ev if e["ev"] == "session_start")
154
+ self.calls, self.dones, self.harness_status = {}, [], []
155
+ last = None
156
+ for e in self.ev:
157
+ if e["ev"] == "call":
158
+ self.calls[(int(e["attempt"]), int(e["step"]))] = e
159
+ last = e
160
+ elif e["ev"] == "done":
161
+ self.dones.append(e)
162
+ last = e
163
+ elif e["ev"] == "http" and last is not None and "think_s" not in last:
164
+ ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
165
+ (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
166
+ if ok:
167
+ last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
168
+ self.manifest = manifest or {}
169
+ self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
170
+ p = os.path.join(self.run_dir, "harness.json")
171
+ self.harness = json.load(open(p)) if os.path.exists(p) else {}
172
+ self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
173
+ self._narration()
174
+
175
+ # ---------------------------------------------------------------- agent narration
176
+ def _narration(self):
177
+ """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
178
+ finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
179
+ self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
180
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
181
+ attempt = 1
182
+
183
+ def take():
184
+ nonlocal buf
185
+ out = {k: v for k, v in buf.items() if v}
186
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
187
+ return out
188
+
189
+ last_msg = ""
190
+ for t in self.traj:
191
+ if t.get("kind") == "header":
192
+ self.headers.append(t.get("agent") or {})
193
+ continue
194
+ if t.get("kind") != "step":
195
+ continue
196
+ if (t.get("message") or "").strip():
197
+ buf["messages"].append(t["message"].strip())
198
+ last_msg = t["message"].strip()
199
+ if (t.get("reasoning_content") or "").strip():
200
+ buf["reasoning"].append(t["reasoning_content"].strip())
201
+ res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
202
+ for c in t.get("tool_calls") or []:
203
+ fn, args = c.get("function_name"), c.get("arguments") or {}
204
+ if fn == "shell":
205
+ buf["shell"].append(str(args.get("command", ""))[:2000])
206
+ elif fn == "view_images":
207
+ buf["viewed"].extend(args.get("paths") or [])
208
+ elif fn == "robot":
209
+ cmd = str(args.get("command", "")).strip()
210
+ r = res.get(c.get("tool_call_id")) or {}
211
+ try:
212
+ rep = json.loads(r.get("content") or "{}")
213
+ except ValueError:
214
+ rep = {}
215
+ word = cmd.split()[0] if cmd else ""
216
+ m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
217
+ if word in ("move_eef", "observe") and m:
218
+ a, s = int(m.group(1)), int(m.group(2))
219
+ n = take()
220
+ n["command"] = cmd
221
+ self.notes[(a, s)] = n
222
+ attempt = a
223
+ elif word in ("finish", "done"):
224
+ n = take()
225
+ n["command"] = cmd
226
+ n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
227
+ self.finish_notes.setdefault(attempt, n)
228
+ if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
229
+ attempt += 1
230
+ # status / help / errors: their narration stays in the buffer for the next command
231
+ self.final_report = last_msg
232
+
233
+ # ---------------------------------------------------------------- run-level labels
234
+ def attempts(self):
235
+ out = []
236
+ for e in self.dones:
237
+ o = e.get("outcome") or {}
238
+ if isinstance(o, str):
239
+ try:
240
+ o = ast.literal_eval(o)
241
+ except (ValueError, SyntaxError):
242
+ o = {}
243
+ out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
244
+ reason=e.get("reason") or ""))
245
+ return sorted(out, key=lambda x: x["attempt"])
246
+
247
+ def condition(self):
248
+ s, en = self.start, self.entry
249
+ mem = s.get("memory", en.get("mem"))
250
+ chain = en.get("chain")
251
+ if mem == "full":
252
+ cond = "with_history"
253
+ elif chain:
254
+ cond = "memory_free_retry"
255
+ else:
256
+ cond = "independent_single_attempt"
257
+ return cond, chain
258
+
259
+ def outcome_class(self):
260
+ """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
261
+ att = self.attempts()
262
+ if not att or self.start.get("memory") != "full":
263
+ return None, "".join("S" if a["success"] else "F" for a in att)
264
+ hist = "".join("S" if a["success"] else "F" for a in att)
265
+ if att[0]["success"]:
266
+ ev = error_event(att[0]["outcome"])
267
+ cls = "S?" if ev is None else ("IR" if ev else "CS")
268
+ else:
269
+ cls = "XR" if any(a["success"] for a in att) else "F"
270
+ return cls, hist
271
+
272
+ def agent_info(self):
273
+ h, en = self.harness, self.entry
274
+ hdr = self.headers[0] if self.headers else {}
275
+ return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
276
+ harness_version=h.get("version") or hdr.get("version"),
277
+ harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
278
+ model=h.get("model") or en.get("model") or hdr.get("model_name"),
279
+ effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
280
+ provider=h.get("provider") or en.get("provider"),
281
+ codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
282
+ jail=en.get("jail"))
283
+
284
+
285
+ # ====================================================================================================== recording
286
+
287
+ class EpisodeSink:
288
+ """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
289
+
290
+ def __init__(self, path):
291
+ self.path = path
292
+ os.makedirs(path, exist_ok=True)
293
+ self.w = None
294
+ self.num = defaultdict(list)
295
+ self.n = 0
296
+
297
+ def add(self, st, imgs):
298
+ import imageio
299
+ if self.w is None:
300
+ self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
301
+ pixelformat="rgb24", macro_block_size=1,
302
+ ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
303
+ for k in ("agentview", "wrist")]
304
+ for w, im in zip(self.w, imgs):
305
+ w.append_data(im)
306
+ for k, v in st.items():
307
+ self.num[k].append(v)
308
+ self.n += 1
309
+
310
+ def close(self, final_state, final_imgs):
311
+ from PIL import Image
312
+ if self.w is not None:
313
+ for w in self.w:
314
+ w.close()
315
+ arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
316
+ np.savez(os.path.join(self.path, "frames.npz"), **arr)
317
+ if self.num.get("sim_state"):
318
+ np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
319
+ np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
320
+ for k, im in zip(("agentview", "wrist"), final_imgs):
321
+ Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
322
+
323
+
324
+ class Recorder:
325
+ """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
326
+
327
+ def __init__(self, rp, res):
328
+ self.rp, self.res = rp, int(res)
329
+ self.active = False
330
+ self.sink = None
331
+ self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
332
+ env = rp.task.env
333
+ self.env, self.rob = env, env.robots[0]
334
+ self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
335
+ orig = env.step
336
+
337
+ def step(a):
338
+ if self.active and self.sink is not None:
339
+ self.capture(np.asarray(a, np.float64))
340
+ out = orig(a)
341
+ if self.active and self.sink is not None:
342
+ self.rp.poll_events(self.sink.n - 1)
343
+ return out
344
+
345
+ env.step = step
346
+
347
+ @property
348
+ def n(self):
349
+ return self.sink.n if self.sink is not None else 0
350
+
351
+ def state(self):
352
+ import robosuite.utils.transform_utils as T
353
+ env, rob = self.env, self.rob
354
+ d = env.sim.data
355
+ eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
356
+ q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
357
+ gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
358
+ try:
359
+ flat = np.asarray(env.sim.get_state().flatten(), np.float64)
360
+ except Exception:
361
+ flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
362
+ sk = self.rp.task.sk
363
+ return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
364
+ gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
365
+ joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
366
+ gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
367
+ eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
368
+ sim_time=np.float64(d.time), sim_state=flat)
369
+
370
+ def images(self):
371
+ return [envs.render(self.env, c, self.res) for c in self.cams]
372
+
373
+ def capture(self, a):
374
+ st = self.state()
375
+ st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
376
+ phase=np.int64(self.cur["phase"]))
377
+ self.sink.add(st, self.images())
378
+
379
+
380
+ class RunReplay:
381
+ def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
382
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
383
+ self.run_name = os.path.basename(self.run_dir)
384
+ self.log = RunLog(self.run_dir, manifest)
385
+ self.ev = self.log.ev
386
+ self.start = self.log.start
387
+ cp = os.path.join(self.run_dir, "contract.json")
388
+ self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
389
+ spec = self.contract.get("image_spec") or {}
390
+ self.image_res = int(spec.get("width", 512))
391
+ self.code_diff = check_code(self.run_dir)
392
+ s = self.start
393
+ self.task = TASKS[s["task"]](cam_res=self.image_res)
394
+ inst = self.task.sample_instance(s["seed"])
395
+ logged = s.get("inst") or {}
396
+ sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
397
+ self.inst_diff = diff_json(sampled, logged, "inst")
398
+ if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
399
+ inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
400
+ self.inst_diff = []
401
+ self.inst = inst
402
+ self.protocol = getattr(self.task, "protocol", "cross")
403
+ self.k = int(s.get("k") or self.task.max_attempts)
404
+ self.attempt = 1
405
+ self.mismatch = [] # (where, what, logged, replayed)
406
+ self.n_checked = 0
407
+ self.max_dev_m = 0.0
408
+ self.unfinished = None
409
+ self.rec = Recorder(self, res) if record else None
410
+ self.res = int(res)
411
+ self.out_root = out_root
412
+ self.n_mon = 0
413
+ self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
414
+ self.episodes = [] # summaries of the written episodes
415
+ self.task.reset_instance(self.inst)
416
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
417
+ sim = self.task.env.sim
418
+ bid = sim.model.body_name2id("robot0_base")
419
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
420
+ if self.rec:
421
+ self._open_episode()
422
+
423
+ # ------------------------------------------------------------------ episodes
424
+ def _ep_dir(self):
425
+ return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
426
+
427
+ def _open_episode(self):
428
+ self.rec.sink = EpisodeSink(self._ep_dir())
429
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
430
+ self.rec.active = True
431
+ self.events, self.spans, self.ep_attempts = [], [], []
432
+ self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
433
+
434
+ def close_episode(self):
435
+ if not self.rec:
436
+ self.ep_attempts = []
437
+ return
438
+ sink = self.rec.sink
439
+ st = self.rec.state()
440
+ imgs = self.rec.images()
441
+ st.pop("sim_state", None)
442
+ sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
443
+ ann = build_annotation(self, sink)
444
+ with open(os.path.join(sink.path, "annotation.json"), "w") as f:
445
+ json.dump(ann, f, indent=1, default=_json_default)
446
+ self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
447
+ attempts=[a["attempt"] for a in self.ep_attempts]))
448
+ self.rec.active = False
449
+ self.rec.sink = None
450
+ self.ep_index += 1
451
+
452
+ # ------------------------------------------------------------------ monitor events (task-side error events)
453
+ def poll_events(self, frame):
454
+ mon = getattr(self.task, "mon", None)
455
+ evs = mon.get("events") if isinstance(mon, dict) else None
456
+ if not isinstance(evs, list):
457
+ return
458
+ if len(evs) < self.n_mon: # monitor was rebuilt
459
+ self.n_mon = 0
460
+ for e in evs[self.n_mon:]:
461
+ self.events.append(dict(frame=int(frame), attempt=self.attempt,
462
+ event=norm_json(e) if isinstance(e, dict) else str(e)))
463
+ self.n_mon = len(evs)
464
+
465
+ # ------------------------------------------------------------------ state as the server reports it
466
+ def proprio_la(self):
467
+ p = self.ex.proprio()
468
+ pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
469
+ return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
470
+
471
+ def compare(self, where, rep_logged, rep):
472
+ self.n_checked += 1
473
+ for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
474
+ if k not in rep_logged or k not in rep:
475
+ continue
476
+ a, b = rep_logged[k], rep[k]
477
+ if k == "eef_pos":
478
+ dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
479
+ self.max_dev_m = max(self.max_dev_m, dev)
480
+ if dev > 1.5e-4:
481
+ self.mismatch.append((where, k, a, b))
482
+ elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
483
+ self.mismatch.append((where, k, a, b))
484
+ if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
485
+ self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
486
+
487
+ def _span(self, e, f0, kind):
488
+ if self.rec:
489
+ self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
490
+ frame_end=self.rec.n))
491
+
492
+ # ------------------------------------------------------------------ commands (robot_server._handle_v2)
493
+ def move_eef(self, e):
494
+ args = e.get("args") or {}
495
+ where = f"a{e['attempt']}s{e['step']}"
496
+ logged = e.get("report") or {}
497
+ f0 = self.rec.n if self.rec else 0
498
+ p = self.ex.proprio()
499
+ if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
500
+ self._span(e, f0, "error")
501
+ return self.compare(where, logged, dict(ok=False))
502
+ off = self.base_off
503
+ try:
504
+ cur = np.asarray(p["eef_pos"], float) - off
505
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
506
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
507
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
508
+ except (TypeError, ValueError):
509
+ self._span(e, f0, "error")
510
+ return self.compare(where, logged, dict(ok=False))
511
+ grip = args.get("gripper")
512
+ if grip not in (None, "open", "close"):
513
+ self._span(e, f0, "error")
514
+ return self.compare(where, logged, dict(ok=False))
515
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
516
+ tgt_w = np.asarray(tgt) + off
517
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
518
+ self._span(e, f0, "rejected")
519
+ return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
520
+ raw = {}
521
+ if self.rec:
522
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
523
+ if moving:
524
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
525
+ if speed is not None:
526
+ mv["speed"] = speed
527
+ raw.update(self.ex.call("move_to", mv).report)
528
+ if grip is not None:
529
+ if self.rec:
530
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
531
+ raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
532
+ rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
533
+ self.compare(where, logged, rep)
534
+ lr = e.get("raw") or {}
535
+ for k in ("holding_object", "touched_object"):
536
+ if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
537
+ self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
538
+ self._span(e, f0, "move_eef")
539
+
540
+ def observe(self, e):
541
+ f0 = self.rec.n if self.rec else 0
542
+ self._span(e, f0, "observe")
543
+
544
+ def done(self, e):
545
+ f0 = self.rec.n if self.rec else 0
546
+ if self.rec:
547
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
548
+ out = self.task.outcome(self.inst)
549
+ succ = bool(out["success"])
550
+ where = f"a{e['attempt']}done"
551
+ if succ != bool(e.get("success") in (True, "True")):
552
+ self.mismatch.append((where, "success", e.get("success"), succ))
553
+ lo = e.get("outcome") or {}
554
+ ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
555
+ if isinstance(lo, dict):
556
+ for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
557
+ self.mismatch.append((where,) + d)
558
+ info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
559
+ feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
560
+ think_s=e.get("think_s"))
561
+ try:
562
+ info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
563
+ except Exception as ex_:
564
+ info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
565
+ if self.rec:
566
+ info["judge_frames"] = [f0, self.rec.n]
567
+ self.ep_attempts.append(info)
568
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
569
+ if self.protocol == "cross" or last:
570
+ self.close_episode()
571
+ if last:
572
+ return True
573
+ self.attempt += 1
574
+ if self.protocol == "cross":
575
+ self.task.reset_instance(self.inst)
576
+ self.n_mon = 0
577
+ if self.rec:
578
+ self._open_episode()
579
+ elif self.rec:
580
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
581
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
582
+ return False
583
+
584
+ def run(self):
585
+ t0 = time.time()
586
+ finished = False
587
+ for e in self.ev:
588
+ if e["ev"] == "call":
589
+ if e.get("cmd") == "move_eef":
590
+ self.move_eef(e)
591
+ elif e.get("cmd") == "observe":
592
+ self.observe(e)
593
+ else:
594
+ self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
595
+ elif e["ev"] == "done":
596
+ finished = self.done(e)
597
+ if finished:
598
+ break
599
+ self.unfinished = not finished
600
+ if not finished and self.rec and self.rec.sink is not None:
601
+ # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
602
+ if self.rec.n or self.ep_attempts:
603
+ self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
604
+ finish_reason="", feedback_shown="", auto_ended=False))
605
+ self.close_episode()
606
+ else:
607
+ shutil.rmtree(self.rec.sink.path, ignore_errors=True)
608
+ self.rec.sink = None
609
+ self.wall_s = time.time() - t0
610
+ return self
611
+
612
+ def summary(self):
613
+ return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
614
+ protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
615
+ n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
616
+ unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
617
+ first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
618
+
619
+
620
+ # ====================================================================================================== annotation
621
+
622
+ def task_info(task, inst):
623
+ cls = type(task)
624
+ return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
625
+ category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
626
+ max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
627
+ instruction=cls.instruction)
628
+
629
+
630
+ def build_annotation(rp, sink):
631
+ """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
632
+ failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
633
+ task-side error events with frame indices."""
634
+ log = rp.log
635
+ s = rp.start
636
+ cond, chain = log.condition()
637
+ cls, hist = log.outcome_class()
638
+ att_all = log.attempts()
639
+ attempts = []
640
+ for a in rp.ep_attempts:
641
+ a = dict(a)
642
+ n = a["attempt"]
643
+ later = [x for x in att_all if x["attempt"] > n]
644
+ a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
645
+ a["is_last_attempt_of_run"] = not later
646
+ fn = log.finish_notes.get(n)
647
+ if fn:
648
+ a["agent_finish"] = fn
649
+ a["error_event_in_attempt"] = error_event(a.get("outcome"))
650
+ attempts.append(a)
651
+ # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
652
+ for a in attempts:
653
+ nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
654
+ if a.get("success") is False and nxt:
655
+ note = log.notes[nxt[0]]
656
+ a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
657
+ commands = []
658
+ for sp in rp.spans:
659
+ e = log.calls.get((sp["attempt"], sp["step"])) or {}
660
+ rep = e.get("report") or {}
661
+ c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
662
+ frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
663
+ args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
664
+ stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
665
+ gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
666
+ touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
667
+ agent_obs_images=rep.get("images"))
668
+ note = log.notes.get((sp["attempt"], sp["step"]))
669
+ if note:
670
+ c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
671
+ commands.append(c)
672
+ t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
673
+ return dict(
674
+ schema=SCHEMA,
675
+ source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
676
+ episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
677
+ memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
678
+ feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
679
+ k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
680
+ contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
681
+ if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
682
+ agent=log.agent_info(),
683
+ task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
684
+ instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
685
+ run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
686
+ run_success=any(x["success"] for x in att_all) if att_all else None,
687
+ agent_final_report=log.final_report[:6000] or None,
688
+ mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
689
+ attempts=attempts,
690
+ commands=commands,
691
+ task_events=rp.events,
692
+ frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
693
+ phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
694
+ joint_pos=rp.ep_initial["joint_pos"],
695
+ gripper_qpos=rp.ep_initial["gripper_qpos"])),
696
+ )
697
+
698
+
699
+ # ====================================================================================================== CLI
700
+
701
+ def load_manifest(run_dir):
702
+ p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
703
+ return json.load(open(p)) if os.path.exists(p) else {}
704
+
705
+
706
+ def main():
707
+ ap = argparse.ArgumentParser()
708
+ ap.add_argument("mode", choices=["check", "record"])
709
+ ap.add_argument("runs", nargs="+")
710
+ ap.add_argument("--json", default="")
711
+ ap.add_argument("--out", default="")
712
+ ap.add_argument("--res", type=int, default=256)
713
+ ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
714
+ a = ap.parse_args()
715
+ rows = []
716
+ for r in a.runs:
717
+ r = r.rstrip("/")
718
+ try:
719
+ if a.mode == "check":
720
+ s = RunReplay(r, manifest=load_manifest(r)).run().summary()
721
+ else:
722
+ batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
723
+ rd = os.path.join(a.out, batch, name)
724
+ if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
725
+ print(json.dumps(dict(run=name, skipped="exists")), flush=True)
726
+ continue
727
+ shutil.rmtree(rd, ignore_errors=True)
728
+ rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
729
+ s = rp.summary()
730
+ s["episodes"] = rp.episodes
731
+ with open(os.path.join(rd, "replay.json"), "w") as f:
732
+ json.dump(s, f, indent=1)
733
+ except Exception:
734
+ import traceback
735
+ s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
736
+ rows.append(s)
737
+ print(json.dumps(s), flush=True)
738
+ if a.json:
739
+ with open(a.json, "w") as f:
740
+ json.dump(rows, f, indent=1)
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
leaf/code/v1.5/backfill-20261102-tw2_opus/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/final/episode_001471_image.png ADDED

Git LFS Details

  • SHA256: fefc91b987490faaaf8e2490674a80bb6451d5f2a639efabc5df65875841b64d
  • Pointer size: 130 Bytes
  • Size of remote file: 69.4 kB
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-opus-5-5|high",
3
+ "fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6",
4
+ "written": "2026-10-20 02:16:17",
5
+ "summary": {
6
+ "system_chars": 6048,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-opus-5-5"
14
+ }
15
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_high.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt|0.163.0|399ff69c431c066e|gpt-6-astra|high",
3
+ "fingerprint_sha256": "359044b5060cd18979e3119b31aa0a6272f52769c7f6a14febeae808d71cc5da",
4
+ "written": "2026-10-19 22:12:19",
5
+ "summary": {
6
+ "developer_chars": 24091,
7
+ "top_tools": [
8
+ "collaboration.followup_task",
9
+ "collaboration.interrupt_agent",
10
+ "collaboration.list_agents",
11
+ "collaboration.send_message",
12
+ "collaboration.spawn_agent",
13
+ "collaboration.wait_agent",
14
+ "functions.exec",
15
+ "functions.request_user_input",
16
+ "functions.request_user_input_async",
17
+ "functions.wait"
18
+ ],
19
+ "all_tools": [
20
+ "apply_patch",
21
+ "clock__curr_time",
22
+ "list_mcp_resource_templates",
23
+ "list_mcp_resources",
24
+ "mcp__lff__robot",
25
+ "mcp__lff__shell",
26
+ "mcp__lff__view_images",
27
+ "read_mcp_resource"
28
+ ],
29
+ "effort_in_request": "high",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "rpent_codex-generic-da5f128c34a2|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9",
4
+ "written": "2026-10-21 05:11:12",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6.1-sol",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ },
22
+ "middle_fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
23
+ "rpent_prefix_sha256": "f0d0e0a62990cb7028bfb3889e49423b12635347aaddbda40e4d2fc4cb408e25",
24
+ "rpent_prefix_chars": 2789,
25
+ "anchor_status": "match"
26
+ }
27
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "sensenova_codex-chatgpt-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9",
4
+ "written": "2026-10-26 07:08:06",
5
+ "summary": {
6
+ "report": "/mnt/cpfs/workspace/agentic-robotics/reports/robot_harness_subscription_resume_20261026/selfcheck_verified/selfcheck.json",
7
+ "checks": 10,
8
+ "framework": {
9
+ "commit": "b513a1c7289ab11eb844856588b64c378705c405",
10
+ "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823",
11
+ "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350",
12
+ "untracked": [
13
+ "lff_integration/__init__.py",
14
+ "lff_integration/run.py"
15
+ ]
16
+ }
17
+ }
18
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_card_edge.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3 card_edge: a thin card lying flat on a board cannot be pinched; slide it over the board's edge, then grasp it.
2
+
3
+ Category: strategy_switching ("this way of doing it cannot work"), the user's taxonomy L3 example verbatim:
4
+ "卡片贴着桌面捏不起来 -> 先把卡片滑到桌沿,再夹起来".
5
+
6
+ Scene: a wooden board (22 x 26 x 5 cm) on the table with a thin red card (9.0 x 5.6 x 0.2 cm, 10 g) lying flat on it,
7
+ long side roughly along x or along y (+-10 deg); a grey bin (16 x 16 cm inside) stands on the table beside the board.
8
+ The board stands in for the table edge of the user's example: the real table edge is out of reach (near edge 16 cm
9
+ from the robot base, side edges at |y| = 0.6 m) and the harness does not let the grasp point go below the table top.
10
+
11
+ Why the prior fails (measured): a top-down grasp across the card's short side. The Panda fingertips land on the
12
+ board on either side of the card, but when they close on its 2 mm edge the contact flips to "slide over the top" and
13
+ both fingertips ride up over the card and close above it: 0/36 lifts for 1.5 / 2 / 3 mm cards, grasp-point height
14
+ -6..+3 mm, xy jitter 5 mm, yaw jitter 0.1 rad (prototype, 2026-10-08). Retrying with small variations fails the same
15
+ way. (A 4 mm card could be pinched -- the reason the earlier `l3_flat_card_edge` was dropped.)
16
+
17
+ What must be learned from the failure: the card cannot be picked up while it lies flat -> change the strategy: press
18
+ the closed fingertips onto the card and slide it (move_to with the fingertips pressing on it) until part of it hangs
19
+ over the board's edge, then grasp the overhanging part with the fingertips below the card: then the fingers close on
20
+ the card's full edge and it lifts (18/18 for 2.5-3.5 cm of overhang in the prototype). More than half the card's
21
+ length over the edge and it tips off the board.
22
+
23
+ Protocol: cross (reset to the same instance before every attempt), k = 5.
24
+ """
25
+ import numpy as np
26
+
27
+ from .. import envs
28
+ from ..bddl import write_bddl
29
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
30
+ from ..skills import Skills
31
+ from ..task_base import LFFTask, register_task
32
+
33
+ CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm
34
+ CARD_MASS = 0.010
35
+ MU = 0.3 # card and board sliding friction (the fingers' 1.0 / 2.0 win in finger contacts: MuJoCo takes the max)
36
+ BOARD_HALF = (0.11, 0.13, 0.025)
37
+ BOARD_TOP = envs.TABLE_Z + 2 * BOARD_HALF[2]
38
+ BIN_IN = 0.08 # inner half width
39
+ BIN_WALL_H = 0.05
40
+ BIN_GAP = 0.06 # board edge to bin outer wall
41
+ BIN_T = 0.006
42
+ BIN_HALF_OUT = BIN_IN + BIN_T
43
+ TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
44
+ LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
45
+ OVERHANG = 0.03 # scripted target overhang (the grasp works for ~2.5-4.0 cm; the card tips off past ~4.5 cm)
46
+ GRASP_OUT = 0.022 # scripted grasp point: this far beyond the board edge (fingers must clear the edge)
47
+ DRAG_SPEED = 0.08
48
+
49
+
50
+ def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
51
+ g = (f' <geom name="{name}_g0" type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" mass="{CARD_MASS}" '
52
+ f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
53
+ f' <geom type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
54
+ return _wrap(name, g, CARD_HALF[2], float(np.hypot(CARD_HALF[0], CARD_HALF[1])))
55
+
56
+
57
+ def _yaw_of(quat_wxyz):
58
+ w, x, y, z = quat_wxyz
59
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
60
+
61
+
62
+ EDGES = ("forward", "backward", "left", "right") # board edges in robot-centric words (+x, -x, +y, -y)
63
+
64
+
65
+ class CardSkills(Skills):
66
+ """Skills that feed the task's per-step monitor and log every close of the gripper."""
67
+
68
+ def __init__(self, env, task, recorder=None):
69
+ super().__init__(env, recorder=recorder)
70
+ self.task = task
71
+ self.closes = []
72
+
73
+ def _act(self, dpos, drot, grip):
74
+ super()._act(dpos, drot, grip)
75
+ self.task.monitor_step()
76
+
77
+ def set_gripper(self, close, steps=15):
78
+ was_open = self.grip < 0
79
+ before = self.task.close_context() if (close and was_open) else None
80
+ rep = super().set_gripper(close, steps)
81
+ if before is not None:
82
+ before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
83
+ self.closes.append(before)
84
+ return rep
85
+
86
+
87
+ @register_task
88
+ class CardEdge(LFFTask):
89
+ name = "l3_card_edge"
90
+ level = "L3"
91
+ category = "strategy_switching"
92
+ capabilities = ("Perceive", "Reason", "Plan")
93
+ protocol = "cross"
94
+ instruction = "Pick up the thin red card lying on the wooden board and put it into the grey bin."
95
+ instruction_indirect = "Put the flat red rectangle that lies on the wooden block into the grey container."
96
+
97
+ # ------------------------------------------------------------ scene
98
+ def make_bddl(self):
99
+ card = register_generated("LffThinCard", card_xml("lff_thin_card"))
100
+ board = register_generated("LffCardBoard", box_xml("lff_card_board", BOARD_HALF, (0.62, 0.45, 0.27, 1.0),
101
+ friction=(MU, 0.005, 0.0001)), free=False)
102
+ bin_ = register_generated("LffCardBin", bin_xml("lff_card_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
103
+ rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
104
+ objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
105
+ fx = [("board_1", board, "board_region", (-0.11, -0.01, -0.09, 0.01)),
106
+ ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
107
+ return write_bddl(self.name, self.instruction, objs, fx)
108
+
109
+ def __init__(self, cam_res=None):
110
+ super().__init__(cam_res)
111
+ m = self.env.sim.model
112
+ self.board_bid = m.body_name2id(self.env.fixtures_dict["board_1"].root_body)
113
+ self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
114
+ self.inst = None
115
+ self.mon = None
116
+
117
+ def sample_instance(self, seed):
118
+ rng = np.random.default_rng(seed)
119
+ bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
120
+ along = str(rng.choice(["x", "y"]))
121
+ yaw = (0.0 if along == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
122
+ if along == "x": # keep the whole card >= 3 cm (long axis) / 2 cm (short axis) inside the board
123
+ off = [rng.uniform(-0.03, 0.03), rng.uniform(-0.07, 0.07)]
124
+ else:
125
+ off = [rng.uniform(-0.055, 0.055), rng.uniform(-0.05, 0.05)]
126
+ side = 1.0 if rng.random() < 0.5 else -1.0
127
+ bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (BOARD_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
128
+ return dict(seed=int(seed), board_xy=[bx, by], card_xy=[bx + float(off[0]), by + float(off[1])],
129
+ card_yaw=float(yaw), card_along=along, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
130
+
131
+ def apply_instance(self, inst):
132
+ self.inst = inst
133
+ m = self.env.sim.model
134
+ bx, by = inst["board_xy"]
135
+ m.body_pos[self.board_bid] = [bx, by, envs.TABLE_Z + BOARD_HALF[2]]
136
+ m.body_quat[self.board_bid] = [1.0, 0.0, 0.0, 0.0]
137
+ cx, cy = inst["bin_xy"]
138
+ m.body_pos[self.bin_bid] = [cx, cy, envs.TABLE_Z + (BIN_WALL_H + BIN_T) / 2]
139
+ m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
140
+ x, y = inst["card_xy"]
141
+ envs.set_obj_pose(self.env, "card_1", [x, y, BOARD_TOP + CARD_HALF[2] + 0.0003], yaw=inst["card_yaw"])
142
+
143
+ def reset_instance(self, inst, recorder=None):
144
+ self.env.reset()
145
+ self.apply_instance(inst)
146
+ self.env.sim.forward()
147
+ envs.settle(self.env, 15)
148
+ self.sk = CardSkills(self.env, self, recorder=recorder)
149
+ p = self.card_pose()
150
+ self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False)
151
+ return self.sk
152
+
153
+ # ------------------------------------------------------------ geometry
154
+ def card_pose(self):
155
+ p = envs.obj_pos(self.env, "card_1")
156
+ return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
157
+
158
+ def card_corners(self):
159
+ d = self.env.sim.data
160
+ bid = envs.body_id(self.env, "card_1")
161
+ R = d.body_xmat[bid].reshape(3, 3)
162
+ h = np.array(CARD_HALF)
163
+ return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
164
+
165
+ def overhang(self):
166
+ """(how far the card sticks out beyond the board's edges (m, max over its corners), edge word)"""
167
+ c = self.card_corners()[:, :2] - np.asarray(self.inst["board_xy"])
168
+ prot = {"forward": c[:, 0].max() - BOARD_HALF[0], "backward": -c[:, 0].min() - BOARD_HALF[0],
169
+ "left": c[:, 1].max() - BOARD_HALF[1], "right": -c[:, 1].min() - BOARD_HALF[1]}
170
+ e = max(prot, key=prot.get)
171
+ return float(prot[e]), e
172
+
173
+ def on_board(self):
174
+ p = self.card_pose()
175
+ rel = np.abs(p["xy"] - np.asarray(self.inst["board_xy"]))
176
+ return bool(rel[0] <= BOARD_HALF[0] and rel[1] <= BOARD_HALF[1] and abs(p["z"] - BOARD_TOP) < 0.012)
177
+
178
+ def in_bin(self):
179
+ p = self.card_pose()
180
+ rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
181
+ return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < envs.TABLE_Z + BIN_T + BIN_WALL_H)
182
+
183
+ # ------------------------------------------------------------ monitor
184
+ def monitor_step(self):
185
+ mon = self.mon
186
+ if mon is None:
187
+ return
188
+ zmin = float(self.card_corners()[:, 2].min())
189
+ mon["max_lift"] = max(mon["max_lift"], zmin - BOARD_TOP)
190
+ if self.on_board() or abs(self.card_pose()["z"] - BOARD_TOP) < 0.012:
191
+ mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
192
+ if self.card_pose()["z"] < BOARD_TOP - 0.02 and not self.sk.holding("card_1"):
193
+ mon["fell"] = True
194
+
195
+ def close_context(self):
196
+ """Where the gripper is relative to the card and the board just before it closes."""
197
+ sk, p = self.sk, self.card_pose()
198
+ e = sk.eef_pos()
199
+ c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
200
+ rel = e[:2] - p["xy"]
201
+ local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side
202
+ b = e[:2] - np.asarray(self.inst["board_xy"])
203
+ beyond = {"forward": b[0] - BOARD_HALF[0], "backward": -b[0] - BOARD_HALF[0],
204
+ "left": b[1] - BOARD_HALF[1], "right": -b[1] - BOARD_HALF[1]}
205
+ edge = max(beyond, key=beyond.get)
206
+ ov, ov_edge = self.overhang()
207
+ return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
208
+ tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
209
+ beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
210
+ card_on_board=self.on_board(), overhang=round(ov, 4), overhang_edge=ov_edge,
211
+ width_before=round(sk.gripper_width(), 4))
212
+
213
+ # ------------------------------------------------------------ outcome / F2
214
+ def outcome(self, inst):
215
+ envs.settle(self.env, 30)
216
+ sk, mon = self.sk, self.mon
217
+ p = self.card_pose()
218
+ held = bool(sk.holding("card_1"))
219
+ in_bin = self.in_bin() and not held
220
+ success = bool(in_bin)
221
+ moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
222
+ lifted = mon["max_lift"] > 0.02
223
+ tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
224
+ parts, mode = [], "success"
225
+ if success:
226
+ parts.append("The card is in the bin.")
227
+ else:
228
+ rel = p["xy"] - np.asarray(inst["bin_xy"])
229
+ where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
230
+ f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
231
+ if held:
232
+ mode = "held"
233
+ parts.append(f"The card is still held by the gripper, {where}.")
234
+ elif lifted:
235
+ mode = "dropped"
236
+ loc = "on the board" if self.on_board() else ("on the table" if p["z"] < BOARD_TOP - 0.02 else
237
+ "partly on the board")
238
+ parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the board but is not in the "
239
+ f"bin: it lies {loc}, its centre {where}.")
240
+ elif mon["fell"]:
241
+ mode = "fell_off"
242
+ parts.append("The card was never lifted; it fell off the board and lies flat on the table.")
243
+ else:
244
+ mode = "not_lifted"
245
+ parts.append("The card was never lifted; it still lies flat on the board"
246
+ + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
247
+ f"{100 * mon['max_overhang']:.1f} cm beyond the board's edge)" if mon["max_overhang"] > 0.003
248
+ else ")") if moved > 0.005 else "") + ".")
249
+ if not lifted:
250
+ if not tries:
251
+ parts.append("The gripper never closed with its fingertips down at the card.")
252
+ else:
253
+ c = tries[-1]
254
+ n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
255
+ if c["card_on_board"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
256
+ txt = ("when the gripper closed on the card lying flat on the board, its fingertips were on "
257
+ "either side of the card, at board level")
258
+ else:
259
+ if c["beyond_edge"] >= 0.0:
260
+ pos = f"{100 * c['beyond_edge']:.1f} cm beyond the board's {c['beyond_edge_name']} edge"
261
+ else:
262
+ pos = f"over the board, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge"
263
+ txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm "
264
+ f"beyond the board's {c['overhang_edge']} edge and the gripper's centre was {pos}")
265
+ txt += (f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the "
266
+ "fingers closed ")
267
+ txt += ("fully, sliding over the top of the card instead of gripping its edges."
268
+ if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
269
+ ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
270
+ parts.append(n + txt if n else txt[0].upper() + txt[1:])
271
+ out = dict(success=success, mode=mode, held=held, lifted=bool(lifted), max_lift=round(mon["max_lift"], 4),
272
+ max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), fell=bool(mon["fell"]),
273
+ grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
274
+ return out
275
+
276
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
277
+ def _edge_plan(self, inst):
278
+ """the board edge the card is slid to: along its long side; the near (backward) edge for x-cards,
279
+ the closer side edge for y-cards"""
280
+ if inst["card_along"] == "x":
281
+ return "backward"
282
+ return "left" if inst["card_xy"][1] >= inst["board_xy"][1] else "right"
283
+
284
+ def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
285
+ sk = self.sk
286
+ sk.set_gripper(False, steps=8)
287
+ sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
288
+ sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
289
+ sk.set_gripper(True, steps=15)
290
+ sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
291
+ if not sk.holding("card_1"):
292
+ sk.set_gripper(False, steps=8)
293
+ return False
294
+ bx, by = self.inst["bin_xy"]
295
+ hi = envs.TABLE_Z + BIN_WALL_H + 0.12
296
+ sk.move_to([bx, by, hi])
297
+ sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05], speed=0.2)
298
+ sk.set_gripper(False, steps=12)
299
+ sk.move_to([bx, by, hi])
300
+ return True
301
+
302
+ def slide_card(self, delta, press=0.004):
303
+ """closed fingertips pressed on the card's centre, straight move by `delta` (xy), lift"""
304
+ sk, p = self.sk, self.card_pose()
305
+ z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
306
+ sk.set_gripper(True, steps=8)
307
+ sk.move_to([p["xy"][0], p["xy"][1], z + 0.06], yaw=p["yaw"])
308
+ sk.move_to([p["xy"][0], p["xy"][1], z], tol=0.003, max_steps=100)
309
+ e = p["xy"] + np.asarray(delta, float)
310
+ sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
311
+ sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
312
+ sk.hold(5)
313
+
314
+ def execute(self, inst, params):
315
+ p = self.card_pose()
316
+ if params["mode"] == "grasp":
317
+ xy = p["xy"] + np.asarray(params.get("dxy", (0.0, 0.0)))
318
+ self.grasp_and_bin(xy, p["yaw"] + params.get("dyaw", 0.0), BOARD_TOP + params.get("dz", 0.0))
319
+ return
320
+ # edge: slide the card along its long side until `overhang` of it sticks out over the chosen edge
321
+ edge = params.get("edge") or self._edge_plan(inst)
322
+ u = {"forward": (1, 0), "backward": (-1, 0), "left": (0, 1), "right": (0, -1)}[edge]
323
+ u = np.asarray(u, float)
324
+ c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
325
+ long_ax = np.array([c, s]) if abs(np.array([c, s]) @ u) >= abs(np.array([-s, c]) @ u) else np.array([-s, c])
326
+ long_ax = long_ax * np.sign(long_ax @ u)
327
+ b = np.asarray(inst["board_xy"])
328
+ half = BOARD_HALF[0] if edge in ("forward", "backward") else BOARD_HALF[1]
329
+ edge_pos = (b @ u) + half # coordinate of the edge along u
330
+ ext = CARD_HALF[0] * abs(long_ax @ u) + CARD_HALF[1] * abs(np.array([-long_ax[1], long_ax[0]]) @ u)
331
+ for short in (0.01, 0.0): # slide to 1 cm short, look again, slide the rest (one stroke overshoots ~0.7 cm)
332
+ p = self.card_pose()
333
+ need = edge_pos + float(params["overhang"]) - short - (p["xy"] @ u + ext) # travel still needed along u
334
+ if need > 0.003:
335
+ self.slide_card(long_ax * need / max(long_ax @ u, 1e-6))
336
+ q = self.card_pose()
337
+ cu = float(q["xy"] @ u)
338
+ tip_u = cu + CARD_HALF[0] * float(long_ax @ u) # centre of the card's far end, along u
339
+ target_u = min(tip_u - 0.008, edge_pos + GRASP_OUT)
340
+ g = q["xy"] + long_ax * (target_u - cu) / max(float(long_ax @ u), 1e-6)
341
+ self.grasp_and_bin(g, q["yaw"], BOARD_TOP - 0.003)
342
+
343
+ def default_params(self, inst):
344
+ return dict(mode="grasp")
345
+
346
+ def oracle_params(self, inst):
347
+ return dict(mode="edge", overhang=OVERHANG)
348
+
349
+ def blind_params(self, inst, attempt, rng):
350
+ return dict(mode="grasp", dxy=rng.normal(0.0, 0.006, 2).tolist(), dyaw=float(rng.normal(0.0, 0.12)),
351
+ dz=float(rng.uniform(-0.006, 0.003)))
352
+
353
+ def adapt_params(self, inst, history):
354
+ """not lifted while flat on the board (fingers slid over it) -> slide it over the edge first, 3 cm.
355
+ Edge tried: card fell off -> 1 cm less; fingers closed without holding and < 4 cm overhang -> 1 cm more."""
356
+ out, prm = history[-1]["outcome"], history[-1]["params"]
357
+ if prm["mode"] == "grasp":
358
+ return dict(mode="edge", overhang=OVERHANG) if out["mode"] in ("not_lifted", "fell_off") else dict(prm)
359
+ h = float(prm["overhang"])
360
+ if out["mode"] == "fell_off":
361
+ h -= 0.01
362
+ elif out["mode"] == "not_lifted":
363
+ h += 0.01 if out["max_overhang"] < 0.04 else -0.005
364
+ return dict(mode="edge", overhang=float(np.clip(h, 0.025, 0.045)))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_wide.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3-B too_wide_push: a box that is slightly too wide for the gripper must be pushed into a square on the table.
2
+
3
+ Why the prior fails: the box looks like an ordinary graspable box (narrow side 8.3-8.9 cm, long side 11-13 cm,
4
+ 4 cm high), but the Panda's fingers open to only 7.9 cm. A top-down grasp across the narrow side therefore puts
5
+ both fingers on top of the box; closing them grips nothing. Across the long side it is worse, and retrying the
6
+ same grasp with small variations fails the same way. A difference of 4-10 mm between the box and the maximum
7
+ opening is not readable from the camera images, and the agent is not told the gripper's opening.
8
+
9
+ What must be learned from the failure: this object cannot be picked up at all -> change the manipulation mode:
10
+ close the gripper and push the box (there is no push primitive: the agent closes the gripper, lowers it beside
11
+ the box and moves it along the table with move_to), keeping the box from turning, until it lies completely
12
+ inside the square.
13
+
14
+ Layout (randomised per instance): box size, position and yaw (long side roughly along x or along y, +-10 deg),
15
+ target square (18 x 18 cm inner, axis-aligned) 16-22 cm away along one world axis (forward, backward, left or
16
+ right) with a lateral offset of up to 3 cm.
17
+
18
+ Protocol: cross (reset to the same instance before every attempt), k = 5.
19
+ """
20
+ import numpy as np
21
+
22
+ from .. import envs
23
+ from ..bddl import write_bddl
24
+ from ..objects import box_xml, register_generated
25
+ from ..skills import DT, _rot_err
26
+ from ..task_base import LFFTask, register_task
27
+ from .l5_slide import square_frame_xml
28
+
29
+ BOX_HALF_MAX = (0.07, 0.05, 0.02) # registered size (x = long, y = narrow, z); shrunk per instance
30
+ BOX_HALF_Z = 0.02 # 4 cm high
31
+ BOX_MASS = 0.40
32
+ BOX_MU = 0.6 # box sliding friction (priority over the table's 1.0 and the fingers')
33
+ GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open
34
+ SQ_IN = 0.09 # target square: 18 cm inner side
35
+ SQ_LINE = 0.008
36
+ Z_GRASP = envs.TABLE_Z + 0.022 # site height of a normal top-down grasp of a 4 cm box (pads 1.7-3.4 cm above table)
37
+ Z_PUSH = envs.TABLE_Z + 0.02 # site height while pushing: finger tips ~1 cm above the table
38
+ PUSH_SPEED = 0.08
39
+ FRONT_GAP = 0.03 # where a push stroke starts: this far behind the box face
40
+
41
+
42
+ def _wrap_pi(a):
43
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
44
+
45
+
46
+ def _yaw_of(quat_wxyz):
47
+ w, x, y, z = quat_wxyz
48
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
49
+
50
+
51
+ DIRS = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)}
52
+
53
+
54
+ @register_task
55
+ class TooWidePush(LFFTask):
56
+ name = "l3_too_wide_push"
57
+ level = "L3"
58
+ category = "strategy_switching"
59
+ capabilities = ("Perceive", "Reason", "Plan")
60
+ protocol = "cross"
61
+ instruction = "Put the brown box completely inside the green square marked on the table."
62
+ instruction_indirect = "Put the cardboard-coloured package completely inside the green outlined area on the table."
63
+
64
+ def __init__(self, cam_res=None):
65
+ super().__init__(cam_res)
66
+ self._mon = None
67
+ self.inst = None
68
+ orig_step = self.env.step
69
+
70
+ def step(action): # per-control-step event monitor (also sees agent-driven attempts)
71
+ ret = orig_step(action)
72
+ if self._mon is not None:
73
+ self._monitor_step()
74
+ return ret
75
+
76
+ self.env.step = step
77
+
78
+ # ------------------------------------------------------------ scene
79
+ def make_bddl(self):
80
+ box = register_generated("LffWideBox", box_xml("lff_wide_box", BOX_HALF_MAX, (0.62, 0.45, 0.28, 1.0),
81
+ density=500))
82
+ sq = register_generated("LffWideSquare", square_frame_xml("lff_wide_square", inner_half=SQ_IN, line_w=SQ_LINE),
83
+ free=False)
84
+ objs = [("box_1", box, "box_region", (-0.11, -0.21, -0.09, -0.19))]
85
+ fx = [("square_1", sq, "square_region", (-0.01, 0.19, 0.01, 0.21))]
86
+ return write_bddl(self.name, self.instruction, objs, fx)
87
+
88
+ def _box_geoms(self):
89
+ if not hasattr(self, "_bg"):
90
+ m = self.env.sim.model
91
+ bid = envs.body_id(self.env, "box_1")
92
+ self._bg = [g for g in range(m.ngeom) if m.geom_bodyid[g] == bid]
93
+ return self._bg
94
+
95
+ def sample_instance(self, seed):
96
+ rng = np.random.default_rng(seed)
97
+ while True:
98
+ narrow = float(rng.uniform(0.083, 0.089))
99
+ long_ = float(rng.uniform(0.11, 0.13))
100
+ long_axis = str(rng.choice(["x", "y"]))
101
+ yaw = (0.0 if long_axis == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
102
+ dname = str(rng.choice(list(DIRS)))
103
+ u = np.array(DIRS[dname])
104
+ # half extent of the box along the push direction (box roughly axis aligned)
105
+ ext = 0.5 * (long_ if (long_axis == "x") == (dname in ("forward", "backward")) else narrow)
106
+ dist = float(rng.uniform(SQ_IN + ext + 0.01, SQ_IN + ext + 0.07))
107
+ lat = float(rng.uniform(-0.03, 0.03))
108
+ box_xy = np.array([rng.uniform(-0.20, 0.04), rng.uniform(-0.20, 0.20)])
109
+ sq_xy = box_xy + u * dist + np.array([-u[1], u[0]]) * lat
110
+ # reach: pushing backward needs the hand ~5 cm beyond the box's far face; the arm's reach at table height
111
+ # ends around x = 0.05-0.08 (seed 1015 of the first version: hand stalled at x = 0.09, box never moved)
112
+ reach_ok = dname != "backward" or box_xy[0] + ext <= -0.01
113
+ if -0.22 <= sq_xy[0] <= 0.06 and -0.20 <= sq_xy[1] <= 0.20 and reach_ok:
114
+ return dict(seed=int(seed), box_half=[long_ / 2, narrow / 2], box_yaw=float(yaw), box_xy=box_xy.tolist(),
115
+ square_xy=sq_xy.tolist(), direction=dname, long_axis=long_axis)
116
+
117
+ def apply_instance(self, inst):
118
+ self.inst = inst
119
+ m = self.env.sim.model
120
+ for g in self._box_geoms():
121
+ m.geom_size[g, 0], m.geom_size[g, 1] = inst["box_half"]
122
+ m.geom_size[g, 2] = BOX_HALF_Z
123
+ envs.scale_mass(self.env, "box_1", BOX_MASS)
124
+ envs.set_friction(self.env, "box_1", BOX_MU)
125
+ sq = self.env.fixtures_dict["square_1"]
126
+ for g in range(m.ngeom):
127
+ if (m.geom_id2name(g) or "").startswith("square_1_"):
128
+ m.geom_contype[g] = 0
129
+ m.geom_conaffinity[g] = 0
130
+ bid = m.body_name2id(sq.root_body)
131
+ m.body_pos[bid] = [inst["square_xy"][0], inst["square_xy"][1], envs.TABLE_Z + 0.0002]
132
+ m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
133
+ bx, by = inst["box_xy"]
134
+ envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF_Z + 0.0005], yaw=inst["box_yaw"])
135
+
136
+ def reset_instance(self, inst, recorder=None):
137
+ self._mon = None
138
+ sk = super().reset_instance(inst, recorder=recorder)
139
+ self._start_monitor()
140
+ return sk
141
+
142
+ # ------------------------------------------------------------ geometry / perception stand-in
143
+ def observe(self):
144
+ """What a perfect perceiver reads off the image: box centre, yaw and footprint, square centre."""
145
+ b = envs.obj_pos(self.env, "box_1")
146
+ return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")),
147
+ square_xy=np.array(self.inst["square_xy"], float), half=np.array(self.inst["box_half"], float))
148
+
149
+ def corners3d(self):
150
+ """the 8 corners of the box (world)"""
151
+ d = self.env.sim.data
152
+ bid = envs.body_id(self.env, "box_1")
153
+ R = d.body_xmat[bid].reshape(3, 3)
154
+ h = np.array([self.inst["box_half"][0], self.inst["box_half"][1], BOX_HALF_Z])
155
+ return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, sz]) for sx in (-1, 1) for sy in (-1, 1)
156
+ for sz in (-1, 1)])
157
+
158
+ def corners(self, o=None):
159
+ """footprint corners (xy) of the box in its current pose (also when it is tilted or on its side)"""
160
+ return self.corners3d()[:, :2]
161
+
162
+ def protrusion(self, o=None):
163
+ """How far the box footprint sticks out beyond each edge of the square (m, >0 = outside)."""
164
+ o = o or self.observe()
165
+ rel = self.corners(o) - o["square_xy"]
166
+ return {"forward": float(rel[:, 0].max() - SQ_IN), "backward": float(-rel[:, 0].min() - SQ_IN),
167
+ "left": float(rel[:, 1].max() - SQ_IN), "right": float(-rel[:, 1].min() - SQ_IN)}
168
+
169
+ def extent_along(self, u, o=None):
170
+ """half extent of the box footprint along the unit xy vector u"""
171
+ o = o or self.observe()
172
+ c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"])
173
+ hx, hy = o["half"]
174
+ return float(hx * abs(u @ [c, s]) + hy * abs(u @ [-s, c]))
175
+
176
+ # ------------------------------------------------------------ contacts / event monitor
177
+ def _groups(self):
178
+ if not hasattr(self, "_gg"):
179
+ m = self.env.sim.model
180
+ fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")}
181
+ robot = set(envs.robot_geom_ids(self.env))
182
+ self._gg = (fg, robot, set(envs.obj_geom_ids(self.env, "box_1")))
183
+ return self._gg
184
+
185
+ def _finger_landings(self):
186
+ """{'box' | 'table' | 'other': n_fingers} for fingers resting on a top surface (contact normal vertical)."""
187
+ m, d = self.env.sim.model, self.env.sim.data
188
+ fg, robot, box = self._groups()
189
+ out = {}
190
+ for i in range(d.ncon):
191
+ c = d.contact[i]
192
+ if c.geom1 in fg and c.geom2 not in robot:
193
+ f, other = c.geom1, c.geom2
194
+ elif c.geom2 in fg and c.geom1 not in robot:
195
+ f, other = c.geom2, c.geom1
196
+ else:
197
+ continue
198
+ if abs(c.frame[2]) < 0.7:
199
+ continue
200
+ lab = "box" if other in box else ("table" if (m.geom_id2name(other) or "").startswith("table") else "other")
201
+ name = m.geom_id2name(f) or ""
202
+ out.setdefault(lab, set()).add("1" if "finger1" in name else "2")
203
+ return out
204
+
205
+ def _closing_axis(self):
206
+ m, d = self.env.sim.model, self.env.sim.data
207
+ jid = m.joint_name2id(self.env.robots[0].gripper.joints[0])
208
+ a = d.xaxis[jid][:2]
209
+ return a / max(np.linalg.norm(a), 1e-9)
210
+
211
+ def _start_monitor(self):
212
+ b = envs.obj_pos(self.env, "box_1")
213
+ self._mon = dict(rest_z=float(b[2]), start_xy=b[:2].copy(), start_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")),
214
+ max_dz=0.0, top_hit=None, prev=set(), was_held=False)
215
+
216
+ def _monitor_step(self):
217
+ mon = self._mon
218
+ zmin = float(self.corners3d()[:, 2].min())
219
+ mon["max_dz"] = max(mon["max_dz"], zmin - envs.TABLE_Z) # whole box above the table
220
+ hits = self._finger_landings()
221
+ open_ = self.sk is not None and self.sk.gripper_width() > 0.03
222
+ if "box" in hits and "box" not in mon["prev"] and open_: # an open gripper landing on the box top = a grasp
223
+ o = self.observe()
224
+ ca = self._closing_axis()
225
+ e = self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id]
226
+ mon["top_hit"] = dict(span=2 * self.extent_along(ca, o), n_fingers=len(hits["box"]),
227
+ offset=float(np.linalg.norm(e[:2] - o["box_xy"])))
228
+ if "box" in hits and len(hits["box"]) == 2 and mon["top_hit"] is not None and open_:
229
+ mon["top_hit"]["n_fingers"] = 2
230
+ mon["prev"] = set(hits)
231
+
232
+ # ------------------------------------------------------------ outcome / F2
233
+ def outcome(self, inst):
234
+ """Success = the whole box footprint inside the square, box resting on the table, released."""
235
+ envs.settle(self.env, 30)
236
+ env, mon = self.env, self._mon or {}
237
+ o = self.observe()
238
+ b = envs.obj_pos(env, "box_1")
239
+ prot = self.protrusion(o)
240
+ inside = max(prot.values()) <= 0.0
241
+ upright = abs(envs.obj_upright_cos(env, "box_1")) > 0.9
242
+ held = bool(self.sk.holding("box_1")) if self.sk is not None else False
243
+ zmin = float(self.corners3d()[:, 2].min())
244
+ resting = abs(zmin - envs.TABLE_Z) < 0.01
245
+ success = bool(inside and resting and not held)
246
+ rel = o["box_xy"] - o["square_xy"]
247
+ moved = float(np.linalg.norm(o["box_xy"] - mon.get("start_xy", o["box_xy"])))
248
+ turned = float(np.degrees(_wrap_pi(o["box_yaw"] - mon.get("start_yaw", o["box_yaw"])))) if upright else 0.0
249
+ lifted = mon.get("max_dz", 0.0) > 0.01
250
+ top = mon.get("top_hit")
251
+ parts, mode = [], "success"
252
+
253
+ def where():
254
+ return (f"its centre is {100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
255
+ f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the square's centre")
256
+
257
+ def sticking():
258
+ return ", ".join(f"{100 * v:.1f} cm beyond the square's {k} edge" for k, v in
259
+ sorted(prot.items(), key=lambda kv: -kv[1]) if v > 0.0)
260
+
261
+ if success:
262
+ parts.append("The box lies completely inside the square.")
263
+ elif b[2] < envs.TABLE_Z - 0.05:
264
+ mode = "fell_off"
265
+ parts.append("The box fell off the table.")
266
+ elif held:
267
+ mode = "held"
268
+ parts.append(f"The box is still held by the gripper; {where()}.")
269
+ elif not resting:
270
+ mode = "not_resting"
271
+ parts.append(f"The box is not resting on the table (it is propped up or tilted); {where()}.")
272
+ else:
273
+ mode = "outside"
274
+ if top is not None and not lifted:
275
+ mode = "too_wide"
276
+ if top["n_fingers"] >= 2 or top["span"] > GRIP_OPEN:
277
+ parts.append(f"The fingers came down on top of the box instead of on either side of it: along the "
278
+ f"gripper's closing direction the box measures {100 * top['span']:.1f} cm, wider than "
279
+ f"the gripper's maximum opening ({100 * GRIP_OPEN:.1f} cm). The box was not grasped.")
280
+ else:
281
+ parts.append(f"A finger came down on top of the box (the gripper was {100 * top['offset']:.1f} cm "
282
+ f"from the box centre). The box was not grasped.")
283
+ if moved < 0.01:
284
+ mode = "not_moved" if mode == "outside" else mode
285
+ parts.append(f"The box did not move; it sticks out {sticking()}.")
286
+ else:
287
+ parts.append(f"The box was moved {100 * moved:.1f} cm but is not completely inside the square: it "
288
+ f"sticks out {sticking()}; {where()}.")
289
+ if abs(turned) >= 5:
290
+ rot = "counter-clockwise" if turned > 0 else "clockwise"
291
+ parts.append(f"It turned by {abs(turned):.0f} deg ({rot} seen from above).")
292
+ if not success and not upright and mode not in ("fell_off",):
293
+ parts.append("The box is no longer lying on its large bottom face.")
294
+ out = dict(success=success, mode=mode, inside=bool(inside), protrusion=prot, rel=[float(rel[0]), float(rel[1])],
295
+ moved=moved, turned_deg=turned, lifted=bool(lifted), held=held, upright=bool(upright),
296
+ top_hit_span=None if top is None else float(top["span"]),
297
+ terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts))
298
+ self._start_monitor()
299
+ return out
300
+
301
+ # ------------------------------------------------------------ primitives for the scripted policies
302
+ def _yaw_near(self, yaw):
303
+ cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)]
304
+ cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands
305
+ return float(min(cands, key=lambda c: abs(c - self.sk.yaw)))
306
+
307
+ def _align(self, tol=0.03, max_steps=60):
308
+ sk = self.sk
309
+ for _ in range(max_steps):
310
+ R = sk._R() @ sk.eef_mat().T
311
+ if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol:
312
+ break
313
+ sk.hold(1)
314
+
315
+ def _guarded_descent(self, xyz, speed=0.12, max_steps=60):
316
+ """descent that stops when a finger lands on a top surface above the target (contact sensing)"""
317
+ sk = self.sk
318
+ p0 = sk.eef_pos()
319
+ tgt = np.asarray(xyz, float)
320
+ dist = max(np.linalg.norm(tgt - p0), 1e-6)
321
+ R = sk._R()
322
+ for k in range(max_steps):
323
+ ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist)
324
+ sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
325
+ if self._finger_landings() and sk.eef_pos()[2] > tgt[2] + 0.005:
326
+ break
327
+ if np.linalg.norm(tgt - sk.eef_pos()) < 0.003:
328
+ break
329
+ sk.hold(4)
330
+
331
+ def _finger_front(self, direction):
332
+ m, d = self.env.sim.model, self.env.sim.data
333
+ e = self.sk.eef_pos()
334
+ best = 0.0
335
+ for g in range(m.ngeom):
336
+ if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7:
337
+ continue
338
+ mid = m.geom_dataid[g]
339
+ v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]]
340
+ w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e
341
+ best = max(best, float((w[:, :2] @ direction).max()))
342
+ return best
343
+
344
+ def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0, across="narrow"):
345
+ """Top-down grasp across the box's narrow side at its centre (+ offsets); if it is held, put it in the square."""
346
+ sk, o = self.sk, self.observe()
347
+ gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy
348
+ # yaw 0 closes along world y; to close across the narrow side (box local y) use the box yaw
349
+ yaw = self._yaw_near(o["box_yaw"] + (0.0 if across == "narrow" else np.pi / 2) + dyaw)
350
+ sk.set_gripper(False, steps=8)
351
+ sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw)
352
+ self._align()
353
+ self._guarded_descent([gx, gy, Z_GRASP])
354
+ sk.set_gripper(True, steps=15)
355
+ z0 = envs.obj_pos(self.env, "box_1")[2]
356
+ sk.move_to([gx, gy, Z_GRASP + 0.12], speed=0.25)
357
+ if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.06):
358
+ sk.set_gripper(False, steps=8)
359
+ return
360
+ sx, sy = o["square_xy"]
361
+ sk.move_to([sx, sy, Z_GRASP + 0.12])
362
+ sk.move_to([sx, sy, Z_GRASP + 0.005])
363
+ sk.set_gripper(False, steps=12)
364
+ sk.move_to([sx, sy, Z_GRASP + 0.12])
365
+
366
+ def push_stroke(self, u, dist):
367
+ """Closed gripper behind the box face opposite to u (fingers side by side across the push direction), sweep
368
+ along u so that the box moves `dist`, then lift away. Built from move_to + close only."""
369
+ sk, o = self.sk, self.observe()
370
+ u = np.asarray(u, float) / np.linalg.norm(u)
371
+ c = o["box_xy"]
372
+ ext = self.extent_along(u, o)
373
+ yaw = self._yaw_near(float(np.arctan2(u[1], u[0]))) # yaw a: closing axis along (-sin a, cos a), i.e. across u
374
+ sk.set_gripper(True, steps=6)
375
+ face = c - u * ext
376
+ p_hi = face - u * 0.08
377
+ sk.move_to([p_hi[0], p_hi[1], Z_PUSH + 0.10], yaw=yaw)
378
+ self._align()
379
+ front = self._finger_front(u)
380
+ start = face - u * (front + FRONT_GAP)
381
+ stop = face + u * (dist - front)
382
+ sk.move_to([start[0], start[1], Z_PUSH + 0.10])
383
+ sk.move_to([start[0], start[1], Z_PUSH], tol=0.003)
384
+ sk.move_to([stop[0], stop[1], Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400)
385
+ sk.hold(3)
386
+ back = stop - u * 0.02
387
+ sk.move_to([back[0], back[1], Z_PUSH], speed=0.1, max_steps=40)
388
+ sk.move_to([back[0], back[1], Z_PUSH + 0.10], speed=0.25)
389
+
390
+ def push_to(self, goal_xy, max_strokes=4, tol=0.008):
391
+ """Closed-loop push along the box's own axes (each stroke perpendicular to a face keeps the box from turning):
392
+ re-observe after every stroke, push along the axis with the larger remaining error."""
393
+ for _ in range(max_strokes):
394
+ o = self.observe()
395
+ d = np.asarray(goal_xy, float) - o["box_xy"]
396
+ c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"])
397
+ axes = [np.array([c, s]), np.array([-s, c])]
398
+ comps = [float(d @ a) for a in axes]
399
+ i = int(np.argmax(np.abs(comps)))
400
+ if abs(comps[i]) < tol:
401
+ break
402
+ u = axes[i] * np.sign(comps[i])
403
+ self.push_stroke(u, abs(comps[i]))
404
+
405
+ def execute(self, inst, params):
406
+ if params["mode"] == "push":
407
+ goal = np.array(inst["square_xy"]) + np.asarray(params.get("goal_offset", (0.0, 0.0)))
408
+ self.push_to(goal, max_strokes=params.get("strokes", 4))
409
+ else:
410
+ self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0),
411
+ params.get("across", "narrow"))
412
+
413
+ # ------------------------------------------------------------ scripted references
414
+ def default_params(self, inst):
415
+ return dict(mode="grasp")
416
+
417
+ def oracle_params(self, inst):
418
+ return dict(mode="push")
419
+
420
+ def blind_params(self, inst, attempt, rng):
421
+ return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)),
422
+ dyaw=float(rng.normal(0, 0.15)))
423
+
424
+ def adapt_params(self, inst, history):
425
+ """too_wide (fingers on top of the box, span > opening) -> the box cannot be picked up: push it instead.
426
+ A push that leaves the box outside -> push again, aiming past the reported miss (box centre offset)."""
427
+ out, prm = history[-1]["outcome"], history[-1]["params"]
428
+ if prm["mode"] != "push":
429
+ if out["mode"] in ("too_wide", "not_moved"):
430
+ return dict(mode="push")
431
+ return dict(prm)
432
+ if out["mode"] == "outside":
433
+ off = np.asarray(prm.get("goal_offset", (0.0, 0.0))) - 0.5 * np.asarray(out["rel"])
434
+ return dict(mode="push", goal_offset=off.tolist())
435
+ return dict(prm)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l4_diagonal.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L4-B diagonal_fit: put a long bar flat into an open box whose inside is shorter than the bar.
2
+
3
+ Scene: one open box (inner a x b, a slightly longer than b, 3 cm walls) and a long, thin wooden bar
4
+ (L x 1.2 x 1.4 cm) lying on the table in front of it. The bar is 1.2-2.2 cm longer than the box's inside
5
+ length, so it never fits lined up with a side of the box -- it fits only when turned towards the box's
6
+ diagonal, at an angle that depends on a, b and L (36-45 deg off the long side; the fitting window at zero
7
+ centring error is 12-25 deg wide, see task card).
8
+
9
+ Hidden: the exact dimensions (the bar is only 8-17 % longer than the box -- easy to miss at a glance), and
10
+ that a diagonal placement exists. Box and bar are resized per instance by editing geom sizes in sim.model,
11
+ so one env serves every instance (same technique as l4_fit_container).
12
+
13
+ Prior (naive): tidy placement -- line the bar up with the box's long side. It always ends lying across the
14
+ box on the rim (visible). F2 after a failure: where the bar lies, the angle between bar and box, and by how
15
+ much the bar's footprint at that angle is longer than the inside of the box along the box's long / short
16
+ side. A learner can work out the bar length from that and turn the bar towards the diagonal; a second
17
+ failure (angle slightly off) gives the over-length along the other side, which tells it which way to correct.
18
+
19
+ Only move_to / open / close are needed: grasp the bar in the middle, turn the wrist, release above the box.
20
+ """
21
+ import numpy as np
22
+
23
+ from .. import envs
24
+ from ..bddl import write_bddl
25
+ from ..objects import bin_xml, box_xml, register_generated
26
+ from ..skills import _rot_err
27
+ from ..task_base import LFFTask, register_task
28
+
29
+ # bar (local x = long axis); length set per instance
30
+ BAR_W, BAR_H = 0.012, 0.014
31
+ BAR_L_MAX = 0.160
32
+ BAR_RGBA = (0.72, 0.36, 0.14, 1.0)
33
+ # box (local x = long axis of the opening); inner size set per instance
34
+ WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030
35
+ BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height
36
+ RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
37
+ BOX_RGBA = (0.55, 0.62, 0.70, 1.0)
38
+ # sampling ranges (m)
39
+ INNER_A = (0.115, 0.130) # inside length of the box
40
+ A_MINUS_B = (0.004, 0.020) # the box is a little longer than wide
41
+ OVER_LEN = (0.010, 0.020) # bar length minus inside length of the box
42
+ MIN_MARGIN = 0.011 # best-angle clearance (total) the sampler insists on
43
+ MIN_WINDOW_DEG = 8.0 # width of the angle window with >= 6 mm total clearance
44
+ # execution
45
+ Z_GRASP = envs.TABLE_Z + 0.0105 # gripper site; pads span ~0.55-2.25 cm above the table, tips just clear it
46
+ Z_CARRY = envs.TABLE_Z + 0.15
47
+ DROP = 0.010 # bar bottom this far above the rim at release
48
+ PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35)
49
+ PERC_SIGMA = 0.003 # perception noise of the scripted adaptive learner (box inner size, bar width)
50
+
51
+
52
+ MIDPHASE_OFF = True
53
+
54
+
55
+ def disable_midphase(env):
56
+ """Box and bar are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding
57
+ volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered
58
+ size. A box wall moved inwards out of its compiled leaf box is silently skipped by the mid-phase (found on the
59
+ nest_order cups, 2026-10-07: the fingers passed through resized walls). Without the mid-phase MuJoCo tests all
60
+ geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set when resizing)."""
61
+ import mujoco
62
+ m = env.sim.model._model
63
+ m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
64
+
65
+
66
+ def wrap_half(a):
67
+ """angle modulo pi into [-pi/2, pi/2) (bar and box are 180-deg symmetric)"""
68
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
69
+
70
+
71
+ def fold_quarter(a):
72
+ """|angle| between two pi-symmetric axes, in [0, pi/2]"""
73
+ a = abs(wrap_half(a))
74
+ return float(min(a, np.pi - a))
75
+
76
+
77
+ def footprint(L, W, rel):
78
+ """extent of an L x W rectangle turned by rel against the box axes: (along long side, along short side)"""
79
+ c, s = abs(np.cos(rel)), abs(np.sin(rel))
80
+ return L * c + W * s, L * s + W * c
81
+
82
+
83
+ def margins(L, W, a, b, rel):
84
+ e1, e2 = footprint(L, W, rel)
85
+ return a - e1, b - e2
86
+
87
+
88
+ def best_angle(L, W, a, b, n=1801):
89
+ """angle in [0, pi/2] maximising the smaller of the two clearances; returns (angle, clearance, window)"""
90
+ th = np.linspace(0.0, np.pi / 2, n)
91
+ m1, m2 = margins(L, W, a, b, th)
92
+ m = np.minimum(m1, m2)
93
+ i = int(np.argmax(m))
94
+ ok = th[m >= 0.006]
95
+ win = float(np.degrees(ok.max() - ok.min())) if len(ok) else 0.0
96
+ return float(th[i]), float(m[i]), win
97
+
98
+
99
+ def _rect_corners(xy, yaw, half):
100
+ c, s = np.cos(yaw), np.sin(yaw)
101
+ R = np.array([[c, -s], [s, c]])
102
+ pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
103
+ return pts @ R.T + np.asarray(xy)
104
+
105
+
106
+ def _rects_overlap(r1, r2):
107
+ c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
108
+ for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
109
+ ax = np.array([np.cos(yaw), np.sin(yaw)])
110
+ p1, p2 = c1 @ ax, c2 @ ax
111
+ if p1.max() < p2.min() or p2.max() < p1.min():
112
+ return False
113
+ return True
114
+
115
+
116
+ def _rel_dir(dx, dy):
117
+ """robot-centric text for an offset in the world frame (forward = +x, left = +y), ending in 'of' / 'from'"""
118
+ parts = []
119
+ if abs(dx) >= 0.005:
120
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward' if dx > 0 else 'backward'}")
121
+ if abs(dy) >= 0.005:
122
+ parts.append(f"{100 * abs(dy):.1f} cm to the {'left' if dy > 0 else 'right'}")
123
+ return " and ".join(parts) + " of" if parts else "within 0.5 cm of"
124
+
125
+
126
+ def _turn_text(signed_deg):
127
+ """relative orientation of the bar against the box's long side (no absolute angles)"""
128
+ if abs(signed_deg) < 2.0:
129
+ return "lies along the box's long side (within 2 degrees)"
130
+ side = "counterclockwise (towards the left)" if signed_deg > 0 else "clockwise (towards the right)"
131
+ return f"is turned about {abs(signed_deg):.0f} degrees {side}, seen from above, from the box's long side"
132
+
133
+
134
+ @register_task
135
+ class DiagonalFit(LFFTask):
136
+ name = "l4_diagonal_fit"
137
+ level = "L4"
138
+ category = "geometry_inference"
139
+ capabilities = ("Perceive", "Reason")
140
+ instruction = "Put the wooden bar into the box so that it lies flat on the bottom of the box."
141
+ instruction_indirect = "Put the long brown stick into the grey open tray so that it lies flat on the tray's floor."
142
+
143
+ # ------------------------------------------------------------ scene
144
+ def make_bddl(self):
145
+ bar = register_generated("LffDiagBar", box_xml("lff_diag_bar", (BAR_L_MAX / 2, BAR_W / 2, BAR_H / 2),
146
+ BAR_RGBA, density=700))
147
+ box = register_generated("LffDiagBox", bin_xml("lff_diag_box", (0.065, 0.065), WALL_H, wall_t=WALL_T,
148
+ floor_t=FLOOR_T, rgba=BOX_RGBA, density=3000))
149
+ objs = [("bar_1", bar, "bar_region", (0.02, -0.01, 0.04, 0.01)),
150
+ ("box_1", box, "box_region", (-0.19, -0.01, -0.17, 0.01))]
151
+ return write_bddl(self.name, self.instruction, objs)
152
+
153
+ def sample_instance(self, seed):
154
+ rng = np.random.default_rng(seed)
155
+ for _ in range(1000):
156
+ a = float(rng.uniform(*INNER_A))
157
+ b = float(a - rng.uniform(*A_MINUS_B))
158
+ L = float(a + rng.uniform(*OVER_LEN))
159
+ th, m, win = best_angle(L, BAR_W, a, b)
160
+ if m < MIN_MARGIN or win < MIN_WINDOW_DEG:
161
+ continue
162
+ box_xy = [float(rng.uniform(-0.22, -0.13)), float(rng.uniform(-0.10, 0.10))]
163
+ box_yaw = float(rng.uniform(-np.pi / 4, np.pi / 4))
164
+ bar_xy = [float(rng.uniform(-0.01, 0.05)), float(rng.uniform(-0.13, 0.13))]
165
+ bar_yaw = float(rng.uniform(-np.pi / 2, np.pi / 2))
166
+ r_box = (box_xy, box_yaw, (a / 2 + WALL_T + 0.03, b / 2 + WALL_T + 0.03))
167
+ r_bar = (bar_xy, bar_yaw, (L / 2 + 0.01, BAR_W / 2 + 0.03))
168
+ if _rects_overlap(r_box, r_bar):
169
+ continue
170
+ break
171
+ else:
172
+ raise RuntimeError("could not sample an instance")
173
+ prng = np.random.default_rng(seed + 7919)
174
+ perc = [float(a + prng.normal(0, PERC_SIGMA)), float(b + prng.normal(0, PERC_SIGMA)),
175
+ float(BAR_W + prng.normal(0, PERC_SIGMA / 2))]
176
+ return dict(seed=int(seed), inner=[a, b], bar_len=L, bar_xy=bar_xy, bar_yaw=bar_yaw, box_xy=box_xy,
177
+ box_yaw=box_yaw, fit_angle_deg=float(np.degrees(th)), fit_margin_cm=float(100 * m),
178
+ fit_window_deg=win, _perc=perc)
179
+
180
+ def _reshape_box(self, a, b):
181
+ ix, iy, H = a / 2, b / 2, BOX_HALF_H
182
+ parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
183
+ ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
184
+ ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
185
+ ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
186
+ ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
187
+ m = self.env.sim.model
188
+ o = self.env.objects_dict["box_1"]
189
+ for names in (o.contact_geoms, o.visual_geoms):
190
+ assert len(names) == len(parts), names
191
+ for k, n in enumerate(names):
192
+ g = m.geom_name2id(n)
193
+ pos, size = parts[k]
194
+ m.geom_pos[g] = pos
195
+ m.geom_size[g] = size
196
+ m.geom_rbound[g] = float(np.linalg.norm(size))
197
+ m.geom_aabb[g] = [0, 0, 0, *size]
198
+
199
+ def _resize_bar(self, L):
200
+ m = self.env.sim.model
201
+ o = self.env.objects_dict["bar_1"]
202
+ for n in list(o.contact_geoms) + list(o.visual_geoms):
203
+ g = m.geom_name2id(n)
204
+ m.geom_size[g] = [L / 2, BAR_W / 2, BAR_H / 2]
205
+ m.geom_rbound[g] = float(np.linalg.norm(m.geom_size[g]))
206
+ m.geom_aabb[g] = [0, 0, 0, *m.geom_size[g]]
207
+ # keep the mass of the resized bar consistent with its volume (density 700); the geoms live in the
208
+ # child body "object", not in the root body that carries the free joint
209
+ bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])])
210
+ mass = 700.0 * L * BAR_W * BAR_H
211
+ m.body_mass[bid] = mass
212
+ m.body_inertia[bid] = mass / 12.0 * np.array([BAR_W ** 2 + BAR_H ** 2, L ** 2 + BAR_H ** 2,
213
+ L ** 2 + BAR_W ** 2])
214
+
215
+ def apply_instance(self, inst):
216
+ if MIDPHASE_OFF:
217
+ disable_midphase(self.env)
218
+ self._reshape_box(*inst["inner"])
219
+ self._resize_bar(inst["bar_len"])
220
+ envs.set_obj_pose(self.env, "box_1", [*inst["box_xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005],
221
+ yaw=inst["box_yaw"])
222
+ envs.set_obj_pose(self.env, "bar_1", [*inst["bar_xy"], envs.TABLE_Z + BAR_H / 2 + 0.0005],
223
+ yaw=inst["bar_yaw"])
224
+
225
+ # ------------------------------------------------------------ outcome
226
+ def _pose(self, name):
227
+ bid = envs.body_id(self.env, name)
228
+ R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
229
+ return self.env.sim.data.body_xpos[bid].copy(), R
230
+
231
+ def outcome(self, inst):
232
+ envs.settle(self.env, 40)
233
+ a, b = inst["inner"]
234
+ L = inst["bar_len"]
235
+ p, R = self._pose("bar_1")
236
+ ax = R[:, 0]
237
+ bar_yaw = float(np.arctan2(ax[1], ax[0]))
238
+ tilt = float(np.degrees(np.arcsin(min(1.0, abs(ax[2]))))) # long axis vs horizontal
239
+ c, Rb = self._pose("box_1")
240
+ byaw = float(np.arctan2(Rb[1, 0], Rb[0, 0]))
241
+ btilt = float(np.degrees(np.arccos(np.clip(Rb[2, 2], -1, 1))))
242
+ held = bool(self.sk is not None and self.sk.holding("bar_1"))
243
+ rel = fold_quarter(bar_yaw - byaw)
244
+ # bar footprint corners in the box frame
245
+ Rz = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]])
246
+ corners = _rect_corners(p[:2], bar_yaw, (L / 2 * np.cos(np.radians(tilt)), BAR_W / 2))
247
+ loc = (corners - c[:2]) @ Rz.T
248
+ out_x = float(np.max(np.abs(loc[:, 0])) - a / 2)
249
+ out_y = float(np.max(np.abs(loc[:, 1])) - b / 2)
250
+ centre = Rz @ (p[:2] - c[:2])
251
+ floor_top = c[2] - BOX_HALF_H + FLOOR_T
252
+ height = float(envs.obj_min_z(self.env, "bar_1") - floor_top)
253
+ in_opening = out_x <= 0.002 and out_y <= 0.002
254
+ on_floor = height < 0.005 and tilt < 6.0
255
+ success = bool(in_opening and on_floor and not held and btilt < 10.0)
256
+ m_long, m_short = margins(L, BAR_W, a, b, rel)
257
+ fb = dict(rel_deg=round(float(np.degrees(rel)), 1),
258
+ over_long_cm=round(-100 * m_long, 1) if m_long < -0.001 else None,
259
+ over_short_cm=round(-100 * m_short, 1) if m_short < -0.001 else None,
260
+ spare_long_cm=round(100 * max(m_long, 0.0), 1) if m_long >= -0.001 else None,
261
+ spare_short_cm=round(100 * max(m_short, 0.0), 1) if m_short >= -0.001 else None,
262
+ centre_offset_cm=[round(100 * float(centre[0]), 1), round(100 * float(centre[1]), 1)])
263
+ res = dict(success=success, height_cm=round(100 * height, 2), tilt_deg=round(tilt, 1), held=held,
264
+ rel_deg=fb["rel_deg"], bar_xy=[float(p[0]), float(p[1])], feedback=fb)
265
+ signed = float(np.degrees(wrap_half(bar_yaw - byaw)))
266
+ fb["rel_signed_deg"] = round(signed, 1)
267
+ off_w = p[:2] - c[:2] # bar centre relative to the box centre, world axes (only relative values are reported)
268
+ if held:
269
+ res["detail"] = "The bar is still in the gripper."
270
+ res["failure"] = "held"
271
+ return res
272
+ over_box = abs(centre[0]) < a / 2 + WALL_T and abs(centre[1]) < b / 2 + WALL_T
273
+ on_table = envs.obj_min_z(self.env, "bar_1") < envs.TABLE_Z + 0.008 # (floor_top is FLOOR_T above the table)
274
+ if not over_box and on_table:
275
+ res["detail"] = (f"The bar is not in the box: it is lying on the table, its centre "
276
+ f"{_rel_dir(*off_w)} the box's centre.")
277
+ res["failure"] = "table"
278
+ return res
279
+ if success:
280
+ res["detail"] = "The bar is lying flat on the bottom of the box."
281
+ res["failure"] = None
282
+ return res
283
+ if not over_box:
284
+ res["detail"] = (f"The bar is not in the box: it ended partly on the box's rim, "
285
+ f"{100 * (p[2] - envs.TABLE_Z):.1f} cm above the table, its centre "
286
+ f"{_rel_dir(*off_w)} the box's centre.")
287
+ res["failure"] = "off"
288
+ return res
289
+ pose_txt = (f"lying across the top of the box on its rim, {100 * height:.1f} cm above the box floor"
290
+ if tilt < 6.0 else
291
+ f"tilted about {tilt:.0f} degrees, with one end down inside the box and the other end on the rim")
292
+ txt = f"The bar did not go in: it is {pose_txt}. The bar {_turn_text(signed)}."
293
+ parts = []
294
+ if fb["over_long_cm"]:
295
+ parts.append(f"{fb['over_long_cm']:.1f} cm longer than the inside of the box along the box's long side")
296
+ if fb["over_short_cm"]:
297
+ parts.append(f"{fb['over_short_cm']:.1f} cm longer than the inside of the box along the box's short side")
298
+ if parts:
299
+ txt += " At that angle the bar's footprint is " + " and ".join(parts) + "."
300
+ else:
301
+ txt += (f" At that angle the bar's footprint is smaller than the opening (spare {fb['spare_long_cm']:.1f} cm "
302
+ f"along the long side, {fb['spare_short_cm']:.1f} cm along the short side), but it caught on the "
303
+ f"rim (bar centre {_rel_dir(*off_w)} the box's centre).")
304
+ res["detail"] = txt
305
+ res["failure"] = "rim"
306
+ return res
307
+
308
+ # ------------------------------------------------------------ execution
309
+ def execute(self, inst, params):
310
+ """params: rel_yaw (rad) = angle of the bar's long axis against the box's long side at release.
311
+ Optional (tolerance checks): dx / dy release offset of the bar centre from the box centre along the
312
+ box's long / short axis (m); drop = bar bottom above the rim at release (m)."""
313
+ sk, env = self.sk, self.env
314
+ px, py = inst["bar_xy"]
315
+ g0 = wrap_half(inst["bar_yaw"]) # yaw 0 closes the fingers along world y = across a bar lying along x
316
+ sk.set_gripper(False, steps=5)
317
+ sk.move_to([px, py, Z_GRASP + 0.10], yaw=g0)
318
+ sk.move_to([px, py, Z_GRASP], tol=0.003)
319
+ sk.set_gripper(True, steps=15)
320
+ sk.move_to([px, py, Z_CARRY], speed=0.25)
321
+ byaw = inst["box_yaw"]
322
+ c, s = np.cos(byaw), np.sin(byaw)
323
+ dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
324
+ bx, by = inst["box_xy"][0] + c * dx - s * dy, inst["box_xy"][1] + s * dx + c * dy
325
+ sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(byaw + params["rel_yaw"]))
326
+ off = envs.obj_pos(env, "bar_1") - sk.eef_pos()
327
+ drop = params.get("drop", DROP)
328
+ sk.move_to([bx - off[0], by - off[1], RIM_Z + drop + BAR_H / 2 + 0.04 - off[2]], tol=0.003)
329
+ tgt = self._servo_bar([bx, by], RIM_Z + drop)
330
+ sk.grip = -1.0
331
+ self._hold_at(tgt, 12)
332
+ sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
333
+ sk.move_to(list(PARK), yaw=0.0)
334
+
335
+ def _hold_at(self, target, steps):
336
+ sk = self.sk
337
+ R = sk._R()
338
+ for _ in range(steps):
339
+ sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
340
+
341
+ def _servo_bar(self, xy, z_bottom, max_steps=60, tol=0.0015):
342
+ """closed loop on the held bar's centre (scripted policies only)"""
343
+ sk = self.sk
344
+ R = sk._R()
345
+ goal = np.array([xy[0], xy[1], z_bottom + BAR_H / 2])
346
+ tgt = e_prev = sk.eef_pos()
347
+ for i in range(max_steps):
348
+ pb, e = envs.obj_pos(self.env, "bar_1"), sk.eef_pos()
349
+ if i >= 8 and np.linalg.norm(pb - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
350
+ break
351
+ tgt = goal - (pb - e)
352
+ sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
353
+ e_prev = e
354
+ return tgt
355
+
356
+ # ------------------------------------------------------------ scripted policies
357
+ def _signed(self, inst, th):
358
+ """+th or -th, whichever needs the smaller wrist turn from the bar's current orientation"""
359
+ cur = wrap_half(inst["bar_yaw"] - inst["box_yaw"])
360
+ return min((th, -th), key=lambda t: abs(wrap_half(t - cur)))
361
+
362
+ def default_params(self, inst):
363
+ """tidy prior: bar lined up with the box's long side"""
364
+ return dict(rel_yaw=0.0)
365
+
366
+ def oracle_params(self, inst):
367
+ return dict(rel_yaw=self._signed(inst, np.radians(inst["fit_angle_deg"])))
368
+
369
+ def blind_params(self, inst, attempt, rng):
370
+ """no history: the prior again with a little jitter in angle and position"""
371
+ return dict(rel_yaw=float(rng.normal(0.0, np.radians(4.0))), dx=float(rng.normal(0, 0.003)),
372
+ dy=float(rng.normal(0, 0.003)))
373
+
374
+ def adapt_params(self, inst, history):
375
+ """Scripted learner on F2 feedback.
376
+
377
+ Knows the box's inner size and the bar's width only through noisy perception (inst['_perc'],
378
+ sigma = PERC_SIGMA), not the bar's length. Every 'X cm longer than the inside along the long / short side
379
+ at angle d' gives an equation for the bar length L (L cos d + W sin d = a + X, or L sin d + W cos d = b + X);
380
+ 'spare' values give the same with a negative X. It takes the largest length estimate (conservative) and turns
381
+ the bar to the angle with the largest clearance for that length; if the last attempt was already at a
382
+ feasible angle and only missed the centre, it keeps the angle."""
383
+ a, b, W = inst["_perc"]
384
+ Ls = []
385
+ for h in history:
386
+ fb = h["outcome"].get("feedback") or {}
387
+ if h["outcome"].get("failure") != "rim":
388
+ continue
389
+ d = np.radians(fb["rel_deg"])
390
+ c, s = np.cos(d), np.sin(d)
391
+ if c > 0.3:
392
+ x = fb["over_long_cm"] if fb["over_long_cm"] is not None else -fb["spare_long_cm"]
393
+ Ls.append((a + x / 100 - W * s) / c)
394
+ if s > 0.3:
395
+ x = fb["over_short_cm"] if fb["over_short_cm"] is not None else -fb["spare_short_cm"]
396
+ Ls.append((b + x / 100 - W * c) / s)
397
+ L_est = max(Ls) if Ls else a + 0.015
398
+ th, m, _ = best_angle(L_est, W, a, b)
399
+ return dict(rel_yaw=self._signed(inst, th), L_est=float(L_est))
400
+
401
+ def random_yaw_params(self, inst, history, rng):
402
+ """sensitivity variant: a random orientation each retry, no history"""
403
+ return dict(rel_yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
404
+
405
+ EXTRA_KINDS = ("random_yaw",)
406
+
407
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
408
+ if kind not in self.EXTRA_KINDS:
409
+ return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
410
+ k = k or self.max_attempts
411
+ rng = np.random.default_rng(seed)
412
+ history = []
413
+ for a in range(k):
414
+ self.reset_instance(inst)
415
+ params = self.default_params(inst) if a == 0 else self.random_yaw_params(inst, history, rng)
416
+ self.execute(inst, params)
417
+ out = self.outcome(inst)
418
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
419
+ if on_attempt:
420
+ on_attempt(a, params, out)
421
+ if out["success"]:
422
+ break
423
+ return history
424
+
425
+
426
+ # ---------------------------------------------------------------- physical validity checks
427
+ def physics_check(seed0=1000, n=10, out=None):
428
+ """Release angles 0 / 90 deg (must fail), +-best angle (must succeed) and best +- 6 deg (report)."""
429
+ import json
430
+ task = DiagonalFit()
431
+ rows = []
432
+ for seed in range(seed0, seed0 + n):
433
+ inst = task.sample_instance(seed)
434
+ th = np.radians(inst["fit_angle_deg"])
435
+ for name, rel, expect in [("aligned", 0.0, False), ("crossed", np.pi / 2, False), ("best+", th, True),
436
+ ("best-", -th, True), ("best-6", th - np.radians(6), None),
437
+ ("best+6", th + np.radians(6), None)]:
438
+ task.reset_instance(inst)
439
+ task.execute(inst, dict(rel_yaw=float(rel)))
440
+ o = task.outcome(inst)
441
+ rows.append(dict(seed=seed, case=name, rel_deg=float(np.degrees(rel)), success=o["success"], expect=expect,
442
+ failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"],
443
+ inner_cm=[round(100 * v, 2) for v in inst["inner"]], bar_cm=round(100 * inst["bar_len"], 2),
444
+ fit_margin_cm=round(inst["fit_margin_cm"], 2), fit_window_deg=round(inst["fit_window_deg"], 1)))
445
+ flag = "" if expect is None or expect == o["success"] else " <-- MISMATCH"
446
+ print(f"seed {seed} {name:8s} rel={np.degrees(rel):+6.1f} succ={o['success']} h={o['height_cm']} "
447
+ f"tilt={o['tilt_deg']} margin={inst['fit_margin_cm']:.2f}cm win={inst['fit_window_deg']:.1f}{flag}",
448
+ flush=True)
449
+ if out:
450
+ with open(out, "w") as f:
451
+ json.dump(rows, f, indent=1)
452
+ bad = [r for r in rows if r["expect"] is not None and r["expect"] != r["success"]]
453
+ print("total", len(rows), "mismatches", len(bad))
454
+ return rows
455
+
456
+
457
+ def window_check(seed0=1000, n=6, out=None):
458
+ """Release angle swept around the best angle (-16..+16 deg, step 2), bar centred: the physical fitting window
459
+ against the geometric clearance."""
460
+ import json
461
+ task = DiagonalFit()
462
+ rows = []
463
+ for seed in range(seed0, seed0 + n):
464
+ inst = task.sample_instance(seed)
465
+ th = inst["fit_angle_deg"]
466
+ L, (a, b) = inst["bar_len"], inst["inner"]
467
+ for d in range(-16, 17, 2):
468
+ rel = np.radians(th + d)
469
+ task.reset_instance(inst)
470
+ task.execute(inst, dict(rel_yaw=float(rel)))
471
+ o = task.outcome(inst)
472
+ m1, m2 = margins(L, BAR_W, a, b, rel)
473
+ rows.append(dict(seed=seed, d_deg=d, rel_deg=round(th + d, 1), success=o["success"],
474
+ clearance_mm=round(1000 * float(min(m1, m2)), 1)))
475
+ print(f"seed {seed} best={th:.1f} " + " ".join(f"{r['d_deg']:+d}:{'S' if r['success'] else '.'}"
476
+ for r in rows if r["seed"] == seed), flush=True)
477
+ if out:
478
+ with open(out, "w") as f:
479
+ json.dump(rows, f, indent=1)
480
+ return rows
481
+
482
+
483
+ def robustness_check(seed0=1000, n=6, out=None):
484
+ """Execution errors at the best angle: release off-centre along the box's long / short axis, angle off by
485
+ +-4 / +-8 deg, released 3 cm above the rim."""
486
+ import json
487
+ task = DiagonalFit()
488
+ rows = []
489
+ cases = [("best", {}), ("dx4", dict(dx=0.004)), ("dy4", dict(dy=0.004)), ("dx7", dict(dx=0.007)),
490
+ ("dy7", dict(dy=0.007)), ("ang+4", dict(dang=4)), ("ang-4", dict(dang=-4)), ("ang+8", dict(dang=8)),
491
+ ("ang-8", dict(dang=-8)), ("drop3cm", dict(drop=0.03)), ("dx4_ang4_drop3", dict(dx=0.004, dang=4, drop=0.03))]
492
+ for seed in range(seed0, seed0 + n):
493
+ inst = task.sample_instance(seed)
494
+ th = inst["fit_angle_deg"]
495
+ for name, c in cases:
496
+ params = dict(rel_yaw=float(np.radians(th + c.get("dang", 0))))
497
+ params.update({k: v for k, v in c.items() if k != "dang"})
498
+ task.reset_instance(inst)
499
+ task.execute(inst, params)
500
+ o = task.outcome(inst)
501
+ rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"],
502
+ fit_margin_cm=round(inst["fit_margin_cm"], 2)))
503
+ print(f"seed {seed} {name:15s} succ={o['success']} | {o['detail'][:160]}", flush=True)
504
+ if out:
505
+ with open(out, "w") as f:
506
+ json.dump(rows, f, indent=1)
507
+ for name, _ in cases:
508
+ r = [x["success"] for x in rows if x["case"] == name]
509
+ print(f"{name:15s} {sum(r)}/{len(r)}")
510
+ return rows
511
+
512
+
513
+ if __name__ == "__main__":
514
+ # python -m lffbench.tasks.l4_diagonal physics results/l4_diagonal_fit/physics_check.json
515
+ import sys
516
+ # python -m lffbench.tasks.l4_diagonal window results/l4_diagonal_fit/window_check.json
517
+ # python -m lffbench.tasks.l4_diagonal robust results/l4_diagonal_fit/robustness_check.json
518
+ if sys.argv[1] == "physics":
519
+ physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None,
520
+ n=int(sys.argv[3]) if len(sys.argv) > 3 else 10)
521
+ elif sys.argv[1] == "window":
522
+ window_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6)
523
+ elif sys.argv[1] == "robust":
524
+ robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py ADDED
@@ -0,0 +1,954 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH false_bottom_lid: open a lidded wooden box, put a tall red block and two blue cubes in, close the lid -- in half
2
+ of the boxes a hidden false bottom makes the box too shallow for the block standing upright, so the lid comes down on
3
+ the block and stays open; the block must be laid on its side.
4
+
5
+ Family: long-horizon common sense + self-disturbance ("state_restoration"): the agent's own normal action (placing the
6
+ block upright, as it was found) makes the last stage (lid closed) impossible; it has to notice the blocked lid, take
7
+ the block out again, lay it down and close the lid (within an attempt), or lay the block down from the start in this
8
+ box (across attempts).
9
+
10
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
11
+ * a wooden box (fixture): outer 20.6 cm (forward-back) x 13.6 cm (left-right) x 9 cm high, walls 0.8 cm; the
12
+ inside is pure black and matte (walls' inner faces, floor and false bottom). The lid (0.6 cm, wood, 0.15 kg) is
13
+ hinged along the box's left or right long edge; a black ball knob sticks out of the middle of the opposite edge.
14
+ Opened past upright the lid falls over to the hinge side and hangs on its stop (182-192 deg) just below
15
+ horizontal beside the box, below every transit;
16
+ * a red block 4 x 4 x 7.5 cm standing upright and two 4 cm blue cubes, in a row in front of the box (robot side),
17
+ on 3 of 4 slots 16 cm apart.
18
+
19
+ Hidden variable: the box's inner depth. With a false bottom (10 of every 20 consecutive seeds) the floor is 4.5 cm
20
+ below the rim instead of 8.4 cm. The outside is identical and the inside is dark: from above (wrist camera) and from
21
+ the far camera the floor height is not readable (measured: renders of the open, empty box with and without the false
22
+ bottom are pixel-identical in both cameras). The Panda hand (21 cm along the finger axis) cannot go below the rim,
23
+ so the fingertips cannot touch the false bottom either. Upright the block is 7.5 cm tall: it fits the deep box (top 0.9 cm
24
+ below the rim) but stands 3 cm above the rim on the false bottom; lying down (4 cm) it fits both.
25
+
26
+ Why the natural action fails: the block is found standing; carried top-down by a gripper that can only turn about the
27
+ vertical, it is naturally put in standing. On a false bottom the closing lid then comes down on the block's top and
28
+ stays open at ~28-41 deg (measured; clearly visible in both cameras). What must be
29
+ learned: take the block out, lay it on its side (tip it over on the table by pushing its upper part with the closed
30
+ fingers, then pick it up lying) and put it in lying (within the attempt), or lay it down before putting it in (across
31
+ attempts).
32
+
33
+ Lid mechanics for agents (inherited from lh_lid_box's `LidSkills`, generalized to a hinge axis along x): while the
34
+ knob is held, a commanded straight move is projected onto the knob's circle around the hinge (at most 1 cm per control
35
+ step), so "up, then over the hinge, release" opens the lid and "up, then away from the hinge, release" closes it.
36
+
37
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (lid closed, all
38
+ three items inside the box below the rim, nothing held, scene static) plus an event log for the server log
39
+ (per-item in_box achieved / lost / restored, lid opened / closed / blocked, red block laid down / stood up); F1 gives
40
+ the agent only success / failure.
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _SOLID, _fmt, box_xml, register_generated
47
+ from ..skills import Skills
48
+ from ..task_base import LFFTask, register_task
49
+ from .lh_lid_box import SMAX, LidSkills, _fb, _lr
50
+
51
+ # ---------------------------------------------------------------- geometry / physics (box frame: hinge along local y
52
+ # at the local +x edge; the box is turned by +-90 deg so that the hinge runs forward-back on the left or right side)
53
+ BOX = "box_1"
54
+ BOX_MODEL = "lff_fbl_box"
55
+ S_IN, L_IN = 0.120, 0.190 # inner cavity across the hinge (local x -> world y) and along it (local y -> world x);
56
+ # roomy enough that closed fingers (~4 cm out from a held 4 cm item) stay off the walls
57
+ WALL_T, WALL_H, FLOOR_T = 0.008, 0.090, 0.006
58
+ FB_DEPTH = 0.045 # inner depth with the false bottom (floor 4.5 cm above the table)
59
+ LX, LY = S_IN + 2 * WALL_T, L_IN + 2 * WALL_T
60
+ LID_T, LID_MASS = 0.006, 0.15
61
+ KNOB_R, STEM_L = 0.013, 0.032
62
+ HINGE_DAMP, HINGE_FRIC = 0.002, 0.002
63
+ LID_SOLREF, LID_SOLIMP = "0.005 1", "0.99 0.998 0.001"
64
+ BACKOFF = 0.003 # m per control step: a hand pressing on a lid that rests on an item yields
65
+ STOP = (182.0, 192.0) # lid opening stop (deg, uniform): opened, the lid hangs just below horizontal beside the box
66
+ # (free end 6.5-7 cm up), below every transit; at < 180 deg its free end and knob rise to 12-14 cm
67
+ # and a carried item sweeps into them (measured)
68
+ WOOD = (0.55, 0.38, 0.22, 1.0)
69
+ LID_RGBA = (0.70, 0.52, 0.32, 1.0)
70
+ DARK = (0.0, 0.0, 0.0, 1.0) # pure black, matte (no specular): every lit shade is 0, so the floor height is invisible
71
+ KNOB_RGBA = (0.10, 0.10, 0.11, 1.0)
72
+
73
+ RED = "red_block_1"
74
+ BLUES = ("blue_cube_1", "blue_cube_2")
75
+ ITEMS = (RED,) + BLUES
76
+ RED_W, RED_H = 0.040, 0.075
77
+ CUBE_E = 0.040
78
+ RED_DENS, CUBE_DENS = 600.0, 500.0 # 72 g, 32 g
79
+ ITEM_MU = 0.8
80
+ P_FB = 0.5
81
+
82
+ IN_TOL = 0.004 # an item's footprint corners may reach this far past the inner walls (an item leaning on a wall
83
+ # touches it; measured: a cube dropped into the deep box ended tilted 52 deg against the front wall)
84
+ RIM_TOL = 0.004 # item top at most this far above the rim
85
+ LID_CLOSED = np.radians(5.0)
86
+ DEBOUNCE = 6 # predicate checks (every 0.1 s)
87
+ UPRIGHT_COS, LYING_COS = np.cos(np.radians(25.0)), np.cos(np.radians(65.0))
88
+
89
+ Z_CARRY = 0.16 # scripted transit height of the grasp point above the table when carrying an item (Sonnet: 11-20 cm)
90
+ Z_HAND_MIN = WALL_H - 0.024 + 0.006 # lowest grasp point over the box: the Panda hand (2.4 cm above the grasp point, 21 cm
91
+ # along the finger axis) must stay above the rim
92
+ # scripted in-box slots along the box's long axis (u, forward-back, box centre = 0), all at v = 0 (centre line).
93
+ # The lying red block lies across the box (axis left-right) and is held with the fingers closing forward-back, so its
94
+ # slot is 1 cm further in: fingers 4 cm out from its centre stay 1 cm off the back wall (measured: at the upright
95
+ # slot the back finger caught the wall and dropped the block)
96
+ SLOT_U = {"red_upright": -0.0575, "red_lying": -0.0475, "blue_cube_1": 0.005, "blue_cube_2": 0.055}
97
+ START_Y = (-0.24, -0.08, 0.08, 0.24)
98
+ START_X = -0.34
99
+
100
+
101
+ def fb_box_xml(name):
102
+ hx, hy = LX / 2, LY / 2
103
+ col = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)),
104
+ ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
105
+ ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
106
+ ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)),
107
+ ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))]
108
+ g = []
109
+ # box: contype 2 / conaffinity 1, lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the
110
+ # hinge limit holds it closed) but both collide with the robot, the table and the free items (as in lh_lid_box)
111
+ for k, (pos, s) in enumerate(col):
112
+ g.append(f'<geom name="{name}_w{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(s)}" rgba="{_fmt(WOOD)}" '
113
+ f'friction="0.8 0.005 0.0001" {_SOLID} contype="2" conaffinity="1" group="0"/>')
114
+ fb_top = WALL_H - FB_DEPTH
115
+ fbh = (fb_top - FLOOR_T) / 2
116
+ fb_pos, fb_size = (0, 0, FLOOR_T + fbh), (hx - WALL_T, hy - WALL_T, fbh)
117
+ # the false bottom: always compiled, its collision switched on / off per instance (contype / conaffinity), so no
118
+ # geom moves at runtime and the compiled bounding volumes stay valid (see lh_fence's refit_bvh note)
119
+ g.append(f'<geom name="{name}_fb" type="box" pos="{_fmt(fb_pos)}" size="{_fmt(fb_size)}" rgba="{_fmt(DARK)}" '
120
+ f'friction="0.8 0.005 0.0001" {_SOLID} contype="2" conaffinity="1" group="0"/>')
121
+ th = WALL_T / 2
122
+ vis = [((hx - th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD),
123
+ ((hx - WALL_T + th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK),
124
+ ((-hx + th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD),
125
+ ((-hx + WALL_T - th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK),
126
+ ((0, hy - th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD),
127
+ ((0, hy - WALL_T + th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK),
128
+ ((0, -hy + th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD),
129
+ ((0, -hy + WALL_T - th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK),
130
+ ((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2), WOOD),
131
+ ((0, 0, FLOOR_T + 0.0005), (hx - WALL_T, hy - WALL_T, 0.0005), DARK)]
132
+ for p, s, c in vis:
133
+ mat = f' material="{name}_dark"' if c == DARK else ""
134
+ g.append(f'<geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}"{mat} contype="0" conaffinity="0" '
135
+ f'group="1"/>')
136
+ g.append(f'<geom name="{name}_fbvis" type="box" pos="{_fmt(fb_pos)}" size="{_fmt(fb_size)}" rgba="{_fmt(DARK)}" '
137
+ f'material="{name}_dark" contype="0" conaffinity="0" group="1"/>')
138
+ m, L = LID_MASS, LX
139
+ lid_c = (-L / 2, 0, LID_T / 2)
140
+ lid_s = (L / 2, hy, LID_T / 2)
141
+ stem = (-L - STEM_L / 2, 0, LID_T / 2)
142
+ ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2)
143
+ lid = [f'<inertial pos="{_fmt(lid_c)}" mass="{m}" diaginertia="{m * (LY ** 2 + LID_T ** 2) / 12:.6f} '
144
+ f'{m * (L ** 2 + LID_T ** 2) / 12:.6f} {m * (LY ** 2 + L ** 2) / 12:.6f}"/>',
145
+ f'<joint name="{name}_hinge" type="hinge" axis="0 1 0" pos="0 0 0" limited="true" range="0 3.0" '
146
+ f'damping="{HINGE_DAMP}" frictionloss="{HINGE_FRIC}" armature="0.0005"/>',
147
+ # stiffer contacts for the lid plate, and solmix so that they win against the items' (default, soft) ones:
148
+ # with soft contacts an arm pressing the lid down onto the 72 g block pushed the lid through it (measured)
149
+ f'<geom name="{name}_lid" type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(LID_RGBA)}" mass="0" '
150
+ f'friction="0.8 0.005 0.0001" solref="{LID_SOLREF}" solimp="{LID_SOLIMP}" solmix="1000" contype="4" '
151
+ f'conaffinity="1" group="0"/>',
152
+ f'<geom type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(LID_RGBA)}" contype="0" conaffinity="0" group="1"/>',
153
+ f'<geom name="{name}_stem" type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
154
+ f'rgba="{_fmt(KNOB_RGBA)}" mass="0" friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
155
+ f'<geom type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
156
+ f'rgba="{_fmt(KNOB_RGBA)}" contype="0" conaffinity="0" group="1"/>',
157
+ f'<geom name="{name}_knob" type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(KNOB_RGBA)}" mass="0" '
158
+ f'friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
159
+ f'<geom type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(KNOB_RGBA)}" contype="0" conaffinity="0" group="1"/>']
160
+ shell = "\n ".join(g)
161
+ lid_xml = "\n ".join(lid)
162
+ # matte near-black inside (no specular highlight): the floor height is not readable from above
163
+ return f"""<mujoco model="{name}">
164
+ <asset>
165
+ <material name="{name}_dark" rgba="{_fmt(DARK)}" specular="0" shininess="0" reflectance="0"/>
166
+ </asset>
167
+ <worldbody>
168
+ <body>
169
+ <body name="object">
170
+ {shell}
171
+ <body name="lid" pos="{hx:.4f} 0 {WALL_H:.4f}">
172
+ {lid_xml}
173
+ </body>
174
+ </body>
175
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
176
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {WALL_H:.4f}" name="top_site" />
177
+ <site rgba="0 0 0 0" size="0.005" pos="{hx:.4f} {hy:.4f} 0" name="horizontal_radius_site" />
178
+ </body>
179
+ </worldbody>
180
+ </mujoco>"""
181
+
182
+
183
+ class FBLidSkills(LidSkills):
184
+ """LidSkills with the hinge axis in any horizontal direction (here forward-back), plus the task's per-step
185
+ monitor. While the knob is held, the commanded displacement is projected onto the tangent of the knob's circle
186
+ about the hinge (<= SMAX per control step), with radial and axial corrections."""
187
+
188
+ def _hinge_frame(self, e):
189
+ h, a = self.task.hinge_point(), self.task.hinge_axis()
190
+ v = e - h
191
+ al = float(v @ a)
192
+ r = v - al * a
193
+ return a, al, r, max(float(np.linalg.norm(r)), 1e-6)
194
+
195
+ def _act(self, dpos, drot, grip):
196
+ if self.latched:
197
+ e = self.eef_pos()
198
+ if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035:
199
+ self.latched = False # opened, or the knob slipped out of the fingers
200
+ else:
201
+ a, al, r, rn = self._hinge_frame(e)
202
+ t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn # knob motion for an opening lid
203
+ s = float(np.clip(np.asarray(dpos) @ t_open, -SMAX, SMAX))
204
+ if s < 0 and self.task.lid_contacts():
205
+ s = 0.0 # compliant wrist: it does not force the lid down onto an item (else the lid tunnels through it)
206
+ dpos = s * t_open + (self.rad0 - rn) * r / rn + (self.y0 - al) * a
207
+ self.knob_steps += 1
208
+ else:
209
+ p = self.task.robot_lid_contact()
210
+ if p is not None and self.task.lid_contacts():
211
+ # the same limit for a hand pressing on the lid itself: no push towards closing while the lid rests on
212
+ # an item (measured without it: pressing 5 cm "into" a lid lying on the block left the block poking
213
+ # through the lid)
214
+ _, _, r, rn = self._hinge_frame(p)
215
+ t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn
216
+ sc = float(np.asarray(dpos) @ t_open)
217
+ if sc < 0: # drop the closing component and yield a little (a force-limited arm gives way)
218
+ dpos = np.asarray(dpos) + (BACKOFF - sc) * t_open
219
+ Skills._act(self, dpos, drot, grip)
220
+ self.task.monitor_step()
221
+
222
+ def set_gripper(self, close, steps=15):
223
+ rep = Skills.set_gripper(self, close, steps)
224
+ if close and self.holding_knob():
225
+ _, al, _, rn = self._hinge_frame(self.eef_pos())
226
+ self.latched, self.rad0, self.y0 = True, rn, al
227
+ self.knob_grasps += 1
228
+ elif not close:
229
+ self.latched = False
230
+ return rep
231
+
232
+
233
+ def _rot(yaw):
234
+ c, s = np.cos(yaw), np.sin(yaw)
235
+ return np.array([[c, -s], [s, c]])
236
+
237
+
238
+ @register_task
239
+ class FalseBottomLid(LFFTask):
240
+ name = "lh_false_bottom_lid"
241
+ level = "L2"
242
+ category = "state_restoration"
243
+ capabilities = ("Perceive", "Reason", "Plan", "Restore")
244
+ protocol = "cross"
245
+ max_attempts = 3
246
+ agent_max_steps = 120 # careful: lid 2 x ~6 + 3 items x ~7 = ~35 commands; laying the block down (tip + pick) ~8;
247
+ # fixing a blocked lid in place (reopen, take out, tip, pick, put in, close) ~30; + looking
248
+ instruction = ("Put the red block and the two blue cubes into the wooden box and close its lid. The lid opens by "
249
+ "lifting the black knob on its edge.")
250
+ instruction_indirect = ("Pack the tall red piece and both small blue cubes into the wooden chest and shut it "
251
+ "(the lid lifts by the black ball on its edge).")
252
+ agent_object_names = ["red block", "blue cube", "blue cube", "wooden box", "lid knob"]
253
+
254
+ # ------------------------------------------------------------ scene
255
+ def make_bddl(self):
256
+ box = register_generated("LffFblBox", fb_box_xml(BOX_MODEL), free=False)
257
+ red = register_generated("LffFblRedBlock", box_xml("lff_fbl_red_block", (RED_W / 2, RED_W / 2, RED_H / 2),
258
+ (0.85, 0.10, 0.08, 1.0), density=RED_DENS,
259
+ friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace(
260
+ 'group="0" />', 'condim="4" group="0" />'))
261
+ objs = [(RED, red, "red_region", (-0.35, -0.25, -0.33, -0.23))]
262
+ for i, n in enumerate(BLUES):
263
+ cat = register_generated(f"LffFblBlueCube{'AB'[i]}",
264
+ box_xml(f"lff_fbl_blue_cube_{'ab'[i]}", (CUBE_E / 2,) * 3, (0.15, 0.30, 0.85, 1.0),
265
+ density=CUBE_DENS, friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace(
266
+ 'group="0" />', 'condim="4" group="0" />'))
267
+ objs.append((n, cat, f"blue_{'ab'[i]}_region", (-0.35, -0.09 + 0.16 * i, -0.33, -0.07 + 0.16 * i)))
268
+ fx = [(BOX, box, "box_region", (-0.16, -0.01, -0.14, 0.01))]
269
+ return write_bddl(self.name, "put the red block and the blue cubes into the box and close the lid", objs, fx)
270
+
271
+ def __init__(self, cam_res=None):
272
+ super().__init__(cam_res)
273
+ m = self.env.sim.model
274
+ pre = f"{BOX}_{BOX_MODEL}"
275
+ self.jid = m.joint_name2id(pre + "_hinge")
276
+ self.qa = m.jnt_qposadr[self.jid]
277
+ self.dof = m.jnt_dofadr[self.jid]
278
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
279
+ self.knob_geom_name = pre + "_knob"
280
+ self.knob_geom_names = [pre + "_knob", pre + "_stem"]
281
+ self.knob_gid = m.geom_name2id(self.knob_geom_name)
282
+ self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")}
283
+ self.fb_gid = m.geom_name2id(pre + "_fb")
284
+ self.fbvis_gid = m.geom_name2id(pre + "_fbvis")
285
+ self.robot_gids = set(envs.robot_geom_ids(self.env))
286
+ self.item_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in ITEMS}
287
+ self.inst = None
288
+ self.mon = None
289
+
290
+ def sample_instance(self, seed):
291
+ rng = np.random.default_rng(seed)
292
+ bx, by = float(rng.uniform(-0.17, -0.14)), float(rng.uniform(-0.02, 0.02))
293
+ hinge = "left" if rng.random() < 0.5 else "right"
294
+ stop = float(rng.uniform(*STOP))
295
+ perm = rng.permutation(len(START_Y))
296
+ start = {n: [float(START_X + rng.uniform(-0.01, 0.01)), float(START_Y[perm[j]] + rng.uniform(-0.01, 0.01))]
297
+ for j, n in enumerate(ITEMS)}
298
+ start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in ITEMS}
299
+ # balanced blocks like lh_lid_box: exactly 10 of every 20 consecutive seeds have the false bottom
300
+ fb = bool((int(seed) * 7) % 20 < round(20 * P_FB))
301
+ return dict(seed=int(seed), box_xy=[bx, by], hinge=hinge, stop_deg=stop, false_bottom=fb,
302
+ inner_depth_cm=round(100 * (FB_DEPTH if fb else WALL_H - FLOOR_T), 1), start=start,
303
+ start_yaw=start_yaw)
304
+
305
+ def box_yaw(self, inst=None):
306
+ inst = inst or self.inst
307
+ return np.pi / 2 if inst["hinge"] == "left" else -np.pi / 2 # local +x (hinge edge) -> world +y / -y
308
+
309
+ def apply_instance(self, inst):
310
+ self.inst = inst
311
+ m, d = self.env.sim.model, self.env.sim.data
312
+ bx, by = inst["box_xy"]
313
+ yaw = self.box_yaw(inst)
314
+ m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z]
315
+ m.body_quat[self.box_bid] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]
316
+ m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])]
317
+ m.jnt_solref[self.jid] = [0.01, 1.0]
318
+ fb = bool(inst["false_bottom"])
319
+ m.geom_contype[self.fb_gid] = 2 if fb else 0
320
+ m.geom_conaffinity[self.fb_gid] = 1 if fb else 0
321
+ m.geom_rgba[self.fbvis_gid, 3] = 1.0 if fb else 0.0
322
+ d.qpos[self.qa] = 0.0
323
+ d.qvel[self.dof] = 0.0
324
+ for n, xy in inst["start"].items():
325
+ envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n])
326
+ for n in ITEMS:
327
+ envs.set_friction(self.env, n, ITEM_MU)
328
+
329
+ def reset_instance(self, inst, recorder=None):
330
+ self.env.reset()
331
+ self.apply_instance(inst)
332
+ self.env.sim.forward()
333
+ envs.settle(self.env, 10)
334
+ self.mon = None
335
+ self.sk = FBLidSkills(self.env, self, recorder=recorder)
336
+ self._init_monitor()
337
+ return self.sk
338
+
339
+ # ------------------------------------------------------------ geometry helpers
340
+ def floor_z(self):
341
+ """height of the surface items rest on inside the box (world z)"""
342
+ return envs.TABLE_Z + ((WALL_H - FB_DEPTH) if self.inst["false_bottom"] else FLOOR_T)
343
+
344
+ def rim_z(self):
345
+ return envs.TABLE_Z + WALL_H
346
+
347
+ def long_axis(self):
348
+ """unit vector (world xy) along the box's long side (= the hinge axis), pointing forward"""
349
+ return np.array([1.0, 0.0])
350
+
351
+ def to_box(self, xy):
352
+ """world xy -> box frame (u along the long side / forward, v across / left)"""
353
+ return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"])
354
+
355
+ def from_box(self, uv):
356
+ return np.asarray(self.inst["box_xy"]) + np.asarray(uv, float)
357
+
358
+ def hinge_sign(self):
359
+ return 1.0 if self.inst["hinge"] == "left" else -1.0
360
+
361
+ def hinge_point(self):
362
+ bx, by = self.inst["box_xy"]
363
+ return np.array([bx, by + self.hinge_sign() * LX / 2, envs.TABLE_Z + WALL_H])
364
+
365
+ def hinge_axis(self):
366
+ return np.array([1.0, 0.0, 0.0])
367
+
368
+ def lid_q(self):
369
+ return float(self.env.sim.data.qpos[self.qa])
370
+
371
+ def lid_deg(self):
372
+ return float(np.degrees(self.lid_q()))
373
+
374
+ def knob_xyz(self):
375
+ return self.env.sim.data.geom_xpos[self.knob_gid].copy()
376
+
377
+ def held(self, name):
378
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
379
+
380
+ def item_axis(self, name):
381
+ """body z axis in world (the red block's long axis)"""
382
+ return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)[:, 2].copy()
383
+
384
+ def red_pose(self):
385
+ c = abs(float(self.item_axis(RED)[2]))
386
+ return "upright" if c >= UPRIGHT_COS else "lying" if c <= LYING_COS else "tilted"
387
+
388
+ def in_cavity_xy(self, name):
389
+ """the item's whole footprint (its collision box corners, also when tilted) inside the inner walls"""
390
+ m, d = self.env.sim.model, self.env.sim.data
391
+ g = next(iter(self.item_gids[name]))
392
+ R = d.geom_xmat[g].reshape(3, 3)
393
+ half = m.geom_size[g][:3]
394
+ c = self.to_box(d.geom_xpos[g][:2])
395
+ ext = np.abs(R[:2, :]) @ half # world-axis half extents of the footprint
396
+ lim = np.array([L_IN / 2, S_IN / 2]) + IN_TOL
397
+ return bool(np.all(np.abs(c) + ext <= lim))
398
+
399
+ def in_box(self, name):
400
+ return bool(self.in_cavity_xy(name) and envs.obj_max_z(self.env, name) <= self.rim_z() + RIM_TOL
401
+ and envs.obj_min_z(self.env, name) >= envs.TABLE_Z + FLOOR_T - 0.005 and not self.held(name))
402
+
403
+ def over_box(self, name):
404
+ """centre above the cavity (in it, or standing in it but sticking out)"""
405
+ c = self.to_box(envs.obj_pos(self.env, name)[:2])
406
+ return bool(abs(c[0]) <= L_IN / 2 and abs(c[1]) <= S_IN / 2)
407
+
408
+ def lid_closed(self):
409
+ return self.lid_q() <= LID_CLOSED
410
+
411
+ def lid_contacts(self):
412
+ """items the lid touches now"""
413
+ d = self.env.sim.data
414
+ out = set()
415
+ for i in range(d.ncon):
416
+ c = d.contact[i]
417
+ for n in ITEMS:
418
+ g = self.item_gids[n]
419
+ if (c.geom1 in g and c.geom2 in self.lid_gids) or (c.geom2 in g and c.geom1 in self.lid_gids):
420
+ out.add(n)
421
+ return out
422
+
423
+ def robot_lid_contact(self):
424
+ """world position of a robot-lid contact (None if the robot does not touch the lid)"""
425
+ d = self.env.sim.data
426
+ for i in range(d.ncon):
427
+ c = d.contact[i]
428
+ if (c.geom1 in self.robot_gids and c.geom2 in self.lid_gids) or (c.geom2 in self.robot_gids
429
+ and c.geom1 in self.lid_gids):
430
+ return np.array(c.pos, float)
431
+ return None
432
+
433
+ def robot_touching(self):
434
+ """'lid' / item names the robot is in contact with now (finishing while pressing the lid down does not count)"""
435
+ d = self.env.sim.data
436
+ out = set()
437
+ for i in range(d.ncon):
438
+ c = d.contact[i]
439
+ g1, g2 = c.geom1, c.geom2
440
+ for a, b in ((g1, g2), (g2, g1)):
441
+ if a in self.robot_gids:
442
+ if b in self.lid_gids:
443
+ out.add("lid")
444
+ for n in ITEMS:
445
+ if b in self.item_gids[n]:
446
+ out.add("red block" if n == RED else "blue cube")
447
+ return sorted(out)
448
+
449
+ def stage_values(self):
450
+ v = {f"{n}_in_box": self.in_box(n) for n in ITEMS}
451
+ v["lid_closed"] = self.lid_closed()
452
+ return v
453
+
454
+ # ------------------------------------------------------------ per-step monitor
455
+ def _init_monitor(self):
456
+ self.mon = dict(state={f"{n}_in_box": False for n in ITEMS}, ever=set(), lost=set(), events=[],
457
+ last_touch={n: None for n in ITEMS}, step=0, lid_opened=False, lid_open_max=0.0,
458
+ lid_prev=0.0, lid_still=0, blocked_now=False, n_blocked=0, blocked_max_deg=0.0,
459
+ red_pose=self.red_pose(), red_pose_cand=None, red_pose_n=0, red_up_in_box=False,
460
+ red_relaid=0, closes=0, cand={f"{n}_in_box": 0 for n in ITEMS})
461
+
462
+ def _touches(self):
463
+ d = self.env.sim.data
464
+ out = {}
465
+ for i in range(d.ncon):
466
+ c = d.contact[i]
467
+ for n in ITEMS:
468
+ g = self.item_gids[n]
469
+ other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None)
470
+ if other is None:
471
+ continue
472
+ if other in self.lid_gids:
473
+ out[n] = "lid"
474
+ elif other in self.robot_gids and out.get(n) != "lid":
475
+ out[n] = "robot"
476
+ return out
477
+
478
+ def monitor_step(self):
479
+ mon = self.mon
480
+ if mon is None:
481
+ return
482
+ mon["step"] += 1
483
+ step = self.sk.n_steps if self.sk is not None else mon["step"]
484
+ for n, who in self._touches().items():
485
+ mon["last_touch"][n] = (who, step)
486
+ q = self.lid_deg()
487
+ mon["lid_open_max"] = max(mon["lid_open_max"], q)
488
+ if not mon["lid_opened"] and q > 90.0:
489
+ mon["lid_opened"] = True
490
+ mon["blocked_now"] = False
491
+ mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical"))
492
+ elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED):
493
+ mon["lid_opened"] = False
494
+ mon["closes"] += 1
495
+ mon["events"].append(dict(step=step, pred="lid", ev="closed"))
496
+ # lid blocked: it came down from past vertical and rests (not held) on an item at 5-80 deg for 1 s
497
+ if abs(q - mon["lid_prev"]) < 0.05:
498
+ mon["lid_still"] += 1
499
+ else:
500
+ mon["lid_still"] = 0
501
+ mon["lid_prev"] = q
502
+ if mon["lid_opened"] and not mon["blocked_now"] and 5.0 < q < 80.0 and mon["lid_still"] >= 20 \
503
+ and not self.sk.latched:
504
+ on = sorted(self.lid_contacts())
505
+ if on:
506
+ mon["blocked_now"] = True
507
+ mon["n_blocked"] += 1
508
+ mon["blocked_max_deg"] = max(mon["blocked_max_deg"], q)
509
+ mon["events"].append(dict(step=step, pred="lid", ev="lid_blocked", lid_deg=round(q, 1), on=on,
510
+ red_pose=self.red_pose()))
511
+ if mon["blocked_now"] and q > 90.0:
512
+ mon["blocked_now"] = False
513
+ if mon["step"] % 2:
514
+ return # predicates every other control step (0.1 s)
515
+ # red block pose (debounced 1 s): upright <-> lying
516
+ p = self.red_pose()
517
+ if p != "tilted" and p != mon["red_pose"]:
518
+ if mon["red_pose_cand"] == p:
519
+ mon["red_pose_n"] += 1
520
+ else:
521
+ mon["red_pose_cand"], mon["red_pose_n"] = p, 1
522
+ if mon["red_pose_n"] >= 10 and not self.held(RED):
523
+ where = "box" if self.over_box(RED) else "table"
524
+ lt = mon["last_touch"][RED]
525
+ cause = lt[0] if lt is not None and step - lt[1] <= 60 else "other"
526
+ ev = "item_relaid" if p == "lying" else "stood_up"
527
+ if p == "lying":
528
+ mon["red_relaid"] += 1
529
+ mon["events"].append(dict(step=step, pred="red_pose", ev=ev, where=where, cause=cause))
530
+ mon["red_pose"] = p
531
+ mon["red_pose_cand"] = None
532
+ else:
533
+ mon["red_pose_cand"] = None
534
+ if not mon["red_up_in_box"] and mon["red_pose"] == "upright" and self.over_box(RED) and not self.held(RED) \
535
+ and envs.obj_min_z(self.env, RED) < self.rim_z():
536
+ mon["red_up_in_box"] = True
537
+ top = envs.obj_max_z(self.env, RED) - self.rim_z()
538
+ mon["events"].append(dict(step=step, pred="red_pose", ev="placed_upright_in_box",
539
+ top_above_rim_cm=round(100 * top, 1)))
540
+ for n in ITEMS: # debounced: a change counts after it held for DEBOUNCE checks (fingers rubbing a released item)
541
+ key = f"{n}_in_box"
542
+ now = self.in_box(n)
543
+ if now == mon["state"][key]:
544
+ mon["cand"][key] = 0
545
+ continue
546
+ mon["cand"][key] += 1
547
+ if mon["cand"][key] >= DEBOUNCE:
548
+ mon["cand"][key] = 0
549
+ self._event(key, now, step, n)
550
+
551
+ def _event(self, key, now, step, name):
552
+ mon = self.mon
553
+ mon["state"][key] = now
554
+ if now:
555
+ ev = "restored" if key in mon["lost"] else "achieved"
556
+ mon["ever"].add(key)
557
+ mon["lost"].discard(key)
558
+ e = dict(step=step, pred=key, ev=ev)
559
+ if name == RED:
560
+ e["red_pose"] = self.red_pose()
561
+ mon["events"].append(e)
562
+ return
563
+ if key not in mon["ever"]:
564
+ return # never achieved: nothing lost
565
+ cause = "other"
566
+ if self.held(name):
567
+ cause = "picked_up"
568
+ else:
569
+ lt = mon["last_touch"][name]
570
+ if lt is not None and step - lt[1] <= 60:
571
+ cause = lt[0]
572
+ mon["lost"].add(key)
573
+ mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1)))
574
+
575
+ # ------------------------------------------------------------ outcome
576
+ def _static(self):
577
+ d = self.env.sim.data
578
+ for n in ITEMS:
579
+ _, da = envs.free_joint_addr(self.env, n)
580
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
581
+ return False
582
+ return abs(float(d.qvel[self.dof])) < 0.2
583
+
584
+ def _where(self, name):
585
+ """F2-style location of an item relative to the box, robot-centric words"""
586
+ rel = self.to_box(envs.obj_pos(self.env, name)[:2])
587
+ return f"{_fb(rel[0])} and {_lr(rel[1])} of the box's centre"
588
+
589
+ def outcome(self, inst):
590
+ envs.settle(self.env, 30)
591
+ mon = self.mon
592
+ vals = self.stage_values()
593
+ static = self._static()
594
+ held = [n for n in ITEMS if self.held(n)]
595
+ touching = self.robot_touching()
596
+ success = bool(all(vals.values()) and static and not held and not touching)
597
+ regress = [e for e in mon["events"] if e["ev"] == "lost"]
598
+ restored = [e for e in mon["events"] if e["ev"] == "restored"]
599
+ on = sorted(self.lid_contacts())
600
+ red_top = envs.obj_max_z(self.env, RED) - self.rim_z()
601
+ parts = []
602
+ failure = None
603
+ if success:
604
+ parts.append("The red block and both blue cubes are inside the box and the lid is closed.")
605
+ else:
606
+ out_items = [n for n in ITEMS if not vals[f"{n}_in_box"]]
607
+ if not vals["lid_closed"] and on:
608
+ failure = "lid_blocked"
609
+ elif held:
610
+ failure = "held"
611
+ elif touching and all(vals.values()):
612
+ failure = "robot_touching"
613
+ elif out_items:
614
+ failure = ("red_sticks_out" if out_items == [RED] and self.over_box(RED) and red_top > RIM_TOL
615
+ else "item_not_in_box")
616
+ elif not vals["lid_closed"]:
617
+ failure = "lid_open"
618
+ else:
619
+ failure = "not_static"
620
+ if not vals["lid_closed"]:
621
+ txt = f"The lid is not closed (open {self.lid_deg():.0f} degrees)"
622
+ if on:
623
+ names = " and ".join("the red block" if n == RED else "a blue cube" for n in on)
624
+ txt += f": it rests on {names}"
625
+ parts.append(txt + ".")
626
+ for n in out_items:
627
+ nm = "The red block" if n == RED else "A blue cube"
628
+ if self.held(n):
629
+ parts.append(f"{nm} is still held by the gripper.")
630
+ elif self.over_box(n) and envs.obj_max_z(self.env, n) > self.rim_z() + RIM_TOL:
631
+ top = envs.obj_max_z(self.env, n) - self.rim_z()
632
+ pose = self.red_pose() if n == RED else "resting"
633
+ parts.append(f"{nm} is in the box but sticks out {100 * top:.1f} cm above the rim ({pose}).")
634
+ else:
635
+ parts.append(f"{nm} is not in the box: its centre is {self._where(n)}.")
636
+ if touching and all(vals.values()):
637
+ parts.append("The robot was still pressing on the " + " and ".join(touching) + " at the end.")
638
+ if not static and all(vals.values()):
639
+ parts.append("Something was still moving at the end.")
640
+ if mon["n_blocked"]:
641
+ parts.append(f"The lid came down on an item {mon['n_blocked']} time(s) during the attempt.")
642
+ out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching,
643
+ events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
644
+ false_bottom=bool(inst["false_bottom"]), n_lid_blocked=mon["n_blocked"],
645
+ lid_blocked_max_deg=round(mon["blocked_max_deg"], 1), red_relaid=mon["red_relaid"],
646
+ red_placed_upright_in_box=mon["red_up_in_box"], red_pose=self.red_pose(),
647
+ red_top_above_rim_cm=round(100 * red_top, 1), lid_on=on,
648
+ lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1),
649
+ lid_closes=mon["closes"], knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps,
650
+ detail=" ".join(parts))
651
+ return out
652
+
653
+ # ------------------------------------------------------------ scripted primitives (perfect perception)
654
+ def _settle_item(self, name, max_checks=20):
655
+ """keep the arm still until `name` has stopped moving (a tipped block rolls on for a moment)"""
656
+ d = self.env.sim.data
657
+ _, da = envs.free_joint_addr(self.env, name)
658
+ for _ in range(max_checks):
659
+ if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
660
+ return
661
+ self.sk.hold(2)
662
+
663
+ def _grasp_yaw(self, name):
664
+ """fingers across a 4 cm side: for the lying red block across its long axis, else yaw mod 90 deg"""
665
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
666
+ if name == RED and self.red_pose() != "upright":
667
+ ax = R[:, 2]
668
+ yaw = float(np.arctan2(ax[1], ax[0])) # closing direction (-sin, cos) is then across the long axis
669
+ return float((yaw + np.pi / 2) % np.pi - np.pi / 2)
670
+ i = int(np.argmin(np.abs(R[2])))
671
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
672
+ return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
673
+
674
+ def _grasp_z(self, name):
675
+ """grasp point height above the table for a top-down grasp of `name` where it is"""
676
+ zmin = envs.obj_min_z(self.env, name) - envs.TABLE_Z
677
+ zmax = envs.obj_max_z(self.env, name) - envs.TABLE_Z
678
+ if name == RED and self.red_pose() == "upright":
679
+ z = zmin + 0.0425 # 4.25 cm up the 7.5 cm block (0.5 cm above its centre)
680
+ else:
681
+ z = (zmin + zmax) / 2
682
+ if self.over_box(name): # the hand (2.4 cm above the grasp point) stays above the rim
683
+ z = max(z, Z_HAND_MIN, WALL_H + 0.016 if zmax > WALL_H + 0.02 else 0.0)
684
+ z = min(z, zmax - 0.004)
685
+ return z
686
+
687
+ def pick(self, name, z_carry=Z_CARRY, tries=2):
688
+ """top-down grasp of `name` where it is, lift to z_carry (a missed grasp is retried once, as anyone would);
689
+ returns the grasp point's height above the item's bottom, or None if the grasp failed"""
690
+ sk = self.sk
691
+ Z = envs.TABLE_Z
692
+ for _ in range(tries):
693
+ self._settle_item(name)
694
+ p = envs.obj_pos(self.env, name)
695
+ yaw = self._grasp_yaw(name)
696
+ zg = self._grasp_z(name)
697
+ zbot = envs.obj_min_z(self.env, name) - Z
698
+ sk.set_gripper(False, steps=8)
699
+ sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw)
700
+ sk.hold(8) # let a large wrist turn settle before going down (else the hand drifts ~1 cm near the table)
701
+ sk.move_to([p[0], p[1], Z + zg], tol=0.003, max_steps=120)
702
+ sk.set_gripper(True, steps=15)
703
+ sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
704
+ if self.held(name):
705
+ return zg - zbot
706
+ sk.set_gripper(False, steps=8)
707
+ return None
708
+
709
+ def place(self, dest_xy, z_rel, yaw, z_carry=Z_CARRY):
710
+ """carry to above dest at z_carry, lower to z_rel (or until the item / hand rests on something), release, lift"""
711
+ sk = self.sk
712
+ Z = envs.TABLE_Z
713
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=yaw)
714
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003, max_steps=80)
715
+ sk.set_gripper(False, steps=12)
716
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry])
717
+
718
+ def put_in_box(self, name, u, v=0.0, noise=None, z_carry=Z_CARRY):
719
+ """pick `name` as it is (the red block upright or lying) and lower it into the box at (u, v) (box frame) as if
720
+ the box were deep (the hand stops above the rim), release. The lying red block is turned across the box."""
721
+ off = self.pick(name, z_carry=z_carry)
722
+ if off is None:
723
+ return False
724
+ yaw = np.pi / 2 if name == RED and self.red_pose() == "lying" else self.sk.yaw
725
+ d = self.from_box([u, v]) + (np.asarray(noise, float) if noise is not None else 0.0)
726
+ self.place(d, max(Z_HAND_MIN, FLOOR_T + off + 0.005), yaw, z_carry=z_carry)
727
+ return True
728
+
729
+ def red_slot(self):
730
+ return SLOT_U["red_lying"] if self.red_pose() == "lying" else SLOT_U["red_upright"]
731
+
732
+ def tip_over(self, name, direction, z_push=0.055, speed=0.10):
733
+ """push the standing item's upper part with the closed fingers along `direction` (xy) so that it falls over"""
734
+ sk = self.sk
735
+ Z = envs.TABLE_Z
736
+ d = np.asarray(direction, float)
737
+ d = d / np.linalg.norm(d)
738
+ p = envs.obj_pos(self.env, name)
739
+ s = p[:2] - d * 0.06
740
+ e = p[:2] + d * 0.035
741
+ yaw = float(np.arctan2(d[1], d[0])) - np.pi / 2 # finger closing direction along the push
742
+ sk.set_gripper(True, steps=8)
743
+ sk.move_to([s[0], s[1], Z + 0.13], yaw=yaw)
744
+ sk.move_to([s[0], s[1], Z + z_push], tol=0.004)
745
+ sk.move_to([e[0], e[1], Z + z_push], speed=speed, tol=0.006)
746
+ sk.move_to([e[0], e[1], Z + 0.13], speed=0.3)
747
+ self._settle_item(name)
748
+ return self.red_pose() if name == RED else None
749
+
750
+ def _tip_direction(self, name):
751
+ """outward along y (away from the other items, which stand 16 cm apart in a row)"""
752
+ y = envs.obj_pos(self.env, name)[1]
753
+ return np.array([0.0, 1.0 if y >= 0 else -1.0])
754
+
755
+ def lay_down(self, name=RED, **kw):
756
+ """tip the standing block over on the table (up to two pushes); True if it lies"""
757
+ for _ in range(2):
758
+ if self.red_pose() == "lying":
759
+ return True
760
+ self.tip_over(name, self._tip_direction(name), **kw)
761
+ return self.red_pose() == "lying"
762
+
763
+ def take_out_red(self):
764
+ """pick the red block out of the box and stand it on its start spot"""
765
+ off = self.pick(RED)
766
+ if off is None:
767
+ return False
768
+ self.place(self.inst["start"][RED], off + 0.004, self.sk.yaw)
769
+ self._settle_item(RED)
770
+ return True
771
+
772
+ def _grasp_knob(self, yaw=-np.pi / 2):
773
+ """open the fingers, come down on the knob at wrist yaw -90 deg (fingers across the stem), close. Always -90
774
+ (not its gripper-symmetric twin +90): with the lid hanging on its stop beside the box the arm reached the knob
775
+ at -90 in every instance, but at +90 it stopped 2-3 cm short against the lid (validate seed 1004: the lying
776
+ block's grasp yaw had landed on +90 by numerical chance and the final close missed the knob twice). A 180 deg
777
+ wrist turn is avoided by passing through yaw 0 (see Skills.wrap_yaw)."""
778
+ sk = self.sk
779
+ k = self.knob_xyz()
780
+ for attempt in range(2):
781
+ sk.set_gripper(False, steps=8)
782
+ if abs(sk.yaw - yaw) > np.pi / 2 + 0.1:
783
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0, wrap_yaw=False)
784
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=yaw, wrap_yaw=False)
785
+ sk.hold(5)
786
+ sk.move_to([k[0], k[1], k[2]], tol=0.003)
787
+ sk.set_gripper(True, steps=15)
788
+ if sk.holding_knob() or attempt:
789
+ break
790
+ # missed (measured once in 40 validation attempts: after a long sequence of wrist turns the arm's posture
791
+ # had drifted and it stopped 3-4 cm short of the knob hanging far to the side): open, go back to a neutral
792
+ # pose over the box at yaw 0 (the OSC's null-space term straightens the arm there) and try once more
793
+ sk.set_gripper(False, steps=8)
794
+ e = sk.eef_pos()
795
+ sk.move_to([e[0], e[1], e[2] + 0.10])
796
+ c = self.from_box([0.0, 0.0])
797
+ sk.move_to([c[0], c[1], envs.TABLE_Z + 0.28], yaw=0.0, wrap_yaw=False)
798
+ sk.hold(10)
799
+ return k
800
+
801
+ def open_lid(self, over=0.04, up=0.16):
802
+ """grasp the knob (fingers across its stem); straight up 10 cm; straight to `over` m beyond the hinge, `up` m
803
+ above it; release; lift"""
804
+ sk = self.sk
805
+ k = self._grasp_knob()
806
+ h = self.hinge_point()
807
+ sg = self.hinge_sign()
808
+ sk.move_to([k[0], k[1], k[2] + 0.10])
809
+ sk.move_to([h[0], h[1] + sg * over, h[2] + up])
810
+ sk.set_gripper(False, steps=10)
811
+ e = sk.eef_pos()
812
+ sk.move_to([e[0], e[1] - sg * 0.04, e[2] + 0.05])
813
+ sk.hold(25)
814
+
815
+ def close_lid(self, away=0.08, up=0.10):
816
+ """grasp the knob where it is; straight up 10 cm; straight to `away` m on the knob side of the hinge; release"""
817
+ sk = self.sk
818
+ k = self._grasp_knob()
819
+ h = self.hinge_point()
820
+ sg = self.hinge_sign()
821
+ sk.move_to([k[0], k[1], k[2] + up])
822
+ sk.move_to([h[0], h[1] - sg * away, max(k[2], h[2]) + up])
823
+ sk.set_gripper(False, steps=10)
824
+ e = sk.eef_pos()
825
+ sk.move_to([e[0], e[1], e[2] + 0.06])
826
+ sk.hold(30)
827
+
828
+ def press_lid(self):
829
+ """the natural retry when the lid did not shut: grasp the knob where it is and push it down towards closed"""
830
+ sk = self.sk
831
+ k = self._grasp_knob()
832
+ h = self.hinge_point()
833
+ sg = self.hinge_sign()
834
+ sk.move_to([k[0], h[1] - sg * (LX + 0.01), h[2] - 0.01], speed=0.1)
835
+ sk.set_gripper(False, steps=10)
836
+ e = sk.eef_pos()
837
+ sk.move_to([e[0], e[1], e[2] + 0.08])
838
+ sk.hold(30)
839
+
840
+ def _fallen(self):
841
+ """items that ended up outside the box (not merely sticking out of it)"""
842
+ return [n for n in ITEMS if not self.in_box(n) and not self.over_box(n) and not self.held(n)]
843
+
844
+ def _replace_fallen(self, done, noise=None, z_carry=Z_CARRY):
845
+ for n in [n for n in self._fallen() if n in done]:
846
+ self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=(noise or {}).get(n), z_carry=z_carry)
847
+
848
+ # ------------------------------------------------------------ scripted policies
849
+ def execute(self, inst, params):
850
+ noise = params.get("noise") or {}
851
+ zc = params.get("z_carry", Z_CARRY)
852
+ self.open_lid(**params.get("open", {}))
853
+ done = []
854
+ for n in ITEMS:
855
+ if n == RED and params.get("lay_first"):
856
+ self.lay_down(RED)
857
+ self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=noise.get(n), z_carry=zc)
858
+ done.append(n)
859
+ self._replace_fallen(done, noise, zc) # looks after every step: re-places an item that fell outside
860
+ self.close_lid(**params.get("close", {}))
861
+ if params.get("check") == "naive":
862
+ self.naive_check(noise, zc)
863
+ elif params.get("check") == "fix":
864
+ self.check_and_fix()
865
+ self.sk.hold(10)
866
+
867
+ def naive_check(self, noise=None, z_carry=Z_CARRY):
868
+ """Sonnet-like look before finishing, without the insight: a lid that did not shut is pushed down once (re-closed
869
+ if it is still open past upright); an item outside the box is put back as it is (the red block upright)"""
870
+ if not self.lid_closed():
871
+ if self.lid_deg() > 90:
872
+ self.close_lid()
873
+ else:
874
+ self.press_lid()
875
+ if self._fallen():
876
+ if self.lid_deg() < 90:
877
+ self.open_lid()
878
+ self._replace_fallen(list(ITEMS), noise, z_carry)
879
+ self.close_lid()
880
+
881
+ def check_and_fix(self, rounds=2):
882
+ """look at every stage; if the red block is not inside below the rim (it stands up out of a shallow box and
883
+ holds the lid open), take it out, lay it down on the table and put it in lying; re-place anything outside the
884
+ box; close the lid"""
885
+ for _ in range(rounds):
886
+ v = self.stage_values()
887
+ if all(v.values()) and not any(self.held(n) for n in ITEMS):
888
+ return True
889
+ bad = [n for n in ITEMS if not v[f"{n}_in_box"]]
890
+ if self.lid_deg() < 90 and (bad or self.lid_contacts()):
891
+ self.open_lid()
892
+ for n in bad:
893
+ if n == RED and self.red_pose() != "lying":
894
+ if self.over_box(RED):
895
+ self.take_out_red()
896
+ self.lay_down(RED)
897
+ self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n])
898
+ if self.lid_deg() > 90 or not self.lid_closed():
899
+ self.close_lid()
900
+ return all(self.stage_values().values())
901
+
902
+ def default_params(self, inst):
903
+ """Sonnet-like: open the lid, items in the listed order, each put in as found (the block upright), carried
904
+ 16 cm up, looks after every step (re-places an item that fell outside), closes the lid, pushes a lid that did
905
+ not shut down once, finishes"""
906
+ return dict(lay_first=False, check="naive")
907
+
908
+ def oracle_params(self, inst):
909
+ """knows the inner depth: lays the block down first in a shallow box; checks every stage at the end"""
910
+ return dict(lay_first=bool(inst["false_bottom"]), check="fix")
911
+
912
+ def adapt_params(self, inst, history):
913
+ """attempt >= 2 (after a failure): lay the block down before putting it in, then check and fix"""
914
+ return dict(lay_first=True, check="fix")
915
+
916
+ def blind_params(self, inst, attempt, rng):
917
+ """the natural behaviour again with small random variations, no history"""
918
+ return dict(lay_first=False, check="naive",
919
+ noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS},
920
+ z_carry=float(rng.uniform(0.13, 0.19)),
921
+ open=dict(over=float(rng.uniform(0.02, 0.06)), up=float(rng.uniform(0.14, 0.18))),
922
+ close=dict(away=float(rng.uniform(0.06, 0.10))))
923
+
924
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
925
+ """oracle / naive: one attempt; adaptive: attempt 1 = the natural placement plus a real check and fix (takes the
926
+ block out and lays it down when the lid is blocked), later attempts lay it down first; blind: natural with
927
+ random variations; switch (extra control): natural, then lay it down first from attempt 2, no real check"""
928
+ k = k or self.max_attempts
929
+ rng = np.random.default_rng(seed)
930
+ history = []
931
+ for a in range(k):
932
+ self.reset_instance(inst)
933
+ if kind == "oracle":
934
+ params = self.oracle_params(inst)
935
+ elif kind == "naive":
936
+ params = self.default_params(inst)
937
+ elif kind == "adaptive":
938
+ params = dict(lay_first=False, check="fix") if a == 0 else self.adapt_params(inst, history)
939
+ elif kind == "blind":
940
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
941
+ elif kind == "switch":
942
+ params = self.default_params(inst) if a == 0 else dict(lay_first=True, check="naive")
943
+ elif kind == "oracle_noise": # robustness check: oracle with +-5 mm placement noise
944
+ params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS})
945
+ else:
946
+ raise ValueError(kind)
947
+ self.execute(inst, params)
948
+ out = self.outcome(inst)
949
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
950
+ if on_attempt:
951
+ on_attempt(a, params, out)
952
+ if out["success"] or kind in ("oracle", "naive", "oracle_noise"):
953
+ break
954
+ return history
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_tray_delivery.py ADDED
@@ -0,0 +1,883 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH tray_delivery v2 (long horizon, state restoration): load three bottles onto a tray in the loading area, then move
2
+ the loaded tray over a low threshold strip into the delivery area. Pushing the tray over the strip makes it rock, and
3
+ the top-heavy bottles fall; holding the tray by its handle while moving it does not.
4
+
5
+ Family: long-horizon tasks in which the agent's own normal later-stage action physically breaks earlier progress
6
+ (docs/11). Stages:
7
+ S1-S3 stand the red / green / blue bottle upright on the tray while the tray is inside the yellow loading area;
8
+ S4 move the tray (with the bottles) over the black threshold strip completely into the purple delivery area.
9
+ Success (F1): at the end the tray (board and handle) is completely inside the delivery area, all three bottles stand
10
+ upright on it, the gripper does not touch them, the scene is static, AND the event log shows that all three bottles
11
+ stood on the tray at the same time while the tray was still completely inside the loading area (load first, then
12
+ deliver). Re-standing a fallen bottle on the tray after the move is allowed (counts as a restoration).
13
+
14
+ v2 (2026-10-09, after the Sonnet 5.5 pilot lh1, see the task card): v1's 15.6 cm bottles on a 2.2 cm foot were hard to
15
+ grasp and to stand, the narrow handle was hard to push straight, "completely inside" needed 2 cm precision, and the
16
+ agents pushed at 3-5 cm/s, far below v1's 0.15 m/s topple threshold, so the hidden variable never mattered. Now:
17
+ - bottles 10.5 cm tall: 4 x 4 x 7.5 cm square body with a flat bottom + a 2.4 cm round neck (3 cm tall), 0.25 kg;
18
+ - T handle, 2.5 cm tall: a 16 cm push bar at the back (push it with the closed gripper) on a 3 cm wide, 5 cm long stem
19
+ (grasp it across its width);
20
+ - delivery area 28 x 42 cm for the 18.5 x 34 cm tray footprint (4.75 / 4 cm slack per side; v1: 2 / 3 cm);
21
+ - a black threshold strip between the areas (a rounded sill 1 cm high, 5.3 cm wide, 46 cm long) that the tray has to
22
+ cross. Measured: with stocky bottles speed alone cannot be the lever (on a flat table a top-heavy bottle stayed up in
23
+ closed-gripper pushes up to 0.3 m/s; only the controller's top speed, ~0.65 m/s, toppled it). On the sill the tray
24
+ first climbs (front up ~5 deg), then rocks over the crest under gravity; when it is pushed, nothing holds its trailing
25
+ edge, which jumps up (max tray tilt 7.2-9.3 deg) and the top-heavy bottles fall over the leading edge,
26
+ at every push speed tried (2-6 cm/s and the top speed). When the stem is grasped, the hand holds the trailing edge
27
+ (max tilt 5.7-7.5 deg) and nothing falls. A hand hovering right over the handle (3 cm handle pushed with the
28
+ grasp point ~1 cm above the table) also held it down; hence the 2.5 cm handle.
29
+ - failure codes report the first unmet requirement: not_loaded / order / bottle_fallen / bottle_off_tray /
30
+ not_delivered / held / not_static.
31
+
32
+ Scene: wooden tray = an 11 x 34 x 1.2 cm board, long side running forward / back, with the T handle sticking out of the
33
+ middle of the long side that faces away from the delivery area; three bottles (same shape, red / green / blue) standing
34
+ in a row on the table on the far side of the loading area; two painted rectangles (no collision): yellow loading area
35
+ (tray inside it at the start) and purple delivery area 32-34 cm (centre to centre) to its left or right (random); the
36
+ threshold strip lies across the path in the gap between them. The tray travels sideways (the arm's comfortable
37
+ workspace is wide in y but short in x).
38
+
39
+ Hidden variable (same appearance): each bottle's centre-of-mass height (an invisible internal weight, 85 % of its
40
+ mass): "stable" 2.0-3.5 cm, "top-heavy" 6.6-7.6 cm above the bottom; 0 / 1 / 2 top-heavy bottles with p = 0.35 / 0.40 /
41
+ 0.25. Measured on 28 instances (scripted loading, same loaded state for every move): closed-gripper pushes (2, 3, 4.5,
42
+ 6 cm/s, top speed, 3 stops, slow approach; agent-style pushes through the tool layer with the grasp point 1.0 / 1.3 /
43
+ 2.5 cm above the table) toppled 24/24 top-heavy bottles and 0/60 stable ones in every variant; grasp-and-drag at 2 and
44
+ 4.5 cm/s toppled 0/84. Above a COM of 8 cm falling bottles sometimes land standing on their neck (cannot be stood up
45
+ again with yaw-only control without first knocking them over), so the range stops at 7.6 cm. Tray-table friction
46
+ 0.45-0.60 is a nuisance variable; the sill's own friction (0.4) wins in its contacts (with the tray's 0.85 the tray
47
+ jammed at the sill and jumped over it, toppling nothing).
48
+ Restoration: a fallen bottle can be stood up again: grasp its round neck (fingers closing across the neck), lift it --
49
+ it swings down and hangs from the neck -- and set it down on the tray.
50
+
51
+ Simulation notes (as in v1): COM heights are set at reset through body_ipos / inertia and the bottle's collision BVH is
52
+ shifted with it (MuJoCo keeps it in the inertial frame); the tray uses the table's soft contact (solref 0.02); the
53
+ bottles' own contacts are stiffer (solref 0.005) so a bottle lowered onto the board by its neck is not pressed through.
54
+ """
55
+ import numpy as np
56
+
57
+ from .. import envs
58
+ from ..bddl import write_bddl
59
+ from ..objects import _fmt, _wrap, register_generated
60
+ from ..skills import Skills
61
+ from ..task_base import LFFTask, register_task
62
+
63
+ SOFT = 'solimp="0.9 0.95 0.001" solref="0.02 1"' # the LIBERO table's contact parameters
64
+
65
+ # bottle: square body with a flat 4 x 4 cm bottom + round neck; body origin at the middle of the total height
66
+ BODY = (0.020, 0.020, 0.0375) # half sizes of the body (4 x 4 x 7.5 cm)
67
+ NECK_R, NECK_H = 0.012, 0.015 # neck radius, half height (2.4 cm wide, 3 cm tall) -> 10.5 cm in total
68
+ BH = BODY[2] + NECK_H # half of the total height
69
+ DAMP_BOT = 0.003 # free-joint damping of the bottles (air drag; damps the swing of a bottle hanging from its neck)
70
+ BOT_MASS = 0.25
71
+ W_FRAC = 0.85 # share of the mass in the hidden internal weight
72
+ MU_BOT = 1.0
73
+ COS_UP = 0.95 # upright: long axis within ~18 deg of vertical
74
+ BOT_SOLREF = (0.005, 1.0) # the bottles win in all their contacts (priority 3)
75
+ BOT_SOLIMP = (0.95, 0.99, 0.001, 0.5, 2.0)
76
+
77
+ # tray: board + T handle (stem + cross bar) sticking out of the middle of the trailing long side (tray frame -x)
78
+ PLATE = (0.055, 0.17, 0.006) # 11 x 34 x 1.2 cm board
79
+ STEM = (0.025, 0.015, 0.0125) # 5 long x 3 wide x 2.5 cm tall: grasp it across its width
80
+ CROSS = (0.0125, 0.08, 0.0125) # 2.5 deep x 16 wide x 2.5 cm tall bar at the back: push it with the closed gripper
81
+ # Handle height 2.5 cm (measured on 6 instances x 6 push heights, see the card): the Panda palm reaches ~3-4 cm ahead
82
+ # of the fingers and ~2 cm above the grasp point. With a 3 cm handle a hand pushing low (grasp point ~1 cm above the
83
+ # table) hovered right over the handle and kept the trailing edge from jumping up on the sill (like a grasp: no topple
84
+ # in 3/6); with 2.5 cm every push with the grasp point 1-2.5 cm above the table toppled the top-heavy bottles (36/36).
85
+ # A hand pushing at >= 3 cm only touches the handle with its fingertips and can slide over it.
86
+ PLATE_TOP = envs.TABLE_Z + 2 * PLATE[2]
87
+ BACK_X = -PLATE[0] - 2 * STEM[0] - 2 * CROSS[0] # tray-frame x of the handle's back face (-0.13)
88
+ FOOT_DX = (PLATE[0] + BACK_X) / 2 # x of the footprint centre (board + handle) relative to the board centre
89
+ # slots 1.5 cm towards the leading edge: a hand grasping the cross bar with its long side along the travel direction
90
+ # (palm 10.5 cm ahead of the grasp point) still clears the middle bottle by ~7 mm
91
+ SLOT_LX = 0.015
92
+ SLOT_LY = (-0.12, 0.0, 0.12)
93
+ MU_HANDLE = 0.6
94
+
95
+ # painted areas (inner half sizes: along travel, along the tray's long side)
96
+ LOAD_IN = (0.1125, 0.20) # tray footprint 18.5 x 34 cm -> 2 / 3 cm slack per side
97
+ DELIV_IN = (0.14, 0.21) # -> 4.75 / 4 cm slack per side
98
+ LINE_W = 0.008
99
+ AREA_DIST = (0.32, 0.34) # centre to centre
100
+
101
+ # threshold strip: a capsule lying across the path, sunk into the table so that it sticks out RIDGE_H (a rounded sill
102
+ # 2 * sqrt(2 R h - h^2) = 5.3 cm wide)
103
+ RIDGE_H = 0.010
104
+ RIDGE_R = 0.040
105
+ RIDGE_HL = 0.23 # half length of the straight part (46 cm: longer than the tray)
106
+ MU_RIDGE = 0.4 # wins in its contacts (priority 4)
107
+
108
+ BOTTLES = ("bottle_red_1", "bottle_green_1", "bottle_blue_1")
109
+ COLOR_OF = {"bottle_red_1": "red", "bottle_green_1": "green", "bottle_blue_1": "blue"}
110
+ RGBA = {"red": (0.82, 0.12, 0.10, 1.0), "green": (0.12, 0.60, 0.20, 1.0), "blue": (0.12, 0.30, 0.85, 1.0)}
111
+ TRAY = "tray_1"
112
+ LOAD, DELIVER, RIDGE = "load_area_1", "deliver_area_1", "threshold_1"
113
+
114
+ # hidden COM heights above the bottle's bottom (m); calibration in the task card
115
+ HC_STABLE = (0.020, 0.035)
116
+ HC_TOPHEAVY = (0.066, 0.076)
117
+ N_TOP_P = (0.35, 0.40, 0.25) # P(0 / 1 / 2 top-heavy bottles)
118
+ MU_TRAY = (0.45, 0.60)
119
+
120
+ DEBOUNCE = 5 # control steps a predicate must keep a new value before an event is recorded (0.25 s)
121
+
122
+ # scripted reference moves
123
+ V_NAIVE = 0.045 # the pilot agents pushed at 3-6 cm/s
124
+ V_CAREFUL = 0.02 # the LA interface's slowest speed
125
+ GRASP_TOP = 0.012 # scripted grasp point: on the neck, this far below the bottle's top (the palm is ~2 cm above it)
126
+ SAFE_Z = envs.TABLE_Z + 0.17 # scripted transits: fingertips ~5 cm above the tops of bottles standing on the tray
127
+ SAFE_Z_HELD = envs.TABLE_Z + 0.25 # ... and with a bottle hanging from the gripper: its bottom ~4 cm above them
128
+ PUSH_Z = envs.TABLE_Z + 0.015 # closed-gripper pushes: grasp point 1.5 cm above the table (fingertips ~0.5 cm)
129
+ DRAG_Z = envs.TABLE_Z + 0.015 # grasping the stem: finger pads over its whole height
130
+
131
+
132
+ def bottle_xml(name, rgba):
133
+ zb = -BH + BODY[2]
134
+ zn = -BH + 2 * BODY[2] + NECK_H
135
+ neck_rgba = tuple(0.8 * c for c in rgba[:3]) + (1.0,)
136
+ parts = [("box", zb, _fmt(BODY), rgba), ("cylinder", zn, f"{NECK_R:.5f} {NECK_H:.5f}", neck_rgba)]
137
+ gs = []
138
+ for k, (typ, z, size, c) in enumerate(parts):
139
+ gs.append(f' <geom name="{name}_g{k}" type="{typ}" pos="0 0 {z:.5f}" size="{size}" rgba="{_fmt(c)}" '
140
+ f'density="500" friction="{MU_BOT} 0.005 0.0001" {SOFT} group="0" />')
141
+ gs.append(f' <geom type="{typ}" pos="0 0 {z:.5f}" size="{size}" rgba="{_fmt(c)}" conaffinity="0" '
142
+ f'contype="0" group="1" />')
143
+ return _wrap(name, "\n".join(gs), BH, float(np.hypot(BODY[0], BODY[1])))
144
+
145
+
146
+ def tray_xml(name, rgba=(0.62, 0.45, 0.27, 1.0)):
147
+ hz = -PLATE[2] + STEM[2] # handle bottom flush with the board's bottom
148
+ sp = (-PLATE[0] - STEM[0], 0.0, hz)
149
+ cp = (-PLATE[0] - 2 * STEM[0] - CROSS[0], 0.0, hz)
150
+ hrgba = (0.30, 0.20, 0.12, 1.0)
151
+ gs = []
152
+ for k, (p, s, c, mu) in enumerate((((0, 0, 0), PLATE, rgba, 0.6), (sp, STEM, hrgba, MU_HANDLE),
153
+ (cp, CROSS, hrgba, MU_HANDLE))):
154
+ gs.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
155
+ f'density="500" friction="{mu} 0.005 0.0001" {SOFT} group="0" />')
156
+ gs.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
157
+ f'contype="0" group="1" />')
158
+ return _wrap(name, "\n".join(gs), PLATE[2], float(np.hypot(PLATE[0] - BACK_X, PLATE[1])))
159
+
160
+
161
+ def area_xml(name, inner, fill, line):
162
+ """Flat, visual-only rectangle painted on the table (light fill + dark outline, no collisions)."""
163
+ ix, iy = inner
164
+ ox, oy = ix + LINE_W, iy + LINE_W
165
+ parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill),
166
+ ((0, iy + LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line),
167
+ ((0, -iy - LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line),
168
+ ((ix + LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line),
169
+ ((-ix - LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line)]
170
+ g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
171
+ f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
172
+ return _wrap(name, g, 0.0012, float(np.hypot(ox, oy)))
173
+
174
+
175
+ def sill_xml(name, rgba=(0.12, 0.12, 0.13, 1.0)):
176
+ """the threshold strip: a capsule along the fixture's local y (quat turns z into y), origin on its axis; the
177
+ fixture is placed with the axis RIDGE_R - RIDGE_H below the table top (static: no contacts with the table)"""
178
+ q = "0.70711 0.70711 0 0"
179
+ g = (f' <geom name="{name}_g0" type="capsule" quat="{q}" size="{RIDGE_R:.5f} {RIDGE_HL:.5f}" '
180
+ f'rgba="{_fmt(rgba)}" friction="{MU_RIDGE} 0.005 0.0001" {SOFT} group="0" />\n'
181
+ f' <geom type="capsule" quat="{q}" size="{RIDGE_R:.5f} {RIDGE_HL:.5f}" rgba="{_fmt(rgba)}" '
182
+ f'conaffinity="0" contype="0" group="1" />')
183
+ return _wrap(name, g, RIDGE_R, RIDGE_HL + RIDGE_R)
184
+
185
+
186
+ def _rotz2(a):
187
+ c, s = np.cos(a), np.sin(a)
188
+ return np.array([[c, -s], [s, c]])
189
+
190
+
191
+ def _yaw_of(R):
192
+ return float(np.arctan2(R[1, 0], R[0, 0]))
193
+
194
+
195
+ class TraySkills(Skills):
196
+ """Skills whose every control step feeds the task's stage monitor."""
197
+
198
+ def __init__(self, env, task, recorder=None):
199
+ super().__init__(env, recorder=recorder)
200
+ self.task = task
201
+
202
+ def _act(self, dpos, drot, grip):
203
+ super()._act(dpos, drot, grip)
204
+ self.task.monitor_step()
205
+
206
+
207
+ @register_task
208
+ class TrayDelivery(LFFTask):
209
+ name = "lh_tray_delivery"
210
+ level = "L2"
211
+ category = "state_restoration"
212
+ capabilities = ("Perceive", "Reason", "Plan")
213
+ protocol = "cross"
214
+ max_attempts = 3
215
+ # scripted primitives (~ agent commands): careful oracle 37; naive push + same-attempt repair of 1-2 bottles 46-63
216
+ agent_max_steps = 110
217
+ instruction = ("Load the red, green and blue bottles onto the wooden tray: stand each bottle upright on the tray "
218
+ "while the tray is still inside the yellow loading area. Only after all three bottles are on the "
219
+ "tray, move the tray with the bottles on it over the black threshold strip into the purple "
220
+ "delivery area. At the end the whole tray, including its handle, must be inside the purple area "
221
+ "with all three bottles standing upright on it.")
222
+ instruction_indirect = ("Stand the three bottles up on the wooden board that lies in the yellow rectangle while "
223
+ "the board is still there; then bring the board with the bottles on it across the black "
224
+ "strip into the purple rectangle. At the end the whole board, including its dark handle, "
225
+ "must lie inside the purple rectangle with all three bottles standing on it.")
226
+ agent_object_names = ["red bottle", "green bottle", "blue bottle", "wooden tray", "yellow loading area",
227
+ "purple delivery area", "black threshold strip"]
228
+
229
+ # ------------------------------------------------------------ scene
230
+ def make_bddl(self):
231
+ objs = []
232
+ for i, b in enumerate(BOTTLES):
233
+ c = COLOR_OF[b]
234
+ cat = register_generated(f"LffTdBottle{c.capitalize()}", bottle_xml(f"lff_td_bottle_{c}", RGBA[c]))
235
+ x0 = -0.25 + 0.12 * i
236
+ objs.append((b, cat, f"bottle_{c}_region", (x0, 0.30, x0 + 0.01, 0.31)))
237
+ tray = register_generated("LffTdTray", tray_xml("lff_td_tray"))
238
+ objs.append((TRAY, tray, "tray_region", (0.0, -0.05, 0.01, -0.04)))
239
+ load = register_generated("LffTdLoadArea", area_xml("lff_td_load_area", LOAD_IN, (0.98, 0.93, 0.55, 1.0),
240
+ (0.85, 0.62, 0.05, 1.0)), free=False)
241
+ deliv = register_generated("LffTdDeliverArea", area_xml("lff_td_deliver_area", DELIV_IN,
242
+ (0.86, 0.78, 0.95, 1.0), (0.45, 0.20, 0.65, 1.0)),
243
+ free=False)
244
+ sill = register_generated("LffTdThreshold", sill_xml("lff_td_threshold"), free=False)
245
+ fx = [(LOAD, load, "load_region", (-0.21, -0.41, -0.20, -0.40)),
246
+ (DELIVER, deliv, "deliver_region", (0.15, -0.41, 0.16, -0.40)),
247
+ (RIDGE, sill, "threshold_region", (0.15, 0.38, 0.16, 0.39))]
248
+ return write_bddl(self.name, self.instruction, objs, fx)
249
+
250
+ def __init__(self, cam_res=None):
251
+ super().__init__(cam_res)
252
+ env = self.env
253
+ m = env.sim.model
254
+ self.area_bid = {a: m.body_name2id(env.fixtures_dict[a].root_body) for a in (LOAD, DELIVER, RIDGE)}
255
+ self.bid = {n: envs.body_id(env, n) for n in BOTTLES + (TRAY,)}
256
+ mm = m._model
257
+ self._bvh0 = {}
258
+ for b in BOTTLES: # compiled inertial frame + BVH (shifted with the hidden COM at every reset)
259
+ bid = self.bid[b]
260
+ adr, num = mm.body_bvhadr[bid], mm.body_bvhnum[bid]
261
+ self._bvh0[b] = (m.body_ipos[bid].copy(), mm.bvh_aabb[adr:adr + num].copy(), adr, num)
262
+ # geom -> object index for the contact checks (0..2 bottles, 3 tray)
263
+ self._obj_of = np.full(m.ngeom, -1, int)
264
+ for k, n in enumerate(BOTTLES + (TRAY,)):
265
+ self._obj_of[envs.obj_geom_ids(env, n)] = k
266
+ self._is_robot = np.zeros(m.ngeom, bool)
267
+ self._is_robot[envs.robot_geom_ids(env)] = True
268
+ sb = self.area_bid[RIDGE]
269
+ self._is_sill = np.array([m.geom_bodyid[g] == sb or m.body_parentid[m.geom_bodyid[g]] == sb
270
+ for g in range(m.ngeom)], bool)
271
+ self._dof = {n: envs.free_joint_addr(env, n)[1] for n in BOTTLES + (TRAY,)}
272
+ self.inst = None
273
+ self.mon = None
274
+
275
+ def sample_instance(self, seed):
276
+ """Layout: the tray's long side runs forward / back (world x); it travels sideways (world y) from the loading
277
+ area to the delivery area, 32-34 cm centre to centre, to the left or to the right, over the threshold strip in
278
+ the middle of the gap between the areas. The bottles stand in a row on the table on the far side of the
279
+ loading area. Tray frame: local +x = direction of travel, handle at local -x."""
280
+ rng = np.random.default_rng(seed)
281
+ s = 1.0 if rng.random() < 0.5 else -1.0 # +1: the tray travels to the robot's left (+y)
282
+ xl, yl = float(rng.uniform(-0.18, -0.15)), float(-s * rng.uniform(0.11, 0.13))
283
+ dist = float(rng.uniform(*AREA_DIST))
284
+ deliver = [xl + float(rng.uniform(-0.01, 0.01)), yl + s * dist]
285
+ yaw = s * np.pi / 2
286
+ R = _rotz2(yaw)
287
+ g0, g1 = LOAD_IN[0] + LINE_W, dist - DELIV_IN[0] - LINE_W # the gap between the areas, along travel
288
+ sill_xy = [(xl + deliver[0]) / 2, float((np.array([xl, yl]) + R @ np.array([(g0 + g1) / 2, 0.0]))[1])]
289
+ jit = np.array([rng.uniform(-0.008, 0.008), rng.uniform(-0.005, 0.005)]) # tray frame
290
+ tray_xy = (np.array([xl, yl]) + R @ (np.array([-FOOT_DX, 0.0]) + jit)).tolist()
291
+ order = [int(i) for i in rng.permutation(3)] # bottle -> position in the start row (along x)
292
+ by = yl - s * (LOAD_IN[0] + LINE_W + 0.04)
293
+ start = {}
294
+ for k, b in enumerate(BOTTLES):
295
+ start[b] = [xl + (-0.12, 0.0, 0.12)[order[k]] + float(rng.uniform(-0.008, 0.008)),
296
+ by + float(rng.uniform(-0.005, 0.005)), float(rng.uniform(-0.35, 0.35))]
297
+ n_top = int(rng.choice(3, p=N_TOP_P))
298
+ top = set(int(i) for i in rng.choice(3, n_top, replace=False))
299
+ hc = {b: float(rng.uniform(*(HC_TOPHEAVY if k in top else HC_STABLE))) for k, b in enumerate(BOTTLES)}
300
+ return dict(seed=int(seed), travel="left" if s > 0 else "right", area_yaw=float(yaw), load_xy=[xl, yl],
301
+ deliver_xy=deliver, sill_xy=sill_xy, tray_xy=tray_xy, tray_yaw=float(yaw), bottle_start=start,
302
+ com_height=hc, top_heavy=[b for k, b in enumerate(BOTTLES) if k in top],
303
+ mu_tray=float(rng.uniform(*MU_TRAY)))
304
+
305
+ def _set_com(self, b, hc):
306
+ """Hidden internal weight: bottle COM at height hc above its bottom (mass and inertia consistent)."""
307
+ m = self.env.sim.model
308
+ mm = m._model
309
+ bid = self.bid[b]
310
+ a, c = BODY[0], BODY[2]
311
+ vb, vn = 8 * a * a * c, np.pi * NECK_R ** 2 * 2 * NECK_H
312
+ zs = ((-BH + c) * vb + (-BH + 2 * c + NECK_H) * vn) / (vb + vn) # shell COM (origin: middle of the height)
313
+ ms, mw = BOT_MASS * (1 - W_FRAC), BOT_MASS * W_FRAC
314
+ zw = float(np.clip((BOT_MASS * (hc - BH) - ms * zs) / mw, -BH + 0.01, BH - 0.01))
315
+ zc = (ms * zs + mw * zw) / BOT_MASS
316
+ ww = 0.025 # the weight is a 2.5 cm cube
317
+ Ixx = ms / 3 * (a * a + c * c) + ms * (zs - zc) ** 2 + mw * (zw - zc) ** 2 + mw * ww * ww / 6
318
+ Izz = ms * 2 * a * a / 3 + mw * ww * ww / 6
319
+ m.body_mass[bid] = BOT_MASS
320
+ m.body_ipos[bid] = [0.0, 0.0, zc]
321
+ m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
322
+ m.body_inertia[bid] = [Ixx, Ixx, Izz]
323
+ ip0, A0, adr, num = self._bvh0[b]
324
+ mm.bvh_aabb[adr:adr + num, :3] = A0[:, :3] - (m.body_ipos[bid] - ip0) # BVH lives in the inertial frame
325
+ return zc + BH
326
+
327
+ def apply_instance(self, inst):
328
+ self.inst = inst
329
+ env = self.env
330
+ m = env.sim.model
331
+ ya = inst["area_yaw"]
332
+ qa = [np.cos(ya / 2), 0.0, 0.0, np.sin(ya / 2)]
333
+ for a, key in ((LOAD, "load_xy"), (DELIVER, "deliver_xy")):
334
+ m.body_pos[self.area_bid[a]] = [inst[key][0], inst[key][1], envs.TABLE_Z + 0.0002]
335
+ m.body_quat[self.area_bid[a]] = qa
336
+ m.body_pos[self.area_bid[RIDGE]] = [inst["sill_xy"][0], inst["sill_xy"][1], envs.TABLE_Z + RIDGE_H - RIDGE_R]
337
+ m.body_quat[self.area_bid[RIDGE]] = qa
338
+ for g in np.flatnonzero(self._is_sill): # the sill's friction wins (the tray's would otherwise: priority 2)
339
+ m.geom_friction[g] = [MU_RIDGE, 0.005, 0.0001]
340
+ m.geom_priority[g] = 4
341
+ envs.set_obj_pose(env, TRAY, [inst["tray_xy"][0], inst["tray_xy"][1], envs.TABLE_Z + PLATE[2] + 0.0005],
342
+ yaw=inst["tray_yaw"])
343
+ envs.set_friction(env, TRAY, inst["mu_tray"], priority=2)
344
+ for b in BOTTLES:
345
+ self._set_com(b, inst["com_height"][b])
346
+ for g in envs.obj_geom_ids(env, b): # bottle params win in all its contacts (tray, table, fingers)
347
+ m.geom_friction[g] = [MU_BOT, 0.005, 0.0001]
348
+ m.geom_condim[g] = 3
349
+ m.geom_priority[g] = 3
350
+ m.geom_solref[g] = BOT_SOLREF
351
+ m.geom_solimp[g] = BOT_SOLIMP
352
+ m.dof_damping[self._dof[b]:self._dof[b] + 6] = DAMP_BOT
353
+ x, y, yaw = inst["bottle_start"][b]
354
+ envs.set_obj_pose(env, b, [x, y, envs.TABLE_Z + BH + 0.0005], yaw=yaw)
355
+
356
+ def reset_instance(self, inst, recorder=None):
357
+ self.env.reset()
358
+ self.apply_instance(inst)
359
+ self.env.sim.forward()
360
+ envs.settle(self.env, 10)
361
+ self.sk = TraySkills(self.env, self, recorder=recorder)
362
+ self._init_monitor()
363
+ return self.sk
364
+
365
+ # ------------------------------------------------------------ geometry / predicates
366
+ def tray_pose(self):
367
+ d = self.env.sim.data
368
+ bid = self.bid[TRAY]
369
+ return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
370
+
371
+ def tray_footprint(self):
372
+ p, R = self.tray_pose()
373
+ loc = np.array([[PLATE[0], PLATE[1]], [PLATE[0], -PLATE[1]], [-PLATE[0], PLATE[1]], [-PLATE[0], -PLATE[1]],
374
+ [BACK_X, CROSS[1]], [BACK_X, -CROSS[1]]])
375
+ return p[:2] + loc @ R[:2, :2].T
376
+
377
+ @staticmethod
378
+ def _word(v):
379
+ """robot-centric word for a horizontal world direction"""
380
+ if abs(v[0]) >= abs(v[1]):
381
+ return "forward" if v[0] > 0 else "back"
382
+ return "left" if v[1] > 0 else "right"
383
+
384
+ def area_excess(self, key):
385
+ """How far the tray footprint sticks out of the area (m, >0 = outside) per edge, keyed by robot-centric word."""
386
+ c = np.asarray(self.inst[key])
387
+ Ra = _rotz2(self.inst["area_yaw"])
388
+ pts = (self.tray_footprint() - c) @ Ra # area frame
389
+ inner = LOAD_IN if key == "load_xy" else DELIV_IN
390
+ out = {}
391
+ for axis, sign in ((0, 1), (0, -1), (1, 1), (1, -1)):
392
+ u = np.zeros(2)
393
+ u[axis] = sign
394
+ out[self._word(Ra @ u)] = float((sign * pts[:, axis]).max() - inner[axis])
395
+ return out
396
+
397
+ def tray_inside(self, key):
398
+ return max(self.area_excess(key).values()) <= 0.0
399
+
400
+ def _contacts(self):
401
+ d = self.env.sim.data
402
+ n = d.ncon
403
+ if not n:
404
+ return np.zeros(0, int), np.zeros(0, int)
405
+ return np.asarray(d.contact.geom1)[:n], np.asarray(d.contact.geom2)[:n]
406
+
407
+ def robot_touch(self):
408
+ """indices (0..2 bottles, 3 tray) of the objects the robot touches now"""
409
+ g1, g2 = self._contacts()
410
+ hit = np.concatenate([self._obj_of[g2[self._is_robot[g1]]], self._obj_of[g1[self._is_robot[g2]]]])
411
+ return set(int(i) for i in hit[hit >= 0])
412
+
413
+ def tray_on_sill(self):
414
+ g1, g2 = self._contacts()
415
+ tray = self._obj_of == 3
416
+ return bool(np.any((tray[g1] & self._is_sill[g2]) | (tray[g2] & self._is_sill[g1])))
417
+
418
+ def bottle_state(self, b, touched=False):
419
+ d = self.env.sim.data
420
+ bid = self.bid[b]
421
+ p = d.body_xpos[bid]
422
+ up = float(d.body_xmat[bid].reshape(3, 3)[2, 2])
423
+ tp, R = self.tray_pose()
424
+ loc = R.T @ (p - tp)
425
+ on_xy = abs(loc[0]) <= PLATE[0] and abs(loc[1]) <= PLATE[1]
426
+ resting = abs(loc[2] - (PLATE[2] + BH)) < 0.012
427
+ upright = up >= COS_UP
428
+ return dict(upright=bool(upright), on_tray=bool(on_xy and resting), touched=bool(touched),
429
+ ok=bool(upright and on_xy and resting and not touched), loc=loc, pos=p.copy(), cos=up)
430
+
431
+ def predicates(self):
432
+ t = self.robot_touch()
433
+ st = {b: self.bottle_state(b, k in t)["ok"] for k, b in enumerate(BOTTLES)}
434
+ st["tray_in_delivery"] = self.tray_inside("deliver_xy")
435
+ st["tray_in_loading"] = self.tray_inside("load_xy")
436
+ return st, t
437
+
438
+ def _tray_speed(self):
439
+ da = self._dof[TRAY]
440
+ return float(np.linalg.norm(self.env.sim.data.qvel[da:da + 2]))
441
+
442
+ # ------------------------------------------------------------ monitor
443
+ def _init_monitor(self):
444
+ st, _ = self.predicates()
445
+ self.mon = dict(stable=dict(st), cnt={k: 0 for k in st}, ever=set(k for k, v in st.items() if v),
446
+ lost=set(), events=[], order_step=None, last_touch={k: -10 ** 6 for k in range(4)},
447
+ last_tray_move=-10 ** 6, last_sill=-10 ** 6, tray_vmax_loaded=0.0, left_unloaded=None,
448
+ on_in_loading=set())
449
+
450
+ def monitor_step(self):
451
+ mon = self.mon
452
+ if mon is None:
453
+ return
454
+ n = self.sk.n_steps
455
+ st, touch = self.predicates()
456
+ for k in touch:
457
+ mon["last_touch"][k] = n
458
+ v = self._tray_speed()
459
+ if v > 0.01:
460
+ mon["last_tray_move"] = n
461
+ if self.tray_on_sill():
462
+ mon["last_sill"] = n
463
+ if all(mon["stable"][b] for b in BOTTLES):
464
+ mon["tray_vmax_loaded"] = max(mon["tray_vmax_loaded"], v)
465
+ for k, val in st.items():
466
+ if val == mon["stable"][k]:
467
+ mon["cnt"][k] = 0
468
+ continue
469
+ mon["cnt"][k] += 1
470
+ if mon["cnt"][k] < DEBOUNCE:
471
+ continue
472
+ mon["stable"][k] = val
473
+ mon["cnt"][k] = 0
474
+ step = n - DEBOUNCE + 1
475
+ if val:
476
+ ev = "restored" if k in mon["lost"] else "achieved"
477
+ mon["ever"].add(k)
478
+ mon["events"].append(dict(step=step, pred=k, ev=ev))
479
+ else:
480
+ mon["lost"].add(k)
481
+ e = dict(step=step, pred=k, ev="lost")
482
+ if k == "tray_in_loading" and mon["order_step"] is None and mon["left_unloaded"] is None:
483
+ mon["left_unloaded"] = step # the tray left the loading area before it was loaded
484
+ if k in BOTTLES:
485
+ j = BOTTLES.index(k)
486
+ moving = n - mon["last_tray_move"] <= 30
487
+ # tray motion first: a bottle toppled by the move often falls against the moving hand
488
+ e["cause"] = ("threshold" if moving and n - mon["last_sill"] <= 40 else
489
+ "tray_moving" if moving else
490
+ "robot" if n - mon["last_touch"][j] <= 20 else "other")
491
+ # a bottle taken off (or knocked off by the robot) while the tray is still in the loading area:
492
+ # the tray is no longer loaded -> the order latch has to be earned again (unload / reload trick)
493
+ if (e["cause"] not in ("threshold", "tray_moving") and mon["stable"]["tray_in_loading"]
494
+ and mon["order_step"] is not None):
495
+ mon["order_step"] = None
496
+ mon["lost"].add("loaded_in_loading_area")
497
+ mon["events"].append(e)
498
+ e = dict(step=step, pred="loaded_in_loading_area", ev="lost")
499
+ mon["events"].append(e)
500
+ if mon["stable"]["tray_in_loading"]:
501
+ mon["on_in_loading"] |= {b for b in BOTTLES if mon["stable"][b]}
502
+ if mon["order_step"] is None and mon["stable"]["tray_in_loading"] and all(mon["stable"][b] for b in BOTTLES):
503
+ mon["order_step"] = n
504
+ mon["events"].append(dict(step=n, pred="loaded_in_loading_area",
505
+ ev="restored" if "loaded_in_loading_area" in mon["lost"] else "achieved"))
506
+
507
+ # ------------------------------------------------------------ outcome / F2
508
+ def _static(self):
509
+ d = self.env.sim.data
510
+ for nm in BOTTLES + (TRAY,):
511
+ da = self._dof[nm]
512
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.15:
513
+ return False
514
+ return True
515
+
516
+ def _where(self, b, bs):
517
+ """robot-centric description of where a bottle is (relative to the tray)"""
518
+ if bs["on_tray"]:
519
+ return "on the tray"
520
+ tp, R = self.tray_pose()
521
+ lx, ly = R[:2, :2].T @ (bs["pos"][:2] - tp[:2])
522
+ if abs(lx) <= PLATE[0] and abs(ly) <= PLATE[1]:
523
+ return "on the tray"
524
+ if abs(lx) <= PLATE[0] + 0.04 and abs(ly) <= PLATE[1] + 0.04:
525
+ return "partly on the tray"
526
+ v = R[:2, 0] * np.sign(lx) if abs(lx) - PLATE[0] >= abs(ly) - PLATE[1] else R[:2, 1] * np.sign(ly)
527
+ side = {"forward": "in front of", "back": "behind", "left": "to the left of",
528
+ "right": "to the right of"}[self._word(v)]
529
+ return f"on the table, {side} the tray"
530
+
531
+ @staticmethod
532
+ def _names(bs):
533
+ cols = [COLOR_OF[b] for b in bs]
534
+ if len(cols) == 1:
535
+ return f"the {cols[0]} bottle"
536
+ return "the " + ", the ".join(cols[:-1]) + f" and the {cols[-1]} bottles"
537
+
538
+ def outcome(self, inst):
539
+ sk = self.sk
540
+ sk.hold(30) # let everything settle (keeps the gripper as it is)
541
+ mon = self.mon
542
+ touch = self.robot_touch()
543
+ bst = {b: self.bottle_state(b, k in touch) for k, b in enumerate(BOTTLES)}
544
+ delivered = self.tray_inside("deliver_xy")
545
+ static = self._static()
546
+ order_ok = mon["order_step"] is not None
547
+ all_ok = all(s["ok"] for s in bst.values())
548
+ success = bool(order_ok and delivered and all_ok and static)
549
+ ev = mon["events"]
550
+ stage_preds = set(BOTTLES) | {"tray_in_delivery"}
551
+ n_reg = sum(1 for e in ev if e["ev"] == "lost" and e["pred"] in stage_preds)
552
+ n_res = sum(1 for e in ev if e["ev"] == "restored" and e["pred"] in stage_preds)
553
+ fell_moving = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") in ("threshold",
554
+ "tray_moving")})
555
+ fell_sill = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") == "threshold"})
556
+ fallen = [b for b in BOTTLES if not bst[b]["upright"]]
557
+ off = [b for b in BOTTLES if bst[b]["upright"] and not bst[b]["on_tray"]]
558
+ held = [b for b in BOTTLES if bst[b]["upright"] and bst[b]["on_tray"] and bst[b]["touched"]]
559
+ # failure code = the first unmet requirement, in task order: loading -> order -> bottles -> delivery -> rest
560
+ if not order_ok:
561
+ failure = "order" if mon["left_unloaded"] is not None else "not_loaded"
562
+ elif fallen:
563
+ failure = "bottle_fallen"
564
+ elif off:
565
+ failure = "bottle_off_tray"
566
+ elif not delivered:
567
+ failure = "not_delivered"
568
+ elif held:
569
+ failure = "held"
570
+ elif not static:
571
+ failure = "not_static"
572
+ else:
573
+ failure = None
574
+ # F2 text (robot-centric words, no coordinates); the first sentence names the failure
575
+ parts = []
576
+ if failure == "not_loaded":
577
+ missing = [b for b in BOTTLES if b not in mon["on_in_loading"]]
578
+ parts.append(f"Loading was not completed: {self._names(missing)} never stood on the tray while it was in "
579
+ f"the yellow loading area." if missing else
580
+ "Loading was not completed: the three bottles never stood on the tray at the same time while "
581
+ "it was in the yellow loading area.")
582
+ elif failure == "order":
583
+ parts.append("The tray left the yellow loading area before all three bottles stood on it (load all three "
584
+ "first, then move the loaded tray).")
585
+ bottle_txt = []
586
+ for b in BOTTLES:
587
+ s, col = bst[b], COLOR_OF[b]
588
+ if s["ok"]:
589
+ bottle_txt.append(f"The {col} bottle stands upright on the tray.")
590
+ elif not s["upright"]:
591
+ bottle_txt.append(f"The {col} bottle has fallen over and lies {self._where(b, s)}.")
592
+ elif not s["on_tray"]:
593
+ bottle_txt.append(f"The {col} bottle stands upright {self._where(b, s)}, not on the tray.")
594
+ else:
595
+ bottle_txt.append(f"The {col} bottle stands on the tray but the gripper is still touching it.")
596
+ if delivered:
597
+ tray_txt = "The tray is completely inside the purple delivery area."
598
+ else:
599
+ ex = self.area_excess("deliver_xy")
600
+ out = [f"{max(100 * v, 0.1):.1f} cm beyond its {k} edge" for k, v in ex.items() if v > 0]
601
+ tray_txt = "The tray is not completely inside the purple delivery area: it sticks out " + \
602
+ " and ".join(out) + "."
603
+ if failure in ("not_delivered",):
604
+ parts += [tray_txt] + bottle_txt
605
+ else:
606
+ parts += bottle_txt + [tray_txt]
607
+ if fell_moving:
608
+ how = " while the tray crossed the threshold strip" if fell_sill == fell_moving else \
609
+ " while the tray was moving"
610
+ txt = self._names(fell_moving)
611
+ parts.append(txt[0].upper() + txt[1:] + f" fell over{how}.")
612
+ if failure == "not_static":
613
+ parts.append("Something was still moving at the end.")
614
+ return dict(success=success, failure=failure,
615
+ stages={**{COLOR_OF[b]: bool(bst[b]["ok"]) for b in BOTTLES}, "tray_in_delivery": bool(delivered),
616
+ "loaded_in_loading_area": bool(order_ok), "static": bool(static)},
617
+ events=list(ev), n_regressions=int(n_reg), n_restored=int(n_res),
618
+ order_step=mon["order_step"], left_loading_unloaded=mon["left_unloaded"],
619
+ tray_vmax_loaded=round(mon["tray_vmax_loaded"], 3),
620
+ fell_while_moving=[COLOR_OF[b] for b in fell_moving],
621
+ fell_at_threshold=[COLOR_OF[b] for b in fell_sill], detail=" ".join(parts))
622
+
623
+ # ------------------------------------------------------------ scripted primitives (move_to + gripper only)
624
+ def _slot_world(self, j):
625
+ tp, R = self.tray_pose()
626
+ return tp[:2] + R[:2, :2] @ np.array([SLOT_LX, SLOT_LY[j]])
627
+
628
+ @staticmethod
629
+ def _yaw_window(a):
630
+ """the gripper-symmetric equivalent of yaw `a` in [-0.5, pi - 0.5) (keeps the last wrist joint off its limit)"""
631
+ return float((a + 0.5) % np.pi - 0.5)
632
+
633
+ def tray_yaw(self):
634
+ return _yaw_of(self.tray_pose()[1])
635
+
636
+ def transit(self, xy, z, yaw=None, z_safe=SAFE_Z):
637
+ """up to z_safe (if lower), across, then down to z"""
638
+ sk = self.sk
639
+ e = sk.eef_pos()
640
+ if e[2] < z_safe - 0.01:
641
+ sk.move_to([e[0], e[1], z_safe], speed=0.3)
642
+ sk.move_to([xy[0], xy[1], z_safe], yaw=None if yaw is None else self._yaw_window(yaw), wrap_yaw=False)
643
+ sk.move_to([xy[0], xy[1], z], tol=0.003, max_steps=200)
644
+
645
+ def _travel_dir(self):
646
+ tp, R = self.tray_pose()
647
+ u = R[:2, 0] / np.linalg.norm(R[:2, 0])
648
+ foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0])
649
+ return tp, R, u, float((np.asarray(self.inst["deliver_xy"]) - foot) @ u)
650
+
651
+ def push_tray(self, speed, gap=0.03, segments=1, z=PUSH_Z, yaw=None, approach=None):
652
+ """the pilot agents' move: closed gripper `gap` behind the handle's cross bar (hand's long side along the bar),
653
+ push along the travel direction until the footprint centre is level with the delivery area's centre;
654
+ `segments` > 1 stops in between; `approach` (m/s): first creep up to the bar at that speed, stop, then push"""
655
+ sk = self.sk
656
+ tp, R, u, dist = self._travel_dir()
657
+ back = tp[:2] + R[:2, :2] @ np.array([BACK_X, 0.0])
658
+ if yaw is None: # yaw 0 = fingers closing along world y; this yaw puts the hand's long side across u
659
+ yaw = float(np.arctan2(u[1], u[0]))
660
+ s0 = back - u * (0.012 + gap) # the closed fingers are ~2.4 cm thick along the push
661
+ sk.set_gripper(True, steps=8)
662
+ self.transit(s0, z, yaw=yaw)
663
+ if approach:
664
+ s0 = back - u * 0.010 # just touching
665
+ sk.move_to([s0[0], s0[1], z], speed=approach, tol=0.003, max_steps=int(gap / approach / 0.05) + 40)
666
+ sk.hold(6)
667
+ gap = 0.0
668
+ total = gap + dist
669
+ for k in range(segments):
670
+ e = s0 + u * total * (k + 1) / segments
671
+ sk.move_to([e[0], e[1], z], speed=speed, tol=0.004,
672
+ max_steps=int(total / segments / speed / 0.05) + 60 if speed else 250)
673
+ sk.hold(6)
674
+ e = sk.eef_pos()[:2] - u * 0.03
675
+ sk.move_to([e[0], e[1], z], speed=0.1)
676
+ sk.move_to([e[0], e[1], z + 0.15], speed=0.25)
677
+
678
+ def drag_tray(self, speed, z=DRAG_Z, cross=False):
679
+ """the careful move: grasp the handle and move the tray with it (the hand keeps the trailing edge down on the
680
+ sill). Default: the stem, fingers closing across its 3 cm width (hand's long side along the tray's long side);
681
+ cross=True: the cross bar, fingers closing across its 2.5 cm depth (hand's long side along the travel)."""
682
+ sk = self.sk
683
+ tp, R, u, dist = self._travel_dir()
684
+ lx = -PLATE[0] - 2 * STEM[0] - CROSS[0] if cross else -PLATE[0] - STEM[0]
685
+ c = tp[:2] + R[:2, :2] @ np.array([lx, 0.0])
686
+ yaw = float(np.arctan2(u[1], u[0])) + (np.pi / 2 if cross else 0.0)
687
+ sk.set_gripper(False, steps=8)
688
+ self.transit(c, z, yaw=yaw)
689
+ sk.set_gripper(True, steps=15)
690
+ e = c + u * dist
691
+ sk.move_to([e[0], e[1], z], speed=speed, tol=0.004,
692
+ max_steps=int(dist / speed / 0.05) + 80 if speed else 250)
693
+ sk.hold(6)
694
+ sk.set_gripper(False, steps=12)
695
+ e = sk.eef_pos()
696
+ sk.move_to([e[0], e[1], e[2] + 0.15], speed=0.25)
697
+
698
+ def pick_upright(self, b, jitter=None, yaw=0.0):
699
+ """grasp the neck of a standing bottle from above (the palm stays above the bottle's top)"""
700
+ sk = self.sk
701
+ p = envs.obj_pos(self.env, b)
702
+ top = envs.obj_max_z(self.env, b)
703
+ xy = p[:2] + (np.zeros(2) if jitter is None else jitter)
704
+ sk.set_gripper(False, steps=8)
705
+ self.transit(xy, top - GRASP_TOP, yaw)
706
+ sk.set_gripper(True, steps=15)
707
+ sk.move_to([xy[0], xy[1], SAFE_Z_HELD], speed=0.25)
708
+ return sk.eef_pos()[2] - envs.obj_min_z(self.env, b) # grasp height actually held
709
+
710
+ def place_at(self, b, xy, held_h, release=0.006):
711
+ sk = self.sk
712
+ self.transit(xy, PLATE_TOP + release + held_h + 0.03, z_safe=SAFE_Z_HELD)
713
+ sk.hold(10) # let a hanging bottle stop swinging
714
+ sk.move_to([xy[0], xy[1], PLATE_TOP + release + held_h], speed=0.08, tol=0.003, max_steps=150)
715
+ sk.hold(4)
716
+ sk.set_gripper(False, steps=12)
717
+ sk.move_to([xy[0], xy[1], SAFE_Z], speed=0.25)
718
+
719
+ def load_all(self, rng=None):
720
+ """every bottle goes to the tray slot on the same side as its start position (a carried bottle never passes
721
+ over a standing one); the hand's long side across the row. With `rng`: +-5 mm on every grasp / placement."""
722
+ tp, R = self.tray_pose()
723
+ ay = R[:2, 1]
724
+ yaw = self.tray_yaw() - np.pi / 2
725
+ by_y = sorted(BOTTLES, key=lambda b: float(np.asarray(self.inst["bottle_start"][b][:2]) @ ay))
726
+ for j, b in enumerate(by_y):
727
+ jg, jp = (None, None) if rng is None else (rng.uniform(-0.005, 0.005, 2), rng.uniform(-0.005, 0.005, 2))
728
+ h = self.pick_upright(b, jitter=jg, yaw=yaw)
729
+ self.place_at(b, self._slot_world(j) + (0 if jp is None else jp), h)
730
+
731
+ def free_slot(self, exclude):
732
+ """a tray slot at least 7 cm from every other bottle (standing or lying); among those the one farthest from the
733
+ robot; else the emptiest slot"""
734
+ tp, R = self.tray_pose()
735
+ others = [R[:2, :2].T @ (self.bottle_state(o)["pos"][:2] - tp[:2]) for o in BOTTLES if o not in exclude]
736
+ cand = []
737
+ for j, ly in enumerate(SLOT_LY):
738
+ dmin = min([np.linalg.norm(np.array([SLOT_LX, ly]) - o) for o in others] + [1.0])
739
+ cand.append((dmin >= 0.07, float(self._slot_world(j)[0]) if dmin >= 0.07 else dmin, j))
740
+ return self._slot_world(max(cand)[2])
741
+
742
+ def restand(self, b):
743
+ """a fallen bottle: grasp its neck across (fingers closing across the neck), lift -- it swings down and hangs
744
+ from the neck -- and set it down on a free slot. A bottle standing off the tray: pick it up by the neck."""
745
+ sk = self.sk
746
+ st = self.bottle_state(b)
747
+ if st["upright"]:
748
+ h = self.pick_upright(b, yaw=self.tray_yaw() - np.pi / 2)
749
+ self.place_at(b, self.free_slot({b}), h)
750
+ return
751
+ for tries in range(2):
752
+ st = self.bottle_state(b)
753
+ R = self.env.sim.data.body_xmat[self.bid[b]].reshape(3, 3)
754
+ ax = R[:, 2] # bottle axis (bottom -> neck)
755
+ u = ax[:2] / max(np.linalg.norm(ax[:2]), 1e-6)
756
+ neck = st["pos"] + ax * (BH - GRASP_TOP)
757
+ yaw = float(np.arctan2(u[1], u[0])) # fingers close across the neck
758
+ sk.set_gripper(False, steps=8)
759
+ self.transit(neck[:2], max(neck[2], envs.TABLE_Z + 0.008), yaw)
760
+ sk.set_gripper(True, steps=15)
761
+ if sk.holding(b) or tries:
762
+ break
763
+ # a finger landed on the tray's edge next to the neck: slide the bottle 5 cm away from the tray, retry
764
+ tp = self.tray_pose()[0]
765
+ v = st["pos"][:2] - tp[:2]
766
+ v = v / max(np.linalg.norm(v), 1e-6)
767
+ sk.set_gripper(False, steps=8)
768
+ sk.move_to(sk.eef_pos() + [0.0, 0.0, 0.05], speed=0.1)
769
+ self.push_point(st["pos"][:2] - v * 0.015, v, 0.065, speed=0.05, z=PLATE_TOP + 0.012)
770
+ sk.move_to([neck[0], neck[1], SAFE_Z_HELD], speed=0.15)
771
+ sk.hold(20)
772
+ held = sk.eef_pos()[2] - envs.obj_min_z(self.env, b)
773
+ self.place_at(b, self.free_slot({b}), held)
774
+
775
+ def push_point(self, p, u, dist, speed=0.03, z=None):
776
+ """closed gripper: from 3 cm behind point `p` (direction `u`) push `dist` metres along u, back off, lift"""
777
+ sk = self.sk
778
+ z = PUSH_Z if z is None else z
779
+ s0 = np.asarray(p) - u * 0.03
780
+ sk.set_gripper(True, steps=8)
781
+ self.transit(s0, z, yaw=float(np.arctan2(u[1], u[0])))
782
+ e = s0 + u * (0.018 + dist)
783
+ sk.move_to([e[0], e[1], z], speed=speed, tol=0.003, max_steps=600)
784
+ sk.hold(4)
785
+ e = sk.eef_pos()[:2] - u * 0.03
786
+ sk.move_to([e[0], e[1], z], speed=0.1)
787
+ sk.move_to([e[0], e[1], SAFE_Z], speed=0.25)
788
+
789
+ def fix_tray(self, speed=V_CAREFUL):
790
+ """straighten the tray by slowly pushing the trailing corner that lags behind, then grasp the handle's stem
791
+ and move the tray, without turning it, until its footprint is centred in the delivery area"""
792
+ sk = self.sk
793
+ y1 = self.inst["area_yaw"]
794
+ u1 = _rotz2(y1)[:, 0]
795
+ for _ in range(3):
796
+ err = (self.tray_yaw() - y1 + np.pi) % (2 * np.pi) - np.pi
797
+ if abs(err) < np.radians(3):
798
+ break
799
+ tp, R = self.tray_pose()
800
+ corners = [tp[:2] + R[:2, :2] @ np.array([-PLATE[0], e * (PLATE[1] - 0.02)]) for e in (1.0, -1.0)]
801
+ a = [float((c - tp[:2]) @ u1) for c in corners]
802
+ k = int(np.argmin(a))
803
+ self.push_point(corners[k], u1, 0.6 * (max(a) - min(a)), speed=speed)
804
+ tp, R = self.tray_pose()
805
+ h0 = tp[:2] + R[:2, :2] @ np.array([-PLATE[0] - STEM[0], 0.0])
806
+ foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0])
807
+ h1 = h0 + (np.asarray(self.inst["deliver_xy"]) - foot)
808
+ d = float(np.linalg.norm(h1 - h0))
809
+ if d < 0.004:
810
+ return
811
+ sk.set_gripper(False, steps=8)
812
+ self.transit(h0, DRAG_Z, yaw=self.tray_yaw()) # fingers close across the stem's width
813
+ sk.set_gripper(True, steps=15)
814
+ sk.move_to([h1[0], h1[1], DRAG_Z], speed=speed, tol=0.003, max_steps=int(d / speed / 0.05) + 80)
815
+ sk.hold(5)
816
+ sk.set_gripper(False, steps=12)
817
+ e = sk.eef_pos()
818
+ sk.move_to([e[0], e[1], SAFE_Z], speed=0.2)
819
+
820
+ def check_and_restore(self, rounds=3):
821
+ """the final check: bottles not upright on the tray -> stand them up on a free slot (farthest from the robot
822
+ first); then, if the tray is not completely in the delivery area, move it there slowly by the handle"""
823
+ for _ in range(rounds):
824
+ bad = [b for b in BOTTLES if not self.bottle_state(b)["ok"]]
825
+ if not bad and self.tray_inside("deliver_xy"):
826
+ return
827
+ for b in sorted(bad, key=lambda o: -float(self.bottle_state(o)["pos"][0])):
828
+ self.restand(b)
829
+ self.sk.hold(10)
830
+ if not self.tray_inside("deliver_xy"):
831
+ self.fix_tray()
832
+ self.sk.hold(10)
833
+
834
+ def execute(self, inst, params):
835
+ rng = np.random.default_rng(params.get("seed")) if params.get("jitter") else None
836
+ self.load_all(rng)
837
+ if params.get("mode", "push") == "drag":
838
+ self.drag_tray(params["speed"])
839
+ else:
840
+ self.push_tray(params["speed"], gap=params.get("gap", 0.03), segments=params.get("segments", 1))
841
+ if params.get("check"):
842
+ self.check_and_restore()
843
+
844
+ def default_params(self, inst):
845
+ """naive = the pilot agents' style: load all three, push the handle with the closed gripper at ~4.5 cm/s"""
846
+ return dict(speed=V_NAIVE, mode="push", check=False)
847
+
848
+ def oracle_params(self, inst):
849
+ return dict(speed=V_CAREFUL, mode="drag", check=True)
850
+
851
+ def adapt_params(self, inst, history):
852
+ return dict(speed=V_CAREFUL, mode="drag", check=True)
853
+
854
+ def blind_params(self, inst, attempt, rng):
855
+ return dict(speed=float(rng.uniform(0.03, 0.06)), mode="push", segments=int(rng.integers(1, 3)),
856
+ check=False, jitter=True, seed=int(rng.integers(1 << 30)))
857
+
858
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
859
+ """cross protocol; adaptive = naive + check-and-restore in attempt 1, careful (drag by the handle) + check
860
+ afterwards"""
861
+ k = k or self.max_attempts
862
+ rng = np.random.default_rng(seed)
863
+ history = []
864
+ for a in range(k):
865
+ self.reset_instance(inst)
866
+ if kind == "oracle":
867
+ params = self.oracle_params(inst)
868
+ elif kind == "naive":
869
+ params = self.default_params(inst)
870
+ elif kind == "adaptive":
871
+ params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
872
+ elif kind == "blind":
873
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
874
+ else:
875
+ raise ValueError(kind)
876
+ self.execute(inst, params)
877
+ out = self.outcome(inst)
878
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
879
+ if on_attempt:
880
+ on_attempt(a, params, out)
881
+ if out["success"] or kind in ("oracle", "naive"):
882
+ break
883
+ return history
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-task specs for the controlled arms of full5 (2026-10-12, docs/14 §6).
2
+
3
+ One module per task, named exactly like the task (lffbench/arm_specs/<task_name>.py), defining:
4
+
5
+ HIDDEN_KEYS : tuple of instance keys that carry the hidden variable(s)
6
+ h0(inst) -> dict overrides for the H0 twin: same layout, hidden variable at its "ordinary" value, so the
7
+ common-sense first attempt succeeds (scripted naive succeeds)
8
+ twin(inst) -> dict overrides for the mismatched-history source: same layout, the trap is still active (scripted
9
+ naive still fails, visibly) but the right correction is different from the original instance's,
10
+ ideally opposite (e.g. centre of mass on the other side)
11
+ reveal(inst)-> str H+ text appended to the task instruction: the hidden variable stated plainly in robot-frame
12
+ words a careful human could act on, without prescribing the solution
13
+
14
+ All three take the ORIGINAL sampled instance and return only the keys to change (JSON-serialisable). The server
15
+ applies them with dict.update() after sample_instance(); reset_instance() must honour them.
16
+ """
17
+ import importlib
18
+
19
+
20
+ def load(task_name):
21
+ """The spec module for task_name, or None if the task has no controlled-arm spec."""
22
+ try:
23
+ return importlib.import_module(f"{__name__}.{task_name}")
24
+ except ModuleNotFoundError as e:
25
+ if e.name == f"{__name__}.{task_name}":
26
+ return None
27
+ raise
28
+
29
+
30
+ def overrides(task_name, arm, inst):
31
+ """Instance overrides for arm in (h0, twin); {} for other arms."""
32
+ if arm not in ("h0", "twin"):
33
+ return {}
34
+ spec = load(task_name)
35
+ if spec is None:
36
+ raise SystemExit(f"--arm {arm}: no spec in lffbench/arm_specs/{task_name}.py")
37
+ return getattr(spec, arm)(inst)
38
+
39
+
40
+ def reveal(task_name, inst):
41
+ spec = load(task_name)
42
+ if spec is None:
43
+ raise SystemExit(f"--arm hplus: no spec in lffbench/arm_specs/{task_name}.py")
44
+ return spec.reveal(inst)
45
+
46
+
47
+ def fix(task_name, inst, params):
48
+ """Fix-rung text of the layer-3 feedback ladder (docs/20): how to succeed on this instance, in robot-frame words,
49
+ built from the task's oracle parameters `params` (task.oracle_params(inst), computed by the caller with the sim)."""
50
+ spec = load(task_name)
51
+ if spec is None or not hasattr(spec, "fix"):
52
+ raise SystemExit(f"ladder fix: no fix() in lffbench/arm_specs/{task_name}.py")
53
+ return spec.fix(inst, params)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_under_table_tool.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l3_under_table_tool (2026-10-12).
2
+
3
+ Hidden variable: inst["pane_side"] -- the y side of the low glass table that is closed by an invisible clear acrylic
4
+ panel (+1 = robot's left, -1 = right; sampled as -side, i.e. the side away from the stick, where the bin stands).
5
+ apply_instance turns on the collision of the panel whose side equals pane_side (inst.get("pane_side", -side)); a
6
+ value matching neither side (0) leaves both panels off.
7
+
8
+ h0 pane_side = 0: no panel. The prior (slide the stick in and push the cube straight across, out towards the bin)
9
+ gets the cube out on the bin's side, then grasps it and drops it in the bin.
10
+ twin pane_side = side: the panel closes the OTHER y side -- the side the stick lies on -- instead of the bin's side.
11
+ The prior still fails visibly, but differently: the stick's head runs into the panel at the table edge and
12
+ the cube is not touched / stays under the glass (original: the cube is pushed across and stops against the
13
+ panel at the bin's side). The blocked side is the opposite one. Measured (seeds 3000-3004): twin naive fails
14
+ 5/5 with F2 mode "blocked" (stick stopped at the panel, the hand ran into the glass edge, cube did not move).
15
+ Limitation: with a single panel on a y side, the reference correction is the same in both (push the cube out
16
+ of the open FRONT side from behind the table; oracle_params ignores the instance), so the cross check
17
+ "twin oracle on the original" succeeds (measured 5/5). A twin whose correction fails on the original would need a second
18
+ panel / panels on the front or back side plus a new scripted push (task-file change); not done.
19
+ reveal Which side is closed, in the words of the task's F2 feedback.
20
+ """
21
+ HIDDEN_KEYS = ("pane_side",)
22
+
23
+
24
+ def _pane_side(inst):
25
+ return int(inst.get("pane_side", -inst["side"]))
26
+
27
+
28
+ def h0(inst):
29
+ return {"pane_side": 0}
30
+
31
+
32
+ def twin(inst):
33
+ return {"pane_side": -_pane_side(inst)}
34
+
35
+
36
+ def reveal(inst):
37
+ ps = _pane_side(inst)
38
+ lr = "the robot's left" if ps > 0 else "the robot's right"
39
+ return (f"A clear acrylic panel, invisible in the camera images, closes the side of the low glass table on {lr} "
40
+ f"(between its two legs, from the tabletop up to the glass); nothing can pass under the table edge on that "
41
+ f"side.")
42
+
43
+
44
+ def fix(inst, params):
45
+ """Ladder Fix rung (docs/20): oracle mode front -- push the cube out of the low table's front side with the stick."""
46
+ return ("A way to succeed: do not push the cube out on the panel's side. Pick the stick up, turn it in the air so "
47
+ "that it points forward (away from the robot), put it down on the table behind the low table (on the "
48
+ "robot's side), in line with the cube. Grasp it again near its handle end and slide it straight forward "
49
+ "under the glass top so that its head pushes the cube out of the low table's front side (the side away "
50
+ "from the robot). Then pull the stick back, put it down, grasp the cube and put it into the bin.")
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath.
2
+
3
+ protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only)
4
+ executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here)
5
+ session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session
6
+ tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed)
7
+ fake_driver.py a driver backed by the simulator (no hardware)
8
+ driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py)
9
+ DRIVER.md spec for the driver author and the operator
10
+ """
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l2_turntable.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the
2
+ turntable back exactly the way it was.
3
+
4
+ Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper
5
+ always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet
6
+ top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet
7
+ placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an
8
+ articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is
9
+ operable with move_to + open/close only.
10
+
11
+ Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed
12
+ shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be
13
+ grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp
14
+ height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim
15
+ turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square,
16
+ green dot; visual only) make the disc's angle readable. The basket stands on the robot's left.
17
+
18
+ Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the
19
+ agent must turn the disc by 136-179 deg (start angle random; measured on seeds 1000-1019). An agent that puts the butter into the basket
20
+ and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start
21
+ angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle:
22
+ it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the
23
+ turntable is not turned the way it was, never by how much or which way.
24
+
25
+ Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
26
+ round; the outcome (success + F2 text) is computed after each round.
27
+
28
+ Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only)
29
+ oracle turns, takes the butter, then immediately turns the disc back to the saved start angle.
30
+ naive turns, takes the butter, done.
31
+ adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve +
32
+ Utilize); redoes the main task if the butter is not in the basket.
33
+ blind no history, no feedback: every later round redoes the main task (lifts the butter out of the
34
+ basket and drops it back, grasp jittered by 5 mm).
35
+ nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a
36
+ random angle in (-180, 180] deg each round.
37
+
38
+ Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg;
39
+ a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at
40
+ ~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round).
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _fmt, register_generated
47
+ from ..task_base import LFFTask, register_task
48
+
49
+ TT = "turntable_1"
50
+ TARGET = "butter_1"
51
+ ITEMS = (TARGET,)
52
+ BASKET = "basket_1"
53
+ MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g)
54
+
55
+ # turntable geometry (fixture frame: origin on the table top at the disc axis)
56
+ R = 0.17 # disc radius
57
+ DISC_T = 0.012 # disc thickness
58
+ BASE_H = 0.012 # pedestal height
59
+ DISC_TOP = BASE_H + DISC_T # disc top above the table
60
+ PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc
61
+ # (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them)
62
+ PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame
63
+ STRIPE_ANG = np.pi # disc frame
64
+ BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table
65
+ BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc)
66
+ HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released
67
+ ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm
68
+
69
+ ANG_TOL = np.radians(15.0) # success: disc within 15 deg of its start angle (4 cm at the pegs, 2.6 cm at the stripe end)
70
+ BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor
71
+ BASKET_RIM = 0.150
72
+ BASKET_FLOOR = 0.017
73
+ SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
74
+
75
+ NAMES = {TARGET: "butter"}
76
+ DESCR = {TARGET: "small orange box"}
77
+
78
+
79
+ def _wrap(a):
80
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
81
+
82
+
83
+ def _wrap_half(a):
84
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
85
+
86
+
87
+ def _rot(a):
88
+ c, s = np.cos(a), np.sin(a)
89
+ return np.array([[c, -s], [s, c]])
90
+
91
+
92
+ def turntable_xml(model_name):
93
+ """Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks."""
94
+ def geoms(kind, pos, size, rgba, coll=True, vis=True):
95
+ s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"'
96
+ out = [f'<geom {s} conaffinity="0" contype="0" group="1" />'] if vis else []
97
+ if coll:
98
+ out.insert(0, f'<geom {s} friction="1.0 0.005 0.0001" {SOLID} density="400" group="0" />')
99
+ return out
100
+
101
+ shelf = (0.82, 0.82, 0.80, 1.0)
102
+ fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0))
103
+ by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04
104
+ fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf)
105
+ fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf)
106
+ # the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a
107
+ # single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured)
108
+ disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False)
109
+ disc += geoms("box", (0, 0, 0), (R / np.sqrt(2), R / np.sqrt(2), DISC_T / 2), (0.62, 0.42, 0.24, 1.0), vis=False)
110
+ for a in PEG_ANG:
111
+ disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2),
112
+ (PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0))
113
+ # painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot
114
+ disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006),
115
+ (0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False)
116
+ disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006),
117
+ (0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False)
118
+ disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006),
119
+ (0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False)
120
+ nl = "\n "
121
+ return f"""<mujoco model="{model_name}">
122
+ <worldbody>
123
+ <body>
124
+ <body name="object">
125
+ {nl.join(fixed)}
126
+ <body name="disc" pos="0 0 {BASE_H + DISC_T / 2:.5f}">
127
+ <joint name="spin" type="hinge" axis="0 0 1" pos="0 0 0" limited="false" damping="{HINGE['damping']}" armature="{HINGE['armature']}" frictionloss="{HINGE['frictionloss']}" />
128
+ {nl.join(disc)}
129
+ </body>
130
+ </body>
131
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
132
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {BOARD_Z + 0.008:.5f}" name="top_site" />
133
+ <site rgba="0 0 0 0" size="0.005" pos="{R:.5f} {R:.5f} 0" name="horizontal_radius_site" />
134
+ </body>
135
+ </worldbody>
136
+ </mujoco>
137
+ """
138
+
139
+
140
+ @register_task
141
+ class TurntableRestore(LFFTask):
142
+ name = "l2_turntable_restore"
143
+ level = "L2"
144
+ category = "state_restoration"
145
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
146
+ protocol = "within"
147
+ max_attempts = 5
148
+ instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the "
149
+ "turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.")
150
+ instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the "
151
+ "shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be "
152
+ "turned exactly the way it is now.")
153
+
154
+ def __init__(self, cam_res=None):
155
+ super().__init__(cam_res)
156
+ m = self.env.sim.model
157
+ self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body)
158
+ jid = m.joint_name2id(f"{TT}_spin")
159
+ self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid]
160
+ self.start = {}
161
+ self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics)
162
+ self._home = None
163
+ self._c = np.zeros(2)
164
+
165
+ # ------------------------------------------------------------ scene
166
+ def make_bddl(self):
167
+ tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False)
168
+ objs = [(n, n[:-2], f"r_{i}", (0.20, -0.25 + 0.15 * i, 0.22, -0.23 + 0.15 * i)) for i, n in enumerate(ITEMS)]
169
+ objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26)))
170
+ fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance
171
+ return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx)
172
+
173
+ def sample_instance(self, seed):
174
+ rng = np.random.default_rng(seed)
175
+ c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)])
176
+ th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg)
177
+ rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS}
178
+ tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial
179
+ # start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis)
180
+ q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40))))
181
+ return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt,
182
+ basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))])
183
+
184
+ def disc_angle(self):
185
+ return float(self.env.sim.data.qpos[self._qa])
186
+
187
+ def to_world(self, r, th, q=None):
188
+ q = self.disc_angle() if q is None else q
189
+ return self._c + r * np.array([np.cos(th + q), np.sin(th + q)])
190
+
191
+ def to_disc(self, xy, q=None):
192
+ q = self.disc_angle() if q is None else q
193
+ return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c)
194
+
195
+ def place(self, name, xy, yaw, surface_z):
196
+ """Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z."""
197
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3],
198
+ quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]))
199
+ self.env.sim.forward()
200
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
201
+ qa, _ = envs.free_joint_addr(self.env, name)
202
+ self.env.sim.data.qpos[qa + 2] -= dz
203
+ self.env.sim.forward()
204
+
205
+ def apply_instance(self, inst):
206
+ m, d = self.env.sim.model, self.env.sim.data
207
+ self._c = np.array(inst["center"], float)
208
+ m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z]
209
+ m.body_quat[self._tt_bid] = [1, 0, 0, 0]
210
+ d.qpos[self._qa] = inst["q0"]
211
+ d.qvel[self._qv] = 0.0
212
+ self.env.sim.forward()
213
+ for n in ITEMS:
214
+ envs.scale_mass(self.env, n, MASS[n])
215
+ th = inst["theta"][n]
216
+ # long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board
217
+ self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n],
218
+ envs.TABLE_Z + DISC_TOP)
219
+ envs.scale_mass(self.env, BASKET, 2.0)
220
+ self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z)
221
+ self.env.sim.forward()
222
+
223
+ def reset_instance(self, inst, recorder=None):
224
+ sk = super().reset_instance(inst, recorder)
225
+ self.start = dict(q=self.disc_angle())
226
+ self._home = sk.eef_pos()
227
+ return sk
228
+
229
+ # ------------------------------------------------------------ measurements
230
+ def footprint(self, name):
231
+ """AABB centre, yaw of the long horizontal axis, z range (scripted 'perception')."""
232
+ m, d = self.env.sim.model, self.env.sim.data
233
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
234
+ best = None
235
+ for g in envs.obj_geom_ids(self.env, name):
236
+ Rg = d.geom_xmat[g].reshape(3, 3)
237
+ c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
238
+ e = np.abs(Rg) @ m.geom_aabb[g, 3:]
239
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
240
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
241
+ if best is None or vol > best[0]:
242
+ best = (vol, Rg, m.geom_aabb[g, 3:])
243
+ _, Rg, half = best
244
+ horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0])
245
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
246
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
247
+ zmin=float(lo[2]), zmax=float(hi[2]))
248
+
249
+ def item_loc(self, name):
250
+ f = self.footprint(name)
251
+ c = np.array(f["center"])
252
+ held = self.sk is not None and self.sk.holding(name)
253
+ if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01:
254
+ return "gripper", f
255
+ bp = envs.obj_pos(self.env, BASKET)
256
+ if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM \
257
+ and f["zmin"] > envs.TABLE_Z + 0.005:
258
+ return "basket", f
259
+ on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012
260
+ if on_disc:
261
+ return "turntable", f
262
+ if f["zmin"] < envs.TABLE_Z + 0.01:
263
+ return "table", f
264
+ return "other", f
265
+
266
+ def outcome(self, inst):
267
+ envs.settle(self.env, 30)
268
+ tloc, _ = self.item_loc(TARGET)
269
+ dq = _wrap(self.disc_angle() - self.start["q"])
270
+ turned_ok = abs(dq) <= ANG_TOL
271
+ success = bool(tloc == "basket" and turned_ok)
272
+ return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1),
273
+ turned_ok=bool(turned_ok),
274
+ detail=self._describe(tloc, turned_ok, dq, NAMES),
275
+ detail_indirect=self._describe(tloc, turned_ok, dq, DESCR),
276
+ detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True))
277
+
278
+ @staticmethod
279
+ def _describe(tloc, turned_ok, dq, names, offset=False):
280
+ tn = names[TARGET]
281
+ msgs = []
282
+ if tloc != "basket":
283
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
284
+ "turntable": f"The {tn} is still on the turntable, not in the basket.",
285
+ "table": f"The {tn} is on the table, not in the basket."}
286
+ .get(tloc, f"The {tn} is not in the basket."))
287
+ if not turned_ok:
288
+ m = "The turntable is not turned the way it was at the start."
289
+ if offset: # ablation tier: relative measurement, externalises the memory
290
+ m += (f" It is turned {abs(np.degrees(dq)):.0f} deg "
291
+ f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.")
292
+ msgs.append(m)
293
+ if not msgs:
294
+ msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.")
295
+ return " ".join(msgs)
296
+
297
+ def feedback(self, inst, out, level="F2", indirect=False, offset=False):
298
+ """F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off).
299
+ offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle."""
300
+ if level == "F2":
301
+ key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
302
+ out = dict(out, detail=out.get(key, out["detail"]))
303
+ return super().feedback(inst, out, level)
304
+
305
+ # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper)
306
+ SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items
307
+ PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on
308
+ # the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while
309
+ # carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit)
310
+ WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board)
311
+
312
+ def go_home(self):
313
+ sk = self.sk
314
+ p = sk.eef_pos()
315
+ sk.move_to([p[0], p[1], max(p[2], self._home[2])])
316
+ sk.move_to(self._home, yaw=0.0)
317
+
318
+ def _settle_yaw(self, tol=np.radians(3), max_steps=40):
319
+ """move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent
320
+ that starts mid-rotation swipes the open fingers across the pegs -- measured)."""
321
+ sk = self.sk
322
+ for _ in range(max_steps // 5):
323
+ R = sk.eef_mat() @ sk.R0.T
324
+ if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol:
325
+ return
326
+ sk.hold(5)
327
+
328
+ def peg_azimuths(self):
329
+ return [_wrap(self.disc_angle() + a) for a in PEG_ANG]
330
+
331
+ def turn(self, delta, step=np.radians(10)):
332
+ """Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side,
333
+ move the gripper along the rim in short straight segments, release, repeat."""
334
+ sk = self.sk
335
+ zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012
336
+ rem = float(delta)
337
+ for _ in range(6):
338
+ if abs(rem) < np.radians(1.0):
339
+ break
340
+ az = self.peg_azimuths()
341
+ if rem > 0:
342
+ cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)]
343
+ a0 = min(cands)
344
+ sweep = min(rem, self.WIN[1] - a0)
345
+ else:
346
+ cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6]
347
+ a0 = max(cands)
348
+ sweep = max(rem, self.WIN[0] - a0)
349
+ q_before = self.disc_angle()
350
+ p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)])
351
+ sk.set_gripper(False, steps=6)
352
+ # up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open
353
+ # fingers sweep the disc (measured: turned it 38 deg the wrong way)
354
+ cur = sk.eef_pos()
355
+ if cur[2] < self.SAFE_Z - 0.02:
356
+ sk.move_to([cur[0], cur[1], self.SAFE_Z])
357
+ sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x
358
+ self._settle_yaw()
359
+ sk.move_to([p[0], p[1], zg + 0.03], speed=0.4)
360
+ sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80)
361
+ sk.set_gripper(True, steps=12)
362
+ dbg = dict(off=np.round((sk.eef_pos() - np.r_[self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]), zg]) * 100, 1).tolist(),
363
+ w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1),
364
+ yaw=round(float(np.degrees(sk.yaw)), 0))
365
+ k = max(1, int(np.ceil(abs(sweep) / step)))
366
+ for i in range(1, k + 1):
367
+ w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)])
368
+ sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40)
369
+ sk.set_gripper(False, steps=8)
370
+ pe = sk.eef_pos()
371
+ sk.move_to([pe[0], pe[1], zg + 0.10])
372
+ got = _wrap(self.disc_angle() - q_before)
373
+ self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1),
374
+ got=round(float(np.degrees(got)), 1), **dbg))
375
+ rem -= got
376
+
377
+ def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0):
378
+ """Top-down pick across the short side, carry, release just above support_z at dest_xy."""
379
+ sk = self.sk
380
+ f = fp or self.footprint(name)
381
+ c = np.array(f["center"])
382
+ gyaw = _wrap_half(f["yaw"])
383
+ zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145)
384
+ sk.set_gripper(False, steps=6)
385
+ p = sk.eef_pos()
386
+ if p[2] < travel_z - 0.02:
387
+ sk.move_to([p[0], p[1], travel_z])
388
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
389
+ self._settle_yaw()
390
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
391
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
392
+ sk.set_gripper(True, steps=12)
393
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
394
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw)
395
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + 0.006], tol=0.003, speed=0.2, max_steps=150)
396
+ sk.hold(4)
397
+ sk.set_gripper(False, steps=10)
398
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
399
+
400
+ def butter_to_basket(self, fp=None):
401
+ """The main task: if the butter is on the turntable, turn it to the open side first."""
402
+ loc, f = self.item_loc(TARGET)
403
+ if loc == "turntable":
404
+ az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0])
405
+ # bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge;
406
+ # a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ
407
+ delta = _wrap_half(f["yaw"] - az)
408
+ self.turn(_wrap(self.PICK_AZ - delta - az))
409
+ b = envs.obj_pos(self.env, BASKET)
410
+ # release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long
411
+ # hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured)
412
+ self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp)
413
+
414
+ def do(self, actions):
415
+ for act in actions:
416
+ if act[0] == "butter_to_basket":
417
+ self.butter_to_basket(fp=act[1] if len(act) > 1 else None)
418
+ elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)]
419
+ self.turn(_wrap(act[1] - self.disc_angle()))
420
+ elif act[0] == "turn_by":
421
+ self.turn(act[1])
422
+ else:
423
+ raise ValueError(act)
424
+
425
+ # ------------------------------------------------------------ scripted reference policies
426
+ def _plan(self, kind, inst, a, history, rng, memory):
427
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
428
+ return [["butter_to_basket"]]
429
+ if kind == "oracle":
430
+ return [["butter_to_basket"], ["turn_to", memory["q"]]]
431
+ last = history[-1]["outcome"]
432
+ acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]]
433
+ if kind == "adaptive":
434
+ return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]])
435
+ if kind == "nomem":
436
+ return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]])
437
+ if kind == "blind":
438
+ fp = self.footprint(TARGET)
439
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
440
+ return [["butter_to_basket", fp]]
441
+ raise ValueError(kind)
442
+
443
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
444
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
445
+ k = k or self.max_attempts
446
+ rng = np.random.default_rng(seed)
447
+ history = []
448
+ self.reset_instance(inst)
449
+ memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame)
450
+ for a in range(k):
451
+ actions = self._plan(kind, inst, a, history, rng, memory)
452
+ self.do(actions)
453
+ self.go_home()
454
+ out = self.outcome(inst)
455
+ params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else [])
456
+ for x in actions])
457
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
458
+ if on_attempt:
459
+ on_attempt(a, params, out)
460
+ if out["success"] or kind in ("oracle", "naive"):
461
+ break
462
+ return history
463
+
464
+ # cross-protocol hooks are not used by this task
465
+ def default_params(self, inst):
466
+ return dict(policy="naive")
467
+
468
+ def oracle_params(self, inst):
469
+ return dict(policy="oracle")
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l3_card_shelf.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3 card_shelf (2026-10-12): a deepened l3_card_edge. The thin card lies on a raised SHELF (thin top on four legs)
2
+ and hides a weight in one end; sliding the heavy end over the edge far enough to grasp it tips the card off the shelf
3
+ onto the table, where it lies flat and cannot be picked up: the attempt is lost.
4
+
5
+ Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 3.2): l3_card_edge saturated. Sonnet 5.5 (cla4) failed one
6
+ flat grasp, then in the same attempt slid the card 2-3 cm over the board's edge and grasped the overhang (both runs
7
+ succeeded on attempt 1): the failed grasp costs one command and changes nothing. Here the first common-sense
8
+ interaction (slide the nearest end out ~3 cm) has an irreversible cost whenever that end is the heavy one.
9
+
10
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): a wooden shelf
11
+ (top 22 x 26 x 1 cm on four 2 x 2 cm legs, top surface 10 cm above the table) with a thin red card (9.0 x 5.6 x 0.2 cm)
12
+ lying flat on it, long side along x or along y (+-8 deg). Its near end is 2.5-4 cm from the shelf edge it points to (an
13
+ x-card's near end is always the FORWARD one: a card that tips off the backward edge lands behind the shelf, hidden from
14
+ the front camera), the far end 9-14 cm from the opposite edge, both long sides >= 5 cm inside; a grey bin (16 x 16 cm
15
+ inside, 5 cm high) stands on the table beside the shelf (left or right, 6 cm gap). Same card size, mass (10 g),
16
+ friction and bin as l3_card_edge.
17
+
18
+ Hidden variable (instance level, the same in every attempt, invisible): 8 of the card's 10 g are a weight hidden in one
19
+ end; its centre of mass sits COM_E = 2.8 cm from the middle towards that end. Both ends look identical. In 14 of every
20
+ 20 consecutive seeds the heavy end is the NEAR end (the end a Sonnet-like agent slides out), else the far end.
21
+
22
+ Mechanism (physics, no teleport): an end slid out by h tips over the edge once the centre of mass passes it. Measured
23
+ (card teleported with overhang h, 2 s): heavy end stays for h <= 1.7 cm, tips for h >= 1.8 cm; light end stays up to
24
+ 7.0 cm; a uniform card up to ~4.5 cm. The grasp of an overhang needs the fingers past the edge: light end 1.8-3.8 cm
25
+ out -> 11/12 grasped; the heavy end only in a narrow window (1.3-1.5 cm out, grasp 0.8-1.2 cm beyond the edge: 12/36).
26
+ A tipped card is flat on the table within 0.4 s (56/56 tilt 0), where it cannot be gripped (0/56 regrasps) and no edge
27
+ is in reach. The fix is to slide the OTHER end out (a longer slide across the shelf), learnable from the failure: "only
28
+ ~2 cm out and it already tipped -> that end is heavy" (the cheaper explanation "I pushed too far" leads to pushing
29
+ less, which leaves too little overhang to grasp). Validation (seeds 1000-1019): Sonnet-like naive tips 14/14 heavy-near
30
+ instances and succeeds on 6/6 light-near ones; the same habit succeeds 20/20 on l3_card_edge and 20/20 here with a
31
+ uniform card.
32
+
33
+ Implementation notes: the centre of mass is fixed in the generated MJCF (explicit <inertial pos="COM_E 0 0">) and the
34
+ heavy end is chosen by the card's yaw (the card is symmetric), so the body's inertial frame is never changed at runtime
35
+ (no bounding-volume refit needed; see lh_fence / envs.refit_bounds for that MuJoCo pitfall). The inertia is written in
36
+ scientific notation: objects._fmt (5 decimals) rounds a 10-30 g card's inertia to ~0 (a 10 g card does not compile; a
37
+ 30 g card with rounded inertia got pinched and lifted by the flat grasp 4/16). Mass 10 g as in l3_card_edge: the flat
38
+ grasp then fails 20/20 (fingers slide over the card). The shelf is a static multi-geom fixture; its legs stand inside
39
+ its top's footprint (robot-leg contacts: 0 in all scripted runs).
40
+
41
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: success = the card lies in the bin,
42
+ not held; plus a per-step event log (end / side slid over an edge, tipped_off, lifted, released, in_bin, hand_hit_leg)
43
+ and R6 fields (tipped_off, trap_fired, grasp_tries) for the server log; F1 gives the agent only success / failure.
44
+ """
45
+ import numpy as np
46
+
47
+ from .. import envs
48
+ from ..bddl import write_bddl
49
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
50
+ from ..skills import Skills
51
+ from ..task_base import LFFTask, register_task
52
+
53
+ TZ = envs.TABLE_Z
54
+ CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm (as l3_card_edge)
55
+ CARD_MASS = 0.010 # as l3_card_edge (flat grasp fails 20/20; a 30 g card was pinched and lifted 4/16)
56
+ SLUG_MASS = 0.008 # hidden weight (+ 2 g of card); slug centre 3.5 cm from the middle
57
+ COM_E = 0.028 # centre of mass this far from the card's middle, towards the heavy end (the card's local +x)
58
+ MU = 0.3 # card and shelf sliding friction (as l3_card_edge)
59
+ SHELF_HALF = (0.11, 0.13) # top half extents (as l3_card_edge's board)
60
+ SHELF_H = 0.10 # top surface above the table
61
+ TOP_T = 0.01 # top thickness
62
+ LEG = 0.01 # leg half width (2 x 2 cm legs)
63
+ LEG_IN = 0.012 # leg centre to the top's edges
64
+ SHELF_TOP = TZ + SHELF_H
65
+ CARD_REST_Z = SHELF_TOP + CARD_HALF[2]
66
+ BIN_IN = 0.08 # inner half width
67
+ BIN_WALL_H = 0.05
68
+ BIN_GAP = 0.06 # shelf edge to bin outer wall
69
+ BIN_T = 0.006
70
+ BIN_HALF_OUT = BIN_IN + BIN_T
71
+ TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
72
+ LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
73
+
74
+ # instance ranges
75
+ P_HEAVY_NEAR = 0.7 # 14 of every 20 consecutive seeds
76
+ NEAR_GAP = (0.025, 0.040) # near end to its shelf edge
77
+ SIDE_CLEAR = 0.05 # long sides to the shelf's side edges, at least
78
+ YAW_JIT = np.radians(8.0)
79
+
80
+ # scripted policies
81
+ GRASP_OUT = 0.022 # grasp point this far beyond the edge (fingers must clear the edge)
82
+ DRAG_SPEED = 0.08
83
+ NAIVE_STEPS = (0.0, 0.01, 0.02, 0.03) # Sonnet-like: slide the end to the edge, then out in 1 cm steps, lift & look
84
+ ORACLE_STEPS = (0.02, 0.03) # l3_card_edge oracle: to 1 cm short, look, the rest
85
+
86
+ EDGES = ("forward", "backward", "left", "right") # shelf edges in robot-centric words (+x, -x, +y, -y)
87
+ EDGE_U = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)}
88
+ OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
89
+
90
+
91
+ def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
92
+ """Uniform-looking card; the inertial (10 g, centre of mass COM_E along local +x) models an 8 g weight hidden in
93
+ the +x end. Explicit inertial pos != 0, so MuJoCo keeps a separate inertial frame (see module doc)."""
94
+ h = CARD_HALF
95
+ ms = CARD_MASS - SLUG_MASS
96
+ xs = COM_E * CARD_MASS / SLUG_MASS # slug centre
97
+ sl = (0.0075, 0.021, h[2]) # slug half extents (1.5 x 4.2 x 0.2 cm)
98
+ box_i = lambda mm, a: mm / 3 * np.array([a[1] ** 2 + a[2] ** 2, a[0] ** 2 + a[2] ** 2, a[0] ** 2 + a[1] ** 2])
99
+ par = lambda mm, r: mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
100
+ c = np.array([COM_E, 0.0, 0.0])
101
+ inertia = box_i(ms, h) + par(ms, -c) + box_i(SLUG_MASS, sl) + par(SLUG_MASS, np.array([xs, 0.0, 0.0]) - c)
102
+ g = (f' <inertial pos="{_fmt(c)}" mass="{CARD_MASS}" diaginertia="{" ".join(f"{v:.6e}" for v in inertia)}" />\n'
103
+ f' <geom name="{name}_g0" type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" '
104
+ f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
105
+ f' <geom type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
106
+ return _wrap(name, g, h[2], float(np.hypot(h[0], h[1])))
107
+
108
+
109
+ def shelf_xml(name, rgba=(0.62, 0.45, 0.27, 1.0), leg_rgba=(0.50, 0.36, 0.21, 1.0)):
110
+ """Static shelf: top plate on four legs; body origin at mid height (top surface at +SHELF_H / 2)."""
111
+ hx, hy = SHELF_HALF
112
+ H = SHELF_H / 2
113
+ parts = [((0.0, 0.0, H - TOP_T / 2), (hx, hy, TOP_T / 2), rgba)]
114
+ for sx in (-1, 1):
115
+ for sy in (-1, 1):
116
+ parts.append(((sx * (hx - LEG_IN), sy * (hy - LEG_IN), -TOP_T / 2), (LEG, LEG, H - TOP_T / 2), leg_rgba))
117
+ g = []
118
+ for k, (p, s, c) in enumerate(parts):
119
+ g.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
120
+ f'density="500" friction="{MU} 0.005 0.0001" {_SOLID} group="0" />')
121
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" contype="0" '
122
+ f'conaffinity="0" group="1" />')
123
+ return _wrap(name, "\n".join(g), H, float(np.hypot(hx, hy)))
124
+
125
+
126
+ def _yaw_of(quat_wxyz):
127
+ w, x, y, z = quat_wxyz
128
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
129
+
130
+
131
+ class ShelfSkills(Skills):
132
+ """Skills that feed the task's per-step monitor and log every close of the gripper."""
133
+
134
+ def __init__(self, env, task, recorder=None):
135
+ super().__init__(env, recorder=recorder)
136
+ self.task = task
137
+ self.closes = []
138
+
139
+ def _act(self, dpos, drot, grip):
140
+ super()._act(dpos, drot, grip)
141
+ self.task.monitor_step()
142
+
143
+ def set_gripper(self, close, steps=15):
144
+ was_open = self.grip < 0
145
+ before = self.task.close_context() if (close and was_open) else None
146
+ rep = super().set_gripper(close, steps)
147
+ if before is not None:
148
+ before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
149
+ self.closes.append(before)
150
+ return rep
151
+
152
+
153
+ @register_task
154
+ class CardShelf(LFFTask):
155
+ name = "l3_card_shelf"
156
+ level = "L3"
157
+ category = "strategy_switching"
158
+ capabilities = ("Perceive", "Reason", "Plan")
159
+ protocol = "cross"
160
+ max_attempts = 3
161
+ agent_max_steps = 40
162
+ instruction = "Pick up the thin red card lying on the wooden shelf and put it into the grey bin."
163
+ instruction_indirect = "Put the flat red rectangle that lies on the raised wooden platform into the grey container."
164
+
165
+ # ------------------------------------------------------------ scene
166
+ def make_bddl(self):
167
+ card = register_generated("LffShelfCard", card_xml("lff_shelf_card"))
168
+ shelf = register_generated("LffCardShelf", shelf_xml("lff_card_shelf"), free=False)
169
+ bin_ = register_generated("LffShelfBin", bin_xml("lff_shelf_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
170
+ rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
171
+ objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
172
+ fx = [("shelf_1", shelf, "shelf_region", (-0.11, -0.01, -0.09, 0.01)),
173
+ ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
174
+ return write_bddl(self.name, self.instruction, objs, fx)
175
+
176
+ def __init__(self, cam_res=None):
177
+ super().__init__(cam_res)
178
+ m = self.env.sim.model
179
+ self.shelf_bid = m.body_name2id(self.env.fixtures_dict["shelf_1"].root_body)
180
+ self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
181
+ g0 = int(m.body_geomadr[self.shelf_bid])
182
+ self.leg_geoms = {g for g in range(g0, g0 + int(m.body_geomnum[self.shelf_bid]))
183
+ if (m.geom_id2name(g) or "").endswith(("_g1", "_g2", "_g3", "_g4"))}
184
+ self.robot_geoms = set(envs.robot_geom_ids(self.env))
185
+ self.inst = None
186
+ self.mon = None
187
+
188
+ def sample_instance(self, seed):
189
+ rng = np.random.default_rng(seed)
190
+ bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
191
+ along = str(rng.choice(["x", "y"]))
192
+ near_sign = 1.0 if rng.random() < 0.5 else -1.0
193
+ if along == "x": # the near end of an x-card is the forward one: a card that tips off the backward edge lands
194
+ near_sign = 1.0 # behind the shelf, hidden from the front camera (measured); forward = nearest = away from the robot
195
+ jit = float(rng.uniform(-YAW_JIT, YAW_JIT))
196
+ gap = float(rng.uniform(*NEAR_GAP))
197
+ heavy_near = bool((int(seed) * 7) % 20 < round(20 * P_HEAVY_NEAR)) # balanced per 20 consecutive seeds
198
+ a_long, a_side = (0, 1) if along == "x" else (1, 0) # world axis of the card's long / short side
199
+ ext_long = CARD_HALF[0] * abs(np.cos(jit)) + CARD_HALF[1] * abs(np.sin(jit)) # half extents incl. the jitter
200
+ ext_side = CARD_HALF[0] * abs(np.sin(jit)) + CARD_HALF[1] * abs(np.cos(jit))
201
+ c = [bx, by]
202
+ c[a_long] += near_sign * (SHELF_HALF[a_long] - gap - ext_long)
203
+ room = SHELF_HALF[a_side] - ext_side - SIDE_CLEAR
204
+ c[a_side] += float(rng.uniform(-room, room))
205
+ u_near = np.zeros(2)
206
+ u_near[a_long] = near_sign
207
+ near_edge = {(1.0, 0.0): "forward", (-1.0, 0.0): "backward", (0.0, 1.0): "left", (0.0, -1.0): "right"}[
208
+ (float(u_near[0]), float(u_near[1]))]
209
+ heavy_dir = u_near if heavy_near else -u_near # the card's local +x (heavy end) points this way (+- jitter)
210
+ yaw = float(np.arctan2(heavy_dir[1], heavy_dir[0]) + jit)
211
+ side = 1.0 if rng.random() < 0.5 else -1.0
212
+ bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (SHELF_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
213
+ return dict(seed=int(seed), shelf_xy=[bx, by], card_xy=[float(c[0]), float(c[1])], card_yaw=yaw,
214
+ card_along=along, near_edge=near_edge, far_edge=OPPOSITE[near_edge], near_gap=gap,
215
+ heavy_near=heavy_near, heavy_edge=near_edge if heavy_near else OPPOSITE[near_edge],
216
+ com_offset=COM_E, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
217
+
218
+ def apply_instance(self, inst):
219
+ self.inst = inst
220
+ m = self.env.sim.model
221
+ bx, by = inst["shelf_xy"]
222
+ m.body_pos[self.shelf_bid] = [bx, by, TZ + SHELF_H / 2]
223
+ m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0]
224
+ cx, cy = inst["bin_xy"]
225
+ m.body_pos[self.bin_bid] = [cx, cy, TZ + (BIN_WALL_H + BIN_T) / 2]
226
+ m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
227
+ x, y = inst["card_xy"]
228
+ envs.set_obj_pose(self.env, "card_1", [x, y, CARD_REST_Z + 0.0003], yaw=inst["card_yaw"])
229
+
230
+ def reset_instance(self, inst, recorder=None):
231
+ self.env.reset()
232
+ self.apply_instance(inst)
233
+ self.env.sim.forward()
234
+ envs.settle(self.env, 15)
235
+ self.sk = ShelfSkills(self.env, self, recorder=recorder)
236
+ p = self.card_pose()
237
+ self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False, lifted=False,
238
+ out=dict(heavy=0.0, light=0.0, side=0.0), out_edge=dict(heavy=None, light=None, side=None),
239
+ flagged=set(), events=[], in_bin=False, tip=None, leg_hits=0, edge_used=None)
240
+ return self.sk
241
+
242
+ # ------------------------------------------------------------ geometry
243
+ def card_pose(self):
244
+ p = envs.obj_pos(self.env, "card_1")
245
+ return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
246
+
247
+ def _card_frame(self):
248
+ d = self.env.sim.data
249
+ bid = envs.body_id(self.env, "card_1")
250
+ return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
251
+
252
+ def card_corners(self):
253
+ p, R = self._card_frame()
254
+ h = np.array(CARD_HALF)
255
+ return np.array([p + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
256
+
257
+ def _beyond(self, xy):
258
+ """{edge: how far the point lies beyond that edge of the shelf top (m, negative = inside)}"""
259
+ b = np.asarray(xy, float) - np.asarray(self.inst["shelf_xy"])
260
+ return {"forward": b[0] - SHELF_HALF[0], "backward": -b[0] - SHELF_HALF[0],
261
+ "left": b[1] - SHELF_HALF[1], "right": -b[1] - SHELF_HALF[1]}
262
+
263
+ def overhang(self):
264
+ """(how far the card sticks out beyond the shelf's edges (m, max over its corners), edge word)"""
265
+ best = (-1.0, None)
266
+ for c in self.card_corners():
267
+ for e, v in self._beyond(c[:2]).items():
268
+ if v > best[0]:
269
+ best = (float(v), e)
270
+ return best
271
+
272
+ def part_overhangs(self):
273
+ """{'heavy' | 'light' | 'side': (overhang m, edge)}: the heavy end (local +x), light end and long sides,
274
+ each measured at its two corners."""
275
+ p, R = self._card_frame()
276
+ h = np.array(CARD_HALF)
277
+ groups = {"heavy": [(1, -1), (1, 1)], "light": [(-1, -1), (-1, 1)]}
278
+ out = {}
279
+ for k, cs in groups.items():
280
+ best = (-1.0, None)
281
+ for sx, sy in cs:
282
+ c = p + R @ (h * [sx, sy, 0.0])
283
+ for e, v in self._beyond(c[:2]).items():
284
+ if v > best[0]:
285
+ best = (float(v), e)
286
+ out[k] = best
287
+ best = (-1.0, None) # a long side: its middle point (an end pushed out also moves two corners out)
288
+ for sy in (-1, 1):
289
+ c = p + R @ (h * [0.0, sy, 0.0])
290
+ for e, v in self._beyond(c[:2]).items():
291
+ if v > best[0]:
292
+ best = (float(v), e)
293
+ out["side"] = best
294
+ return out
295
+
296
+ def end_edge(self, which):
297
+ """shelf edge that the card's `which` end ('heavy' | 'light' | 'near' | 'far') points to, from the live pose"""
298
+ p = self.card_pose()
299
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) # heavy end direction
300
+ if which == "near" or which == "far":
301
+ gaps = {}
302
+ for s in (1.0, -1.0):
303
+ u = d * s
304
+ e = max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
305
+ tip = p["xy"] + u * CARD_HALF[0]
306
+ gaps[e] = -self._beyond(tip)[e]
307
+ near = min(gaps, key=gaps.get)
308
+ return near if which == "near" else OPPOSITE[near]
309
+ u = d if which == "heavy" else -d
310
+ return max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
311
+
312
+ def on_shelf(self):
313
+ p = self.card_pose()
314
+ rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
315
+ return bool(rel[0] <= SHELF_HALF[0] and rel[1] <= SHELF_HALF[1] and abs(p["z"] - CARD_REST_Z) < 0.012)
316
+
317
+ def on_table(self):
318
+ return bool(self.card_pose()["z"] < TZ + 0.03 and not self.in_bin())
319
+
320
+ def tilt_deg(self):
321
+ _, R = self._card_frame()
322
+ return float(np.degrees(np.arccos(np.clip(abs(R[2, 2]), 0.0, 1.0))))
323
+
324
+ def in_bin(self):
325
+ p = self.card_pose()
326
+ rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
327
+ return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < TZ + BIN_T + BIN_WALL_H)
328
+
329
+ # ------------------------------------------------------------ monitor
330
+ def _event(self, ev, **kw):
331
+ self.mon["events"].append(dict(event=ev, step=int(self.sk.n_steps), **kw))
332
+
333
+ def monitor_step(self):
334
+ mon = self.mon
335
+ if mon is None or self.sk is None:
336
+ return
337
+ p = self.card_pose()
338
+ held = self.sk.holding("card_1")
339
+ zmin = float(self.card_corners()[:, 2].min())
340
+ mon["max_lift"] = max(mon["max_lift"], zmin - SHELF_TOP)
341
+ if held and zmin - SHELF_TOP > 0.02 and not mon["lifted"]:
342
+ mon["lifted"] = True
343
+ self._event("lifted")
344
+ rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
345
+ if (not held and abs(p["z"] - CARD_REST_Z) < 0.004 and self.tilt_deg() < 5.0 and rel[0] <= SHELF_HALF[0]
346
+ and rel[1] <= SHELF_HALF[1]): # lying flat on the shelf
347
+ mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
348
+ for k, (v, e) in self.part_overhangs().items():
349
+ if v > mon["out"][k]:
350
+ mon["out"][k], mon["out_edge"][k] = v, e
351
+ if v >= 0.005 and k not in mon["flagged"]:
352
+ mon["flagged"].add(k)
353
+ self._event("side_over_edge" if k == "side" else "end_over_edge", part=k, edge=e)
354
+ if p["z"] < SHELF_TOP - 0.02 and not held and not mon["fell"]:
355
+ mon["fell"] = True
356
+ if not mon["lifted"]: # never lifted: it tipped (or was pushed) off the shelf
357
+ part = max(("heavy", "light", "side"), key=lambda k: mon["out"][k])
358
+ mon["tip"] = dict(part=part, edge=mon["out_edge"][part], overhang=round(mon["out"][part], 4))
359
+ self._event("tipped_off", **mon["tip"])
360
+ else:
361
+ self._event("released")
362
+ d = self.env.sim.data
363
+ for i in range(d.ncon): # the hand / arm touching a shelf leg (should not happen in normal grasps)
364
+ c = d.contact[i]
365
+ if (c.geom1 in self.leg_geoms and c.geom2 in self.robot_geoms) or (c.geom2 in self.leg_geoms and
366
+ c.geom1 in self.robot_geoms):
367
+ if mon["leg_hits"] == 0:
368
+ self._event("hand_hit_leg")
369
+ mon["leg_hits"] += 1
370
+ break
371
+ if not mon["in_bin"] and self.in_bin() and not held:
372
+ mon["in_bin"] = True
373
+ self._event("in_bin")
374
+
375
+ def close_context(self):
376
+ """Where the gripper is relative to the card and the shelf just before it closes."""
377
+ sk, p = self.sk, self.card_pose()
378
+ e = sk.eef_pos()
379
+ c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
380
+ rel = e[:2] - p["xy"]
381
+ local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side (+ = heavy end)
382
+ beyond = self._beyond(e[:2])
383
+ edge = max(beyond, key=beyond.get)
384
+ ov, ov_edge = self.overhang()
385
+ return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
386
+ tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
387
+ beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
388
+ card_on_shelf=self.on_shelf(), overhang=round(ov, 4), overhang_edge=ov_edge,
389
+ width_before=round(sk.gripper_width(), 4))
390
+
391
+ # ------------------------------------------------------------ outcome / F2
392
+ def outcome(self, inst):
393
+ envs.settle(self.env, 30)
394
+ self.monitor_step()
395
+ sk, mon = self.sk, self.mon
396
+ p = self.card_pose()
397
+ held = bool(sk.holding("card_1"))
398
+ in_bin = self.in_bin() and not held
399
+ success = bool(in_bin)
400
+ moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
401
+ lifted = mon["max_lift"] > 0.02
402
+ tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
403
+ parts, mode = [], "success"
404
+ rel = p["xy"] - np.asarray(inst["bin_xy"])
405
+ where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
406
+ f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
407
+ tip = mon["tip"]
408
+ if success:
409
+ parts.append("The card is in the bin.")
410
+ elif held:
411
+ mode = "held"
412
+ parts.append(f"The card is still held by the gripper, {where}.")
413
+ elif lifted:
414
+ mode = "dropped"
415
+ loc = ("on the shelf" if self.on_shelf() else "on the table" if self.on_table() else
416
+ "partly on the shelf" if p["z"] > SHELF_TOP - 0.02 else "off the shelf")
417
+ parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the shelf but is not in the "
418
+ f"bin: it lies {loc}, its centre {where}.")
419
+ elif mon["fell"]:
420
+ mode = "fell_off"
421
+ what = "a long side" if tip["part"] == "side" else "one end"
422
+ parts.append(f"The card was never lifted: after {what} of it had been slid {100 * max(tip['overhang'], 0):.1f}"
423
+ f" cm beyond the shelf's {tip['edge']} edge, it tipped over that edge and fell off the shelf; "
424
+ + ("it lies flat on the table." if self.on_table() and self.tilt_deg() < 10 else
425
+ f"it rests off the shelf, tilted {self.tilt_deg():.0f} degrees."))
426
+ else:
427
+ mode = "not_lifted"
428
+ parts.append("The card was never lifted; it still lies flat on the shelf"
429
+ + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
430
+ f"{100 * mon['max_overhang']:.1f} cm beyond the shelf's edge)" if mon["max_overhang"] > 0.003
431
+ else ")") if moved > 0.005 else "") + ".")
432
+ if not success and not lifted and tries:
433
+ c = tries[-1]
434
+ n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
435
+ if c["card_on_shelf"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
436
+ txt = ("when the gripper closed on the card lying flat on the shelf, its fingertips were on either side "
437
+ "of the card, at shelf level")
438
+ else:
439
+ pos = (f"{100 * c['beyond_edge']:.1f} cm beyond the shelf's {c['beyond_edge_name']} edge"
440
+ if c["beyond_edge"] >= 0.0 else
441
+ f"over the shelf, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge")
442
+ txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm beyond the "
443
+ f"shelf's {c['overhang_edge']} edge and the gripper's centre was {pos}")
444
+ txt += f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the fingers closed "
445
+ txt += ("fully, sliding over the top of the card instead of gripping its edges."
446
+ if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
447
+ ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
448
+ parts.append(n + txt if n else txt[0].upper() + txt[1:])
449
+ elif not success and not lifted and not mon["fell"]:
450
+ parts.append("The gripper never closed with its fingertips down at the card.")
451
+ failure = "none" if success else mode
452
+ out = dict(success=success, mode=mode, failure=failure, held=held, lifted=bool(lifted),
453
+ max_lift=round(mon["max_lift"], 4), max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4),
454
+ fell=bool(mon["fell"]), tipped_off=tip is not None, trap_fired=bool(tip is not None and
455
+ tip["part"] == "heavy"),
456
+ tip=tip, end_out={k: round(v, 4) for k, v in mon["out"].items()},
457
+ end_out_edge=dict(mon["out_edge"]), card_final=dict(xy=[round(float(v), 4) for v in p["xy"]],
458
+ z_above_table=round(p["z"] - TZ, 4),
459
+ tilt_deg=round(self.tilt_deg(), 1)),
460
+ leg_hits=int(mon["leg_hits"]), slid_edge=mon["edge_used"],
461
+ events=list(mon["events"]), grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
462
+ return out
463
+
464
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
465
+ def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
466
+ sk = self.sk
467
+ sk.set_gripper(False, steps=8)
468
+ sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
469
+ sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
470
+ sk.set_gripper(True, steps=15)
471
+ sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
472
+ if not sk.holding("card_1"):
473
+ sk.set_gripper(False, steps=8)
474
+ return False
475
+ bx, by = self.inst["bin_xy"]
476
+ hi = SHELF_TOP + 0.10
477
+ sk.move_to([bx, by, hi])
478
+ sk.move_to([bx, by, TZ + BIN_WALL_H + 0.05], speed=0.2)
479
+ sk.set_gripper(False, steps=12)
480
+ sk.move_to([bx, by, hi])
481
+ return True
482
+
483
+ def slide_card(self, delta, press=0.004, at=(0.0, 0.0)):
484
+ """closed fingertips pressed on the card (at its centre + `at`), straight move by `delta` (xy), lift"""
485
+ sk, p = self.sk, self.card_pose()
486
+ z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
487
+ s = p["xy"] + np.asarray(at, float)
488
+ sk.set_gripper(True, steps=8)
489
+ sk.move_to([s[0], s[1], z + 0.06], yaw=p["yaw"])
490
+ sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
491
+ e = s + np.asarray(delta, float)
492
+ sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
493
+ sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
494
+ sk.hold(10) # look
495
+
496
+ def push_end(self, u, dist, behind=0.015):
497
+ """closed fingers at shelf level `behind` m behind the card's trailing end, push it `dist` along u, lift"""
498
+ sk, p = self.sk, self.card_pose()
499
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
500
+ la = d * np.sign(d @ u) if abs(d @ u) > 0.5 else d
501
+ tail = p["xy"] - la * CARD_HALF[0]
502
+ s = tail - u * behind
503
+ z = SHELF_TOP + TIP_BELOW_SITE - 0.001 # fingertips on the shelf top (2 mm above: they pass over the card)
504
+ yaw = float(np.arctan2(u[1], u[0]) - np.pi / 2) # finger axis across the push direction
505
+ sk.set_gripper(True, steps=8)
506
+ sk.move_to([s[0], s[1], z + 0.05], yaw=yaw)
507
+ sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
508
+ e = s + u * (behind + dist)
509
+ sk.move_to([e[0], e[1], z], speed=0.04, tol=0.004, max_steps=300)
510
+ sk.move_to([e[0], e[1], z + 0.05], speed=0.2)
511
+ sk.hold(10)
512
+
513
+ def execute(self, inst, params):
514
+ p = self.card_pose()
515
+ rng = np.random.default_rng(params.get("noise_seed")) if params.get("noise_seed") is not None else None
516
+ if params.get("probe_grasp", False) or params["mode"] == "grasp": # flat grasp at the card's middle
517
+ dxy = np.asarray(params.get("probe_dxy", (0.0, 0.0)))
518
+ self.grasp_and_bin(p["xy"] + dxy, p["yaw"], SHELF_TOP + params.get("probe_dz", 0.0))
519
+ if params["mode"] == "grasp" or self.sk.holding("card_1") or self.mon["lifted"]:
520
+ return
521
+ # slide one end of the card along its long side out over the edge it points to, in strokes
522
+ edge = params.get("edge") or self.end_edge(params.get("end", "near"))
523
+ self.mon["edge_used"] = edge
524
+ u = np.asarray(EDGE_U[edge], float)
525
+ b = np.asarray(inst["shelf_xy"])
526
+ half = SHELF_HALF[0] if edge in ("forward", "backward") else SHELF_HALF[1]
527
+ edge_pos = float(b @ u) + half
528
+ for k, target in enumerate(params.get("steps", ORACLE_STEPS)):
529
+ if not self.on_shelf():
530
+ return # tipped off: nothing left to grasp (the attempt is lost)
531
+ p = self.card_pose()
532
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
533
+ la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
534
+ ext = max(float(c[:2] @ u) for c in self.card_corners()) - float(p["xy"] @ u)
535
+ tgt = float(target) + (float(rng.uniform(-1, 1)) * params.get("step_noise", 0.0) if rng is not None else 0.0)
536
+ need = edge_pos + tgt - (float(p["xy"] @ u) + ext) # travel still needed along u
537
+ if need > 0.003:
538
+ if params.get("style", "press") == "endpush":
539
+ self.push_end(u, need)
540
+ else:
541
+ at = (np.asarray(params.get("press_at", (0.0, 0.0))) if rng is None else
542
+ rng.normal(0.0, params.get("press_noise", 0.0), 2))
543
+ self.slide_card(la * need / max(float(la @ u), 1e-6), at=at)
544
+ self.sk.hold(10)
545
+ if not self.on_shelf():
546
+ return
547
+ q = self.card_pose()
548
+ d = np.array([np.cos(q["yaw"]), np.sin(q["yaw"])])
549
+ la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
550
+ cu = float(q["xy"] @ u)
551
+ tip_u = max(float(c[:2] @ u) for c in self.card_corners()) # outermost point of the card along u
552
+ target_u = min(tip_u - 0.008, edge_pos + params.get("grasp_out", GRASP_OUT))
553
+ g = q["xy"] + la * (target_u - cu) / max(float(la @ u), 1e-6)
554
+ g = g + np.asarray(params.get("grasp_dxy", (0.0, 0.0)))
555
+ self.grasp_and_bin(g, q["yaw"], SHELF_TOP - 0.003 + params.get("grasp_dz", 0.0))
556
+
557
+ def default_params(self, inst):
558
+ """Sonnet-like (cla4 l3_card_edge): one flat grasp, then the nearest end out to the edge and 1 cm at a time
559
+ to ~3 cm, lifting the finger and looking after each stroke; grasp the overhang."""
560
+ return dict(mode="edge", probe_grasp=True, end="near", steps=list(NAIVE_STEPS))
561
+
562
+ def oracle_params(self, inst):
563
+ """Knows the hidden weight: slides the light end out 3 cm (two strokes, as the l3_card_edge oracle)."""
564
+ return dict(mode="edge", end="light", steps=list(ORACLE_STEPS))
565
+
566
+ def blind_params(self, inst, attempt, rng):
567
+ """naive with small random variations, no history: nearest end, 2.5-3.5 cm, pressing point / grasp jitter"""
568
+ return dict(mode="edge", probe_grasp=True, end="near", steps=[0.0, 0.01, 0.02, float(rng.uniform(0.025, 0.035))],
569
+ noise_seed=int(rng.integers(1 << 30)), press_noise=0.005,
570
+ grasp_dxy=rng.uniform(-0.005, 0.005, 2).tolist(), grasp_dz=float(rng.uniform(-0.004, 0.003)))
571
+
572
+ def adapt_params(self, inst, history):
573
+ """Tipped off the shelf (never lifted) -> slide the OTHER end next time (it tipped although only ~2 cm stuck
574
+ out: that end must be heavy). Slid out but not gripped -> 1 cm more overhang. Otherwise repeat."""
575
+ out, prm = history[-1]["outcome"], history[-1]["params"]
576
+ used = out.get("slid_edge") or prm.get("edge")
577
+ nxt = dict(mode="edge", probe_grasp=False, edge=used, steps=list(ORACLE_STEPS))
578
+ if out["mode"] == "fell_off":
579
+ e = (out.get("tip") or {}).get("edge") or used
580
+ nxt["edge"] = OPPOSITE.get(e)
581
+ elif out["mode"] == "not_lifted" and used is not None:
582
+ last = float((prm.get("steps") or ORACLE_STEPS)[-1])
583
+ nxt["steps"] = [s + 0.01 for s in ORACLE_STEPS] if last < 0.035 else list(ORACLE_STEPS)
584
+ if nxt["edge"] is None:
585
+ nxt.pop("edge")
586
+ nxt["end"] = "near"
587
+ return nxt
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l5_iterative.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary:
2
+ the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches
3
+ different speeds at different extensions. Needs a configuration-independent striker before use.]
4
+
5
+ L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue).
6
+
7
+ The cube starts far from the target zone; each push is a straight strike away from the robot whose
8
+ only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails).
9
+ Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose
10
+ the next push (how far a push of a given speed carries the cube) is only available from the
11
+ outcomes of the previous pushes in the same episode -> within-episode learning from failure.
12
+
13
+ "Attempt" granularity for the history: one push.
14
+ """
15
+ import numpy as np
16
+
17
+ from .. import envs
18
+ from ..task_base import register_task
19
+ from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget
20
+
21
+
22
+ @register_task
23
+ class IterativePush(SlideToTarget):
24
+ name = "l5_iterative_push"
25
+ level = "L5"
26
+ capabilities = ("Reason", "Save", "Utilize")
27
+ protocol = "within"
28
+ max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps
29
+ instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. "
30
+ "You have at most three separate pushes. If the cube passes the zone, the task fails.")
31
+ instruction_indirect = instruction
32
+ tol_along = 0.015
33
+
34
+ def sample_instance(self, seed):
35
+ rng = np.random.default_rng(seed)
36
+ return dict(seed=int(seed),
37
+ cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))],
38
+ target_dist=float(rng.uniform(0.22, 0.30)),
39
+ mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08)))))
40
+
41
+ def make_bddl(self):
42
+ return super().make_bddl()
43
+
44
+ # --------------------------------------------------------------- one push from the current cube pose
45
+ def push_once(self, inst, speed):
46
+ c = envs.obj_pos(self.env, "cube_1")
47
+ x, y = c[0], c[1]
48
+ sk = self.sk
49
+ sk.set_gripper(True, steps=3)
50
+ sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0)
51
+ sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003)
52
+ sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01,
53
+ max_steps=80)
54
+ sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3)
55
+ envs.settle(self.env, 40)
56
+ c1 = envs.obj_pos(self.env, "cube_1")
57
+ return float(c1[0] - x)
58
+
59
+ def outcome(self, inst):
60
+ x0, y0 = inst["cube_xy"]
61
+ c = envs.obj_pos(self.env, "cube_1")
62
+ along = (c[0] - x0) - inst["target_dist"]
63
+ across = c[1] - y0
64
+ success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z)
65
+ overshoot = bool(along > self.tol_along)
66
+ if success:
67
+ detail = "The cube is inside the target zone."
68
+ elif overshoot:
69
+ detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed."
70
+ else:
71
+ detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone."
72
+ return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across),
73
+ detail=detail)
74
+
75
+ # --------------------------------------------------------------- scripted references
76
+ S0 = 0.02 # distance the cube travels during the contact stroke itself
77
+
78
+ def _plan_speed(self, remaining, model, pushes_left=1):
79
+ """Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short
80
+ final leg (a short push is more predictable); with one push left, aim at the zone centre."""
81
+ if model is None:
82
+ return 0.30
83
+ s0, k = model
84
+ goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0)
85
+ v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6))
86
+ return float(np.clip(v, V_MIN, V_MAX))
87
+
88
+ @classmethod
89
+ def _fit(cls, pts):
90
+ """pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k)."""
91
+ if len(pts) == 1:
92
+ v, d = pts[0]
93
+ return cls.S0, max(d - cls.S0, 1e-4) / v ** 2
94
+ A = np.array([[1.0, v ** 2] for v, _ in pts])
95
+ b = np.array([d for _, d in pts])
96
+ s0, k = np.linalg.lstsq(A, b, rcond=None)[0]
97
+ if k <= 0:
98
+ return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts])
99
+ return float(np.clip(s0, 0.0, 0.05)), float(k)
100
+
101
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
102
+ k = k or self.max_attempts
103
+ rng = np.random.default_rng(seed)
104
+ self.reset_instance(inst)
105
+ history = []
106
+ model = None
107
+ if kind == "oracle":
108
+ model = self._oracle_model(inst)
109
+ for a in range(k):
110
+ out0 = self.outcome(inst)
111
+ remaining = -out0["along_err"]
112
+ if kind == "naive" or kind == "blind":
113
+ speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))
114
+ if remaining < 0.06: # naive heuristic: tap gently near the end
115
+ speed = 0.20
116
+ else:
117
+ speed = self._plan_speed(remaining, model, pushes_left=k - a)
118
+ moved = self.push_once(inst, speed)
119
+ out = self.outcome(inst)
120
+ history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved)))
121
+ if kind == "adaptive" and moved > 0.005:
122
+ pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005]
123
+ model = self._fit(pts)
124
+ if out["success"] or out["overshoot"]:
125
+ break
126
+ # mark only the final state as the episode outcome
127
+ return history
128
+
129
+ def _oracle_model(self, inst):
130
+ """Privileged: measure the push model with the true mu in scratch rollouts."""
131
+ pts = []
132
+ for v in (0.2, 0.35, 0.5):
133
+ self.reset_instance(inst)
134
+ pts.append((v, self.push_once(inst, v)))
135
+ self.reset_instance(inst)
136
+ return self._fit(pts)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l5_slippery_lift.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L5-B slippery_lift: pick up a heavy, slippery metal bar and hold it level.
2
+
3
+ Category dynamics_adaptation (L5): "figure out how this object moves".
4
+
5
+ Scene: one long steel-grey bar (4 x 28 x 4 cm, lying along the robot's left-right axis) on the table. It looks
6
+ perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits
7
+ e = 2.5-7 cm from the bar's midpoint, towards the left or the right end. The bar is heavy (0.8-1.2 kg) and its
8
+ surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold
9
+ much torque.
10
+
11
+ Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to
12
+ one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar
13
+ ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static).
14
+
15
+ What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp
16
+ has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The
17
+ tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts.
18
+
19
+ Measured physics (2026-10-07, `l5dyn/bar_win.py`): mass 0.8-1.2 kg, mu 0.4-0.6, lift 15 cm at 0.15 m/s:
20
+ |grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not
21
+ creep during a 3 s hold. mu 0.8 gave non-monotone tilts and is not used; mu 0.3 + 1.3 kg slips out entirely.
22
+ """
23
+ import numpy as np
24
+
25
+ from .. import envs
26
+ from ..bddl import write_bddl
27
+ from ..objects import _fmt, _wrap, register_generated
28
+ from ..skills import Skills
29
+ from ..task_base import LFFTask, register_task
30
+
31
+ BAR = "bar_1"
32
+ HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y
33
+ _SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
34
+ W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug
35
+ W_HALF = 0.015 # slug half size (for its inertia)
36
+ E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m)
37
+ LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table
38
+ TILT_MAX = 8.0 # deg
39
+ Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table)
40
+ Z_LIFT = Z_GRASP + 0.15
41
+ YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar
42
+
43
+
44
+ def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)):
45
+ """Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps
46
+ body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance."""
47
+ I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2),
48
+ mass / 3 * (half[0] ** 2 + half[1] ** 2)]
49
+ g = (f' <inertial pos="0 0.001 0.001" mass="{mass}" diaginertia="{_fmt(I)}" />\n'
50
+ f' <geom name="{name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
51
+ f'friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
52
+ f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
53
+ return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
54
+
55
+
56
+ def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF):
57
+ """Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame).
58
+ Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame)."""
59
+ m = env.sim.model
60
+ bid = envs.body_id(env, obj)
61
+ ms, mw = (1 - w_frac) * mass, w_frac * mass
62
+ w_pos = np.asarray(w_pos, float)
63
+ c = mw * w_pos / mass
64
+ hx, hy, hz = half
65
+
66
+ def par(mm, r): # parallel-axis terms (diagonal)
67
+ return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
68
+
69
+ I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c)
70
+ + mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c))
71
+ m.body_mass[bid] = mass
72
+ m.body_ipos[bid] = c
73
+ m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
74
+ m.body_inertia[bid] = I
75
+ envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds)
76
+ return c
77
+
78
+
79
+ def bar_axis(env):
80
+ """World direction of the bar's long axis (body y)."""
81
+ return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy()
82
+
83
+
84
+ def bar_tilt_deg(env):
85
+ """Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower."""
86
+ ax = bar_axis(env)
87
+ if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right
88
+ ax = -ax
89
+ return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0))))
90
+
91
+
92
+ def side_words(sign):
93
+ return "left (+y)" if sign > 0 else "right (-y)"
94
+
95
+
96
+ class BarSkills(Skills):
97
+ """Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent)."""
98
+
99
+ def __init__(self, env, bias=None, recorder=None):
100
+ super().__init__(env, bias=bias, recorder=recorder)
101
+ self.closes = []
102
+ self.zmax = float(envs.obj_pos(env, BAR)[2])
103
+ self.z0 = self.zmax
104
+
105
+ def _act(self, dpos, drot, grip):
106
+ super()._act(dpos, drot, grip)
107
+ self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2]))
108
+
109
+ def set_gripper(self, close, steps=15):
110
+ rep = super().set_gripper(close, steps)
111
+ if close:
112
+ c = envs.obj_pos(self.env, BAR)
113
+ ax = bar_axis(self.env)
114
+ if ax[1] < 0:
115
+ ax = -ax
116
+ along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint
117
+ self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps))
118
+ return rep
119
+
120
+
121
+ @register_task
122
+ class SlipperyLift(LFFTask):
123
+ name = "l5_slippery_lift"
124
+ level = "L5"
125
+ category = "dynamics_adaptation"
126
+ capabilities = ("Perceive", "Reason", "Utilize")
127
+ protocol = "cross"
128
+ instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at "
129
+ "least 10 cm above the table. Keep holding it when you finish.")
130
+ instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 "
131
+ "degrees), with its lowest point at least 10 cm above the table. Keep holding it when you "
132
+ "finish.")
133
+
134
+ # ------------------------------------------------------------ scene
135
+ def make_bddl(self):
136
+ bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
137
+ objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))]
138
+ return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses
139
+
140
+ def sample_instance(self, seed):
141
+ rng = np.random.default_rng(seed)
142
+ e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX))
143
+ return dict(seed=int(seed),
144
+ bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))],
145
+ com_offset=e, # along the bar, + = towards the robot's left (+y) end
146
+ mass=float(rng.uniform(0.8, 1.2)),
147
+ mu=float(rng.uniform(0.40, 0.60)))
148
+
149
+ def apply_instance(self, inst):
150
+ x, y = inst["bar_xy"]
151
+ envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001])
152
+ envs.set_friction(self.env, BAR, inst["mu"])
153
+ set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0])
154
+
155
+ def reset_instance(self, inst, recorder=None):
156
+ self.env.reset()
157
+ self.apply_instance(inst)
158
+ self.env.sim.forward()
159
+ envs.settle(self.env, 10)
160
+ self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
161
+ return self.sk
162
+
163
+ # ------------------------------------------------------------ outcome
164
+ def outcome(self, inst):
165
+ sk = self.sk
166
+ sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
167
+ held = sk.holding(BAR)
168
+ tilt = bar_tilt_deg(self.env)
169
+ bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z
170
+ lifted = (sk.zmax - sk.z0) > 0.03
171
+ close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None)
172
+ success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN)
173
+ out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
174
+ grasp_along=None if close is None else round(close["along"], 4))
175
+ g = ""
176
+ if close is not None and close["holding"]:
177
+ a = close["along"]
178
+ g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint."
179
+ if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.")
180
+ tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its "
181
+ f"{side_words(-tilt).split()[0]} end")
182
+ if success:
183
+ out["failure"] = None
184
+ detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g
185
+ elif held and abs(tilt) > TILT_MAX:
186
+ out["failure"] = "tilted"
187
+ detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now "
188
+ f"{tilt_txt}." + g)
189
+ if bottom < LIFT_MIN:
190
+ detail += f" Its lowest point is {100 * bottom:.0f} cm above the table."
191
+ elif held:
192
+ out["failure"] = "too_low"
193
+ detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
194
+ f"{100 * bottom:.0f} cm above the table." + g)
195
+ elif lifted:
196
+ out["failure"] = "dropped"
197
+ detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table "
198
+ f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g)
199
+ elif close is None:
200
+ out["failure"] = "no_grasp"
201
+ detail = "The gripper never closed on the bar; it is still lying on the table."
202
+ else:
203
+ out["failure"] = "no_grasp"
204
+ detail = "The gripper closed but did not catch the bar; it is still lying on the table."
205
+ out["detail"] = detail
206
+ out["detail_indirect"] = detail.replace("bar", "rod")
207
+ return out
208
+
209
+ def feedback(self, inst, out, level="F2", indirect=False):
210
+ if indirect and level == "F2":
211
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
212
+ return super().feedback(inst, out, level)
213
+
214
+ # ------------------------------------------------------------ scripted execution (cross protocol)
215
+ def execute(self, inst, params):
216
+ """Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm."""
217
+ sk = self.sk
218
+ c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception)
219
+ ax = bar_axis(self.env)
220
+ if ax[1] < 0:
221
+ ax = -ax
222
+ g = c + ax * float(params["along"])
223
+ sk.set_gripper(False, steps=5)
224
+ sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS)
225
+ sk.move_to([g[0], g[1], Z_GRASP], tol=0.003)
226
+ sk.set_gripper(True, steps=15)
227
+ sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300)
228
+
229
+ def default_params(self, inst):
230
+ return dict(along=0.0)
231
+
232
+ def oracle_params(self, inst):
233
+ return dict(along=float(inst["com_offset"]))
234
+
235
+ MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm)
236
+ STEP = 0.030 # first step towards the heavy end when only one side is bounded
237
+
238
+ def adapt_params(self, inst, history):
239
+ """Bracketing on the grasp point: the end that sank is the heavy side of the last grasp."""
240
+ lo, hi = -HALF[1], HALF[1]
241
+ lo_set = hi_set = False
242
+ for h in history:
243
+ o = h["outcome"]
244
+ g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"]
245
+ if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3):
246
+ if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp
247
+ lo, lo_set = max(lo, g + self.MARGIN), True
248
+ else:
249
+ hi, hi_set = min(hi, g - self.MARGIN), True
250
+ last = history[-1]["params"]["along"]
251
+ if lo_set and hi_set:
252
+ a = 0.5 * (lo + hi)
253
+ elif lo_set:
254
+ a = lo + self.STEP - self.MARGIN
255
+ elif hi_set:
256
+ a = hi - self.STEP + self.MARGIN
257
+ else: # no direction information (e.g. too low): repeat
258
+ a = last
259
+ return dict(along=float(np.clip(a, -0.12, 0.12)))
260
+
261
+ def blind_params(self, inst, attempt, rng):
262
+ return dict(along=float(rng.normal(0.0, 0.01)))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_parts_cart.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport.
2
+
3
+ Not part of main_v1. See task_cards/lh_parts_cart.md for validation status.
4
+ Only reset_instance/apply_instance position objects; all reference actions use the public motion skills.
5
+ """
6
+ import copy
7
+ import numpy as np
8
+ from .. import envs
9
+ from ..bddl import write_bddl
10
+ from ..objects import register_generated, box_xml
11
+ from ..task_base import register_task
12
+ from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF,
13
+ HANDLE_HALF, TOP_HALF)
14
+ from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml,
15
+ HALF, MASS, MU, BOX, _rot)
16
+
17
+
18
+ class CartSkills(PushSkills):
19
+ def __init__(self,*args,**kwargs):
20
+ super().__init__(*args,**kwargs)
21
+ self.robot_commands=0
22
+ def move_to(self,*args,**kwargs):
23
+ self.robot_commands+=1
24
+ return super().move_to(*args,**kwargs)
25
+ def set_gripper(self,*args,**kwargs):
26
+ self.robot_commands+=1
27
+ return super().set_gripper(*args,**kwargs)
28
+
29
+
30
+ @register_task
31
+ class PartsCart(UnderTableTool):
32
+ name = 'lh_parts_cart'
33
+ level = 'L4'
34
+ category = 'geometry_inference'
35
+ failure_causes = ('L4', 'L2', 'L5')
36
+ capabilities = ('Perceive', 'Reason', 'Plan', 'Restore')
37
+ protocol = 'cross'
38
+ agent_max_steps = 180
39
+ instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. '
40
+ 'Load the red and blue parts on the two marks on the brown transport platform, '
41
+ 'then push the loaded platform with the closed gripper completely into the green parking area. '
42
+ 'At the end both parts must still be on their marks, and the gripper must be open and clear.')
43
+ instruction_indirect = instruction
44
+
45
+ def make_bddl(self):
46
+ cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300))
47
+ blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300))
48
+ stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"')
49
+ stick = register_generated('LffPartsCartStick', stick_xml_text)
50
+ table_xml=low_table_xml('lff_parts_cart_table')
51
+ # Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure
52
+ # trapping the cube against a corner leg, which the existing standalone task did not test in-attempt.
53
+ table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"')
54
+ for sx in (-.052,.052):
55
+ for sy in (-.052,.052):
56
+ table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"')
57
+ table = register_generated('LffPartsCartTable', table_xml, free=False)
58
+ xml=long_box_xml('lff_parts_cart_platform')
59
+ marks=''.join(f'<geom type="box" pos="0 {y} {HALF[2]+.0006}" size=".022 .022 .0003" rgba="{color}" contype="0" conaffinity="0" group="1" />' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')])
60
+ xml=xml.replace(' </body>',marks+' </body>',1)
61
+ cart = register_generated('LffPartsCartPlatform', xml)
62
+ zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False)
63
+ # Inertial/shape match existing off-centre box, with purely visual cargo marks.
64
+ objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)),
65
+ ('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)),
66
+ ('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)),
67
+ ('box_1',cart,'cart_region',(.19,.24,.21,.26))]
68
+ fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)),
69
+ ('zone_1',zone,'zone_region',(.19,.39,.21,.41))]
70
+ return write_bddl(self.name,self.instruction,objs,fx)
71
+
72
+ def sample_instance(self, seed):
73
+ # Tool geometry is inherited; put transport in the other half of the same tabletop.
74
+ rng=np.random.default_rng(seed)
75
+ base=super().sample_instance(seed)
76
+ base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08],
77
+ stick_xy=[-.08,-.34],stick_yaw=np.pi/2,
78
+ box_xy=[-.25,.24],target_dist=.16,
79
+ com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)),
80
+ traps=dict(L4=True,L2=True,L5=True))
81
+ base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture.
82
+ return base
83
+
84
+ def target_xy(self, inst):
85
+ return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]])
86
+
87
+ def apply_instance(self, inst):
88
+ self.inst=inst
89
+ m=self.env.sim.model
90
+ bid,_=self._fixture('lowtable_1')
91
+ m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z]
92
+ for g,sy in self._panes():
93
+ on=inst['traps']['L4'] and sy==inst['pane_side']
94
+ m.geom_contype[g]=m.geom_conaffinity[g]=int(on)
95
+ envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005])
96
+ envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005])
97
+ envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw'])
98
+ bid=envs.body_id(self.env,BOX)
99
+ m.body_mass[bid]=MASS
100
+ m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0]
101
+ for g in range(m.ngeom):
102
+ if m.geom_bodyid[g]==bid and (np.allclose(m.geom_rgba[g,:3],[.9,.4,.4]) or np.allclose(m.geom_rgba[g,:3],[.4,.5,.9])):
103
+ m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07)
104
+ envs.refit_bounds(self.env,bid)
105
+ envs.set_friction(self.env,BOX,MU)
106
+ envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001])
107
+ zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body)
108
+ m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002]
109
+
110
+ def reset_instance(self, inst, recorder=None):
111
+ self.loadmon=None
112
+ self._mon=None
113
+ self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15)
114
+ self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst))
115
+ self._start_monitor()
116
+ self.loadmon=dict(states=[False,False],count=[0,0],ever=[False,False],lost=[False,False],events=[],loaded=False,departed_unloaded=False,load_step=None,departure_step=None,last_robot_touch=[-10000,-10000])
117
+ self.ncmd=0;self.budget=None
118
+ return self.sk
119
+
120
+ def mark(self,i):
121
+ p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.)
122
+ spacing=.03 if self.inst['traps']['L2'] else .07
123
+ return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]])
124
+
125
+ def cargo_ok(self,i):
126
+ obj=('cube_1','blue_1')[i]
127
+ p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX)
128
+ return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and
129
+ abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj))
130
+
131
+ def _monitor_step(self):
132
+ super()._monitor_step()
133
+ mon=getattr(self,'loadmon',None)
134
+ if mon is None:return
135
+ robot=set(envs.robot_geom_ids(self.env))
136
+ for i,obj in enumerate(('cube_1','blue_1')):
137
+ geoms=set(envs.obj_geom_ids(self.env,obj))
138
+ for c in self.env.sim.data.contact[:self.env.sim.data.ncon]:
139
+ if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms):
140
+ mon['last_robot_touch'][i]=self.sk.n_steps
141
+ now=self.cargo_ok(i)
142
+ if now==mon['states'][i]:mon['count'][i]=0;continue
143
+ mon['count'][i]+=1
144
+ if mon['count'][i]<5:continue
145
+ mon['count'][i]=0;mon['states'][i]=now
146
+ ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost'
147
+ if now:mon['ever'][i]=True
148
+ else:
149
+ mon['lost'][i]=True
150
+ if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025:
151
+ mon['loaded']=False
152
+ mon['load_step']=None
153
+ mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev,
154
+ cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])),
155
+ cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other'))
156
+ displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])
157
+ if all(mon['states']) and displacement<.02 and not mon['loaded']:
158
+ mon['loaded']=True
159
+ mon['load_step']=self.sk.n_steps
160
+ if displacement>.03 and mon['departure_step'] is None:
161
+ mon['departure_step']=self.sk.n_steps
162
+ if not mon['loaded']:mon['departed_unloaded']=True
163
+
164
+ def pick_place(self,obj,xy,yaw=0.):
165
+ sk=self.sk;p=envs.obj_pos(self.env,obj)
166
+ sk.set_gripper(False,steps=10)
167
+ sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0. if obj=='cube_1' and self.under_table(margin=.08) else yaw)
168
+ sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002)
169
+ sk.set_gripper(True,steps=15)
170
+ held=sk.holding(obj)
171
+ sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15)
172
+ if held:
173
+ sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw)
174
+ bp=envs.obj_pos(self.env,BOX)
175
+ sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002)
176
+ sk.set_gripper(False,steps=15)
177
+ sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15)
178
+ return bool(held)
179
+
180
+ def load(self, careful=True):
181
+ self.pick_place('cube_1',self.mark(0),np.pi/2)
182
+ # Open fingers along y at the adjacent mark can knock the already loaded red cube.
183
+ yaw=np.pi/2 if careful else 0.
184
+ self.pick_place('blue_1',self.mark(1),yaw)
185
+
186
+ def repair_load(self):
187
+ for _ in range(3):
188
+ for i,o in enumerate(('cube_1','blue_1')):
189
+ if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2)
190
+
191
+ def transport(self,c=0.,repair=False):
192
+ # Call existing push controller on this same environment; no independent rollout stitching.
193
+ if not repair:
194
+ return OffcenterPush.execute(self,self.inst,dict(c=c))
195
+ if repair:
196
+ # Original feedback-driven corrector calls self.execute for its initial push.
197
+ self._transport_only=True
198
+ try:OffcenterPush.adaptive_attempt(self,self.inst,c)
199
+ finally:self._transport_only=False
200
+
201
+ _cmd=OffcenterPush._cmd
202
+ _sim_used=OffcenterPush._sim_used
203
+ _push_at=OffcenterPush._push_at
204
+ bracket=OffcenterPush.bracket
205
+ _front_runup=staticmethod(OffcenterPush._front_runup)
206
+ STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK
207
+ GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V
208
+
209
+ def execute(self,inst,params):
210
+ if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params)
211
+ if params.get('front',False):self.tool_push_front()
212
+ else:self.tool_push_out()
213
+ if self.under_table():return
214
+ self.load(params.get('careful',False))
215
+ if params.get('repair',False):self.repair_load()
216
+ if all(self.cargo_ok(i) for i in range(2)):
217
+ self.transport(params.get('c',0.),params.get('repair',False))
218
+ if params.get('repair',False):self.repair_load()
219
+ self.sk.set_gripper(False,steps=10)
220
+ p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24])
221
+
222
+ def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.)
223
+ def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.)
224
+ def adapt_params(self,inst,history):
225
+ # The L4 side hit is learned from actual prior outcome, not from inst['pane_side'].
226
+ seen_geometry=any(h['outcome']['traps']['L4'] for h in history)
227
+ seen_loading=any(h['outcome']['traps']['L2'] for h in history)
228
+ pushes=[m for h in history for m in h['outcome']['box_moves']]
229
+ return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes))
230
+
231
+ def outcome(self,inst):
232
+ self.sk.hold(30)
233
+ fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)]
234
+ ev=list(self.loadmon['events'])
235
+ # Loading regressions count only while cart remains at the loading station.
236
+ load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot']
237
+ loaded=self.loadmon['loaded']
238
+ static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05)
239
+ robot=set(envs.robot_geom_ids(self.env)); items=set()
240
+ for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o))
241
+ touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items)
242
+ for c in self.env.sim.data.contact[:self.env.sim.data.ncon])
243
+ budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3)
244
+ success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded
245
+ and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0
246
+ and self._mon['stick_touched_cube'])
247
+ moves=copy.deepcopy(self.sk.box_moves)
248
+ return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded),
249
+ static=static,touching=bool(touching),tool_used=bool(self._mon['stick_touched_cube']),load_step=self.loadmon['load_step'],departure_step=self.loadmon['departure_step'],commands=self.sk.robot_commands,budget_ok=budget_ok,departed_unloaded=self.loadmon['departed_unloaded'],
250
+ events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev),
251
+ traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)),
252
+ box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit,
253
+ detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.')
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/mismatch_plan.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mismatched-history control for layer 2 (user 2026-10-27: "错配历史的做一下"; design docs/14 §6 Do / Dm, current protocol).
2
+
3
+ Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance
4
+ (Sonnet 5.5: cc_main1 / cc_sonnet_s2 / cc_sonnet_s3; Opus 5.5: cc_opus1 / cc_opus_s2 / cc_opus_s3) whose attempt 1 failed.
5
+ Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI:
6
+ tw_<m> twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the
7
+ mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_<m>), then give up.
8
+ do_<m> own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py)
9
+ dm_<m> mismatched record: history/ = the failed twin run. README byte-identical to do_<m>; only history/ differs.
10
+
11
+ python3 scripts/mismatch_plan.py own build own records + write <OUT>/<m>/own.json and tasks_<m>.txt
12
+ python3 scripts/mismatch_plan.py twin <m> build twin records from tw_<m> (+ tw2_<m>) -> <OUT>/<m>/twin.json;
13
+ prints the instances still without a failed twin run
14
+ python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first
15
+ memory-free retry (N2), Do, Dm, twin; totals and paired counts
16
+ -> <OUT>/report.json + markdown on stdout
17
+ """
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import sys
22
+
23
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24
+ API = os.path.join(ROOT, "runs", "api")
25
+ OUT = os.path.join(API, "mismatch_20261027")
26
+ TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
27
+ "l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"]
28
+ MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]}
29
+
30
+
31
+ def runs(batch):
32
+ return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
33
+
34
+
35
+ def attempt1(log):
36
+ for line in open(os.path.join(log, "events.jsonl")):
37
+ e = json.loads(line)
38
+ if e.get("ev") == "done" and e.get("attempt") == 1:
39
+ return e
40
+ return None
41
+
42
+
43
+ def dossier(log, out):
44
+ if not os.path.isdir(out):
45
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True,
46
+ capture_output=True)
47
+ return out
48
+
49
+
50
+ def cmd_own():
51
+ for m, batches in MAIN.items():
52
+ own, tasks = {}, []
53
+ for b in batches:
54
+ for r in runs(b):
55
+ if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done":
56
+ continue
57
+ d = attempt1(r["log"])
58
+ if d is None or d["success"]:
59
+ continue
60
+ key = f"{r['task']}:{r['seed']}"
61
+ own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}"))
62
+ tasks.append(key)
63
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
64
+ json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1)
65
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n")
66
+ print(m, len(tasks))
67
+
68
+
69
+ def cmd_twin(m):
70
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
71
+ twin = {}
72
+ for b in (f"tw_{m}", f"tw2_{m}"):
73
+ if not os.path.exists(os.path.join(API, b, "manifest.json")):
74
+ continue
75
+ for r in runs(b):
76
+ key = f"{r['task']}:{r['seed']}"
77
+ if key in twin or r["status"] != "done":
78
+ continue
79
+ d = attempt1(r["log"])
80
+ if d is not None and not d["success"]:
81
+ twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}"))
82
+ json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1)
83
+ print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin])))
84
+
85
+
86
+ # twin oracle also solves the original instance (docs/14 §6.4, 10-12 validation): mismatch is weak there
87
+ WEAK = {"l3_wall_flush", "l3_under_table_tool"}
88
+
89
+
90
+ def single(batch):
91
+ """task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished."""
92
+ out = {}
93
+ if not os.path.exists(os.path.join(API, batch, "manifest.json")):
94
+ return out
95
+ for r in runs(batch):
96
+ if r["status"] == "done":
97
+ d = attempt1(r["log"])
98
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
99
+ return out
100
+
101
+
102
+ def main_rows(batches):
103
+ rows = {}
104
+ for b in batches:
105
+ tmp = os.path.join(OUT, f".oc_{b}.json")
106
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp],
107
+ check=True, capture_output=True)
108
+ for r in json.load(open(tmp))["rows"]:
109
+ rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"])
110
+ os.remove(tmp)
111
+ return rows
112
+
113
+
114
+ def cmd_report():
115
+ rep, md = {}, []
116
+ for m, batches in MAIN.items():
117
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
118
+ main = main_rows(batches)
119
+ do, dm = single(f"do_{m}"), single(f"dm_{m}")
120
+ t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists)
121
+ tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)}
122
+ rows = []
123
+ for k in want:
124
+ h, mf = main[k]["history"] or "", main[k]["memfree"] or ""
125
+ rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK,
126
+ H2=(h[1] == "S") if len(h) > 1 else None, N2=(mf[1] == "S") if len(mf) > 1 and mf[1] in "SF" else None,
127
+ Do=do.get(k), Dm=dm.get(k), twin=tw.get(k)))
128
+ def rate(key, sub):
129
+ v = [r[key] for r in sub if r[key] is not None]
130
+ return f"{sum(v)}/{len(v)}" if v else "-"
131
+ both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None]
132
+ pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both),
133
+ dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both))
134
+ rep[m] = dict(rows=rows, pairs=pairs)
135
+ md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |",
136
+ "|---|---|---|---|---|---|"]
137
+ f = lambda v: "-" if v is None else ("S" if v else "F")
138
+ for r in rows:
139
+ md.append(f"| {r['inst']}{' (weak)' if r['weak'] else ''} | {f(r['twin'])} | {f(r['H2'])} | {f(r['N2'])} | {f(r['Do'])} | {f(r['Dm'])} |")
140
+ strong = [r for r in rows if not r["weak"]]
141
+ md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; "
142
+ f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; "
143
+ f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""]
144
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
145
+ print("\n".join(md))
146
+
147
+
148
+ if __name__ == "__main__":
149
+ {"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l5_slide_to_target (docs/14 §6).
2
+
3
+ Hidden variable: mu, the cube-table sliding friction (apply_instance() sets it on every reset; oracle_params() bisects
4
+ the strike speed with it). The layout (cube_xy, target_dist) is kept.
5
+
6
+ The naive strike is 0.30 m/s. Where the cube stops depends on mu and, by up to ~1.5 cm, on the cube's position on the
7
+ table, and the target tolerance is only +-1 cm, so H0 and the twin are calibrated per full5 seed with a simulated sweep
8
+ (deterministic sim, scratchpad arms/fine.py, 2026-10-12); other seeds fall back to a power-law fit of the stopping
9
+ distance at 0.30 m/s (dist ~ 0.00453 / mu^1.04 m).
10
+
11
+ h0 mu at which the 0.30 m/s strike stops the cube on the square's centre (|err| <= 0.3 cm).
12
+ twin the opposite trap: if the original cube overshoots (slippery) the twin is grippy and stops short, and vice
13
+ versa, so the correction is the other way (slow down <-> speed up). The twin's naive error is at least 2 cm
14
+ and, where the twin's oracle still succeeds, about as large as the original's (mirrored). Seeds 3000 and 3007
15
+ overshoot by 6.9 / 4.1 cm, but a grippy cube cannot be made to stop that far short and still be solvable,
16
+ so their twins stop 2.1 / 3.4 cm short.
17
+ reveal states the friction coefficient only.
18
+ """
19
+
20
+ HIDDEN_KEYS = ("mu",)
21
+
22
+ # seed: h0 mu (naive err there), twin mu (twin naive err, twin oracle speed m/s -> err). Original naive err in brackets.
23
+ _CAL = {
24
+ 3000: dict(h0=0.0749, twin=0.1060), # [orig +6.94 cm] h0 +0.26; twin -2.13, oracle 0.551 -> +0.01
25
+ 3001: dict(h0=0.0602, twin=0.0783), # [orig +2.95 cm] h0 +0.14; twin -2.73, oracle 0.450 -> 0.00
26
+ 3003: dict(h0=0.0583, twin=0.0463), # [orig -1.73 cm] h0 +0.03; twin +2.75, oracle 0.242 -> -0.13
27
+ 3004: dict(h0=0.0537, twin=0.0444), # [orig -1.66 cm] h0 -0.31; twin +2.14, oracle 0.240 -> -0.02
28
+ 3007: dict(h0=0.0532, twin=0.0984), # [orig +4.05 cm] h0 +0.15; twin -3.39, oracle 0.570 -> -0.18
29
+ }
30
+
31
+
32
+ def _h0_mu(inst):
33
+ c = _CAL.get(int(inst.get("seed", -1)))
34
+ return c["h0"] if c else (0.00453 / float(inst["target_dist"])) ** (1 / 1.04)
35
+
36
+
37
+ def h0(inst):
38
+ return {"mu": float(_h0_mu(inst))}
39
+
40
+
41
+ def twin(inst):
42
+ c = _CAL.get(int(inst.get("seed", -1)))
43
+ if c:
44
+ return {"mu": float(c["twin"])}
45
+ m0 = _h0_mu(inst) # fallback: mirror mu about the H0 value in log space, kept in a solvable range
46
+ return {"mu": float(min(max(m0 * m0 / float(inst["mu"]), 0.03), 0.10))}
47
+
48
+
49
+ def reveal(inst):
50
+ return f"The red cube's sliding friction coefficient on the table is about {float(inst['mu']):.3f}."
51
+
52
+
53
+ def fix(inst, params):
54
+ """Ladder Fix rung (docs/20): one strike at the oracle speed (bisection with the true mu), 22 cm run-up, stopping
55
+ 1.5 cm past the cube's near face -- as l5_slide.execute; move_eef speed = Skills.move_to speed."""
56
+ v = float(params["speed"])
57
+ return (f"A way to succeed: one straight strike at the right speed. Close the gripper (yaw 0), put the fingertips "
58
+ f"just above the table (grasp point about 2 cm above the tabletop) 22 cm behind the cube's centre, on the "
59
+ f"robot's side and in line with the cube and the target, then in one move_eef command move straight "
60
+ f"forward at speed {v:.2f} to a point 1.5 cm past where the cube's near face was (0.5 cm short of its "
61
+ f"centre), and lift the gripper. The cube then slides into the target zone.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/camera.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map.
2
+
3
+ Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's
4
+ bottom-up buffer to an upright image):
5
+ u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image.
6
+ Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils.
7
+ """
8
+ import numpy as np
9
+ from robosuite.utils import camera_utils as CU
10
+
11
+ from .. import envs
12
+
13
+ # agent-facing camera name -> MuJoCo camera name
14
+ CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"}
15
+
16
+
17
+ def mj_cam(name):
18
+ if name in CAMERAS:
19
+ return CAMERAS[name]
20
+ if name in CAMERAS.values():
21
+ return name
22
+ raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}")
23
+
24
+
25
+ def intrinsics(env, cam, res):
26
+ return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res)
27
+
28
+
29
+ def cam_to_world(env, cam):
30
+ """4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward)."""
31
+ return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam))
32
+
33
+
34
+ def render_depth(env, cam, res):
35
+ """Metric depth (distance along the optical axis, metres), upright (res, res)."""
36
+ _, d = envs.render(env, mj_cam(cam), res, depth=True)
37
+ return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0))
38
+
39
+
40
+ def world_to_pixel(env, cam, xyz, res):
41
+ """Project a world point; returns (u, v) floats (u = column, v = row) and the depth."""
42
+ K = intrinsics(env, cam, res)
43
+ T = np.linalg.inv(cam_to_world(env, cam))
44
+ p = T @ np.append(np.asarray(xyz, float), 1.0)
45
+ uvw = K @ p[:3]
46
+ return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2])
47
+
48
+
49
+ def pixel_ray(env, cam, u, v, res):
50
+ """Unit ray direction (world) through pixel (u, v) and the camera origin."""
51
+ K = intrinsics(env, cam, res)
52
+ E = cam_to_world(env, cam)
53
+ d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0])
54
+ d = E[:3, :3] @ d_cam
55
+ return E[:3, 3].copy(), d / np.linalg.norm(d)
56
+
57
+
58
+ def pixel_to_world(env, cam, u, v, res, depth=None):
59
+ """Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict."""
60
+ if depth is None:
61
+ depth = render_depth(env, cam, res)
62
+ iu, iv = int(round(u)), int(round(v))
63
+ if not (0 <= iu < res and 0 <= iv < res):
64
+ raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image")
65
+ z = float(depth[iv, iu])
66
+ K = intrinsics(env, cam, res)
67
+ E = cam_to_world(env, cam)
68
+ p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0])
69
+ p = E @ p_cam
70
+ far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent
71
+ return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far))
72
+
73
+
74
+ def image_axes(env, cam, res, plane_z=envs.TABLE_Z):
75
+ """World directions of image-right and image-down at the image centre, projected onto the table
76
+ plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y)."""
77
+ o, d = pixel_ray(env, cam, res / 2, res / 2, res)
78
+ if abs(d[2]) < 1e-6:
79
+ return None
80
+ t = (plane_z - o[2]) / d[2]
81
+ c = o + t * d
82
+ out = []
83
+ for du, dv in ((8, 0), (0, 8)):
84
+ o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res)
85
+ t2 = (plane_z - o2[2]) / d2[2]
86
+ w = (o2 + t2 * d2 - c)[:2]
87
+ out.append(w / max(np.linalg.norm(w), 1e-9))
88
+ return out
89
+
90
+
91
+ def describe_axes(env, cam, res):
92
+ """Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign)."""
93
+ ax = image_axes(env, cam, res)
94
+ if ax is None:
95
+ return None
96
+ names = []
97
+ for w in ax:
98
+ i = int(np.argmax(np.abs(w)))
99
+ names.append(("+" if w[i] > 0 else "-") + "xy"[i])
100
+ return dict(right=names[0], down=names[1])
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l3_card_shelf.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3 card_shelf (2026-10-12): a deepened l3_card_edge. The thin card lies on a raised SHELF (thin top on four legs)
2
+ and hides a weight in one end; sliding the heavy end over the edge far enough to grasp it tips the card off the shelf
3
+ onto the table, where it lies flat and cannot be picked up: the attempt is lost.
4
+
5
+ Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 3.2): l3_card_edge saturated. Sonnet 5.5 (cla4) failed one
6
+ flat grasp, then in the same attempt slid the card 2-3 cm over the board's edge and grasped the overhang (both runs
7
+ succeeded on attempt 1): the failed grasp costs one command and changes nothing. Here the first common-sense
8
+ interaction (slide the nearest end out ~3 cm) has an irreversible cost whenever that end is the heavy one.
9
+
10
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): a wooden shelf
11
+ (top 22 x 26 x 1 cm on four 2 x 2 cm legs, top surface 10 cm above the table) with a thin red card (9.0 x 5.6 x 0.2 cm)
12
+ lying flat on it, long side along x or along y (+-8 deg). Its near end is 2.5-4 cm from the shelf edge it points to (an
13
+ x-card's near end is always the FORWARD one: a card that tips off the backward edge lands behind the shelf, hidden from
14
+ the front camera), the far end 9-14 cm from the opposite edge, both long sides >= 5 cm inside; a grey bin (16 x 16 cm
15
+ inside, 5 cm high) stands on the table beside the shelf (left or right, 6 cm gap). Same card size, mass (10 g),
16
+ friction and bin as l3_card_edge.
17
+
18
+ Hidden variable (instance level, the same in every attempt, invisible): 8 of the card's 10 g are a weight hidden in one
19
+ end; its centre of mass sits COM_E = 2.8 cm from the middle towards that end. Both ends look identical. In 14 of every
20
+ 20 consecutive seeds the heavy end is the NEAR end (the end a Sonnet-like agent slides out), else the far end.
21
+
22
+ Mechanism (physics, no teleport): an end slid out by h tips over the edge once the centre of mass passes it. Measured
23
+ (card teleported with overhang h, 2 s): heavy end stays for h <= 1.7 cm, tips for h >= 1.8 cm; light end stays up to
24
+ 7.0 cm; a uniform card up to ~4.5 cm. The grasp of an overhang needs the fingers past the edge: light end 1.8-3.8 cm
25
+ out -> 11/12 grasped; the heavy end only in a narrow window (1.3-1.5 cm out, grasp 0.8-1.2 cm beyond the edge: 12/36).
26
+ A tipped card is flat on the table within 0.4 s (56/56 tilt 0), where it cannot be gripped (0/56 regrasps) and no edge
27
+ is in reach. The fix is to slide the OTHER end out (a longer slide across the shelf), learnable from the failure: "only
28
+ ~2 cm out and it already tipped -> that end is heavy" (the cheaper explanation "I pushed too far" leads to pushing
29
+ less, which leaves too little overhang to grasp). Validation (seeds 1000-1019): Sonnet-like naive tips 14/14 heavy-near
30
+ instances and succeeds on 6/6 light-near ones; the same habit succeeds 20/20 on l3_card_edge and 20/20 here with a
31
+ uniform card.
32
+
33
+ Implementation notes: the centre of mass is fixed in the generated MJCF (explicit <inertial pos="COM_E 0 0">) and the
34
+ heavy end is chosen by the card's yaw (the card is symmetric), so the body's inertial frame is never changed at runtime
35
+ (no bounding-volume refit needed; see lh_fence / envs.refit_bounds for that MuJoCo pitfall). The inertia is written in
36
+ scientific notation: objects._fmt (5 decimals) rounds a 10-30 g card's inertia to ~0 (a 10 g card does not compile; a
37
+ 30 g card with rounded inertia got pinched and lifted by the flat grasp 4/16). Mass 10 g as in l3_card_edge: the flat
38
+ grasp then fails 20/20 (fingers slide over the card). The shelf is a static multi-geom fixture; its legs stand inside
39
+ its top's footprint (robot-leg contacts: 0 in all scripted runs).
40
+
41
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: success = the card lies in the bin,
42
+ not held; plus a per-step event log (end / side slid over an edge, tipped_off, lifted, released, in_bin, hand_hit_leg)
43
+ and R6 fields (tipped_off, trap_fired, grasp_tries) for the server log; F1 gives the agent only success / failure.
44
+ """
45
+ import numpy as np
46
+
47
+ from .. import envs
48
+ from ..bddl import write_bddl
49
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
50
+ from ..skills import Skills
51
+ from ..task_base import LFFTask, register_task
52
+
53
+ TZ = envs.TABLE_Z
54
+ CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm (as l3_card_edge)
55
+ CARD_MASS = 0.010 # as l3_card_edge (flat grasp fails 20/20; a 30 g card was pinched and lifted 4/16)
56
+ SLUG_MASS = 0.008 # hidden weight (+ 2 g of card); slug centre 3.5 cm from the middle
57
+ COM_E = 0.028 # centre of mass this far from the card's middle, towards the heavy end (the card's local +x)
58
+ MU = 0.3 # card and shelf sliding friction (as l3_card_edge)
59
+ SHELF_HALF = (0.11, 0.13) # top half extents (as l3_card_edge's board)
60
+ SHELF_H = 0.10 # top surface above the table
61
+ TOP_T = 0.01 # top thickness
62
+ LEG = 0.01 # leg half width (2 x 2 cm legs)
63
+ LEG_IN = 0.012 # leg centre to the top's edges
64
+ SHELF_TOP = TZ + SHELF_H
65
+ CARD_REST_Z = SHELF_TOP + CARD_HALF[2]
66
+ BIN_IN = 0.08 # inner half width
67
+ BIN_WALL_H = 0.05
68
+ BIN_GAP = 0.06 # shelf edge to bin outer wall
69
+ BIN_T = 0.006
70
+ BIN_HALF_OUT = BIN_IN + BIN_T
71
+ TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
72
+ LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
73
+
74
+ # instance ranges
75
+ P_HEAVY_NEAR = 0.7 # 14 of every 20 consecutive seeds
76
+ NEAR_GAP = (0.025, 0.040) # near end to its shelf edge
77
+ SIDE_CLEAR = 0.05 # long sides to the shelf's side edges, at least
78
+ YAW_JIT = np.radians(8.0)
79
+
80
+ # scripted policies
81
+ GRASP_OUT = 0.022 # grasp point this far beyond the edge (fingers must clear the edge)
82
+ DRAG_SPEED = 0.08
83
+ NAIVE_STEPS = (0.0, 0.01, 0.02, 0.03) # Sonnet-like: slide the end to the edge, then out in 1 cm steps, lift & look
84
+ ORACLE_STEPS = (0.02, 0.03) # l3_card_edge oracle: to 1 cm short, look, the rest
85
+
86
+ EDGES = ("forward", "backward", "left", "right") # shelf edges in robot-centric words (+x, -x, +y, -y)
87
+ EDGE_U = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)}
88
+ OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
89
+
90
+
91
+ def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
92
+ """Uniform-looking card; the inertial (10 g, centre of mass COM_E along local +x) models an 8 g weight hidden in
93
+ the +x end. Explicit inertial pos != 0, so MuJoCo keeps a separate inertial frame (see module doc)."""
94
+ h = CARD_HALF
95
+ ms = CARD_MASS - SLUG_MASS
96
+ xs = COM_E * CARD_MASS / SLUG_MASS # slug centre
97
+ sl = (0.0075, 0.021, h[2]) # slug half extents (1.5 x 4.2 x 0.2 cm)
98
+ box_i = lambda mm, a: mm / 3 * np.array([a[1] ** 2 + a[2] ** 2, a[0] ** 2 + a[2] ** 2, a[0] ** 2 + a[1] ** 2])
99
+ par = lambda mm, r: mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
100
+ c = np.array([COM_E, 0.0, 0.0])
101
+ inertia = box_i(ms, h) + par(ms, -c) + box_i(SLUG_MASS, sl) + par(SLUG_MASS, np.array([xs, 0.0, 0.0]) - c)
102
+ g = (f' <inertial pos="{_fmt(c)}" mass="{CARD_MASS}" diaginertia="{" ".join(f"{v:.6e}" for v in inertia)}" />\n'
103
+ f' <geom name="{name}_g0" type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" '
104
+ f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
105
+ f' <geom type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
106
+ return _wrap(name, g, h[2], float(np.hypot(h[0], h[1])))
107
+
108
+
109
+ def shelf_xml(name, rgba=(0.62, 0.45, 0.27, 1.0), leg_rgba=(0.50, 0.36, 0.21, 1.0)):
110
+ """Static shelf: top plate on four legs; body origin at mid height (top surface at +SHELF_H / 2)."""
111
+ hx, hy = SHELF_HALF
112
+ H = SHELF_H / 2
113
+ parts = [((0.0, 0.0, H - TOP_T / 2), (hx, hy, TOP_T / 2), rgba)]
114
+ for sx in (-1, 1):
115
+ for sy in (-1, 1):
116
+ parts.append(((sx * (hx - LEG_IN), sy * (hy - LEG_IN), -TOP_T / 2), (LEG, LEG, H - TOP_T / 2), leg_rgba))
117
+ g = []
118
+ for k, (p, s, c) in enumerate(parts):
119
+ g.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
120
+ f'density="500" friction="{MU} 0.005 0.0001" {_SOLID} group="0" />')
121
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" contype="0" '
122
+ f'conaffinity="0" group="1" />')
123
+ return _wrap(name, "\n".join(g), H, float(np.hypot(hx, hy)))
124
+
125
+
126
+ def _yaw_of(quat_wxyz):
127
+ w, x, y, z = quat_wxyz
128
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
129
+
130
+
131
+ class ShelfSkills(Skills):
132
+ """Skills that feed the task's per-step monitor and log every close of the gripper."""
133
+
134
+ def __init__(self, env, task, recorder=None):
135
+ super().__init__(env, recorder=recorder)
136
+ self.task = task
137
+ self.closes = []
138
+
139
+ def _act(self, dpos, drot, grip):
140
+ super()._act(dpos, drot, grip)
141
+ self.task.monitor_step()
142
+
143
+ def set_gripper(self, close, steps=15):
144
+ was_open = self.grip < 0
145
+ before = self.task.close_context() if (close and was_open) else None
146
+ rep = super().set_gripper(close, steps)
147
+ if before is not None:
148
+ before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
149
+ self.closes.append(before)
150
+ return rep
151
+
152
+
153
+ @register_task
154
+ class CardShelf(LFFTask):
155
+ name = "l3_card_shelf"
156
+ level = "L3"
157
+ category = "strategy_switching"
158
+ capabilities = ("Perceive", "Reason", "Plan")
159
+ protocol = "cross"
160
+ max_attempts = 3
161
+ agent_max_steps = 40
162
+ instruction = "Pick up the thin red card lying on the wooden shelf and put it into the grey bin."
163
+ instruction_indirect = "Put the flat red rectangle that lies on the raised wooden platform into the grey container."
164
+
165
+ # ------------------------------------------------------------ scene
166
+ def make_bddl(self):
167
+ card = register_generated("LffShelfCard", card_xml("lff_shelf_card"))
168
+ shelf = register_generated("LffCardShelf", shelf_xml("lff_card_shelf"), free=False)
169
+ bin_ = register_generated("LffShelfBin", bin_xml("lff_shelf_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
170
+ rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
171
+ objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
172
+ fx = [("shelf_1", shelf, "shelf_region", (-0.11, -0.01, -0.09, 0.01)),
173
+ ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
174
+ return write_bddl(self.name, self.instruction, objs, fx)
175
+
176
+ def __init__(self, cam_res=None):
177
+ super().__init__(cam_res)
178
+ m = self.env.sim.model
179
+ self.shelf_bid = m.body_name2id(self.env.fixtures_dict["shelf_1"].root_body)
180
+ self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
181
+ g0 = int(m.body_geomadr[self.shelf_bid])
182
+ self.leg_geoms = {g for g in range(g0, g0 + int(m.body_geomnum[self.shelf_bid]))
183
+ if (m.geom_id2name(g) or "").endswith(("_g1", "_g2", "_g3", "_g4"))}
184
+ self.robot_geoms = set(envs.robot_geom_ids(self.env))
185
+ self.inst = None
186
+ self.mon = None
187
+
188
+ def sample_instance(self, seed):
189
+ rng = np.random.default_rng(seed)
190
+ bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
191
+ along = str(rng.choice(["x", "y"]))
192
+ near_sign = 1.0 if rng.random() < 0.5 else -1.0
193
+ if along == "x": # the near end of an x-card is the forward one: a card that tips off the backward edge lands
194
+ near_sign = 1.0 # behind the shelf, hidden from the front camera (measured); forward = nearest = away from the robot
195
+ jit = float(rng.uniform(-YAW_JIT, YAW_JIT))
196
+ gap = float(rng.uniform(*NEAR_GAP))
197
+ heavy_near = bool((int(seed) * 7) % 20 < round(20 * P_HEAVY_NEAR)) # balanced per 20 consecutive seeds
198
+ a_long, a_side = (0, 1) if along == "x" else (1, 0) # world axis of the card's long / short side
199
+ ext_long = CARD_HALF[0] * abs(np.cos(jit)) + CARD_HALF[1] * abs(np.sin(jit)) # half extents incl. the jitter
200
+ ext_side = CARD_HALF[0] * abs(np.sin(jit)) + CARD_HALF[1] * abs(np.cos(jit))
201
+ c = [bx, by]
202
+ c[a_long] += near_sign * (SHELF_HALF[a_long] - gap - ext_long)
203
+ room = SHELF_HALF[a_side] - ext_side - SIDE_CLEAR
204
+ c[a_side] += float(rng.uniform(-room, room))
205
+ u_near = np.zeros(2)
206
+ u_near[a_long] = near_sign
207
+ near_edge = {(1.0, 0.0): "forward", (-1.0, 0.0): "backward", (0.0, 1.0): "left", (0.0, -1.0): "right"}[
208
+ (float(u_near[0]), float(u_near[1]))]
209
+ heavy_dir = u_near if heavy_near else -u_near # the card's local +x (heavy end) points this way (+- jitter)
210
+ yaw = float(np.arctan2(heavy_dir[1], heavy_dir[0]) + jit)
211
+ side = 1.0 if rng.random() < 0.5 else -1.0
212
+ bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (SHELF_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
213
+ return dict(seed=int(seed), shelf_xy=[bx, by], card_xy=[float(c[0]), float(c[1])], card_yaw=yaw,
214
+ card_along=along, near_edge=near_edge, far_edge=OPPOSITE[near_edge], near_gap=gap,
215
+ heavy_near=heavy_near, heavy_edge=near_edge if heavy_near else OPPOSITE[near_edge],
216
+ com_offset=COM_E, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
217
+
218
+ def apply_instance(self, inst):
219
+ self.inst = inst
220
+ m = self.env.sim.model
221
+ bx, by = inst["shelf_xy"]
222
+ m.body_pos[self.shelf_bid] = [bx, by, TZ + SHELF_H / 2]
223
+ m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0]
224
+ cx, cy = inst["bin_xy"]
225
+ m.body_pos[self.bin_bid] = [cx, cy, TZ + (BIN_WALL_H + BIN_T) / 2]
226
+ m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
227
+ x, y = inst["card_xy"]
228
+ envs.set_obj_pose(self.env, "card_1", [x, y, CARD_REST_Z + 0.0003], yaw=inst["card_yaw"])
229
+
230
+ def reset_instance(self, inst, recorder=None):
231
+ self.env.reset()
232
+ self.apply_instance(inst)
233
+ self.env.sim.forward()
234
+ envs.settle(self.env, 15)
235
+ self.sk = ShelfSkills(self.env, self, recorder=recorder)
236
+ p = self.card_pose()
237
+ self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False, lifted=False,
238
+ out=dict(heavy=0.0, light=0.0, side=0.0), out_edge=dict(heavy=None, light=None, side=None),
239
+ flagged=set(), events=[], in_bin=False, tip=None, leg_hits=0, edge_used=None)
240
+ return self.sk
241
+
242
+ # ------------------------------------------------------------ geometry
243
+ def card_pose(self):
244
+ p = envs.obj_pos(self.env, "card_1")
245
+ return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
246
+
247
+ def _card_frame(self):
248
+ d = self.env.sim.data
249
+ bid = envs.body_id(self.env, "card_1")
250
+ return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
251
+
252
+ def card_corners(self):
253
+ p, R = self._card_frame()
254
+ h = np.array(CARD_HALF)
255
+ return np.array([p + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
256
+
257
+ def _beyond(self, xy):
258
+ """{edge: how far the point lies beyond that edge of the shelf top (m, negative = inside)}"""
259
+ b = np.asarray(xy, float) - np.asarray(self.inst["shelf_xy"])
260
+ return {"forward": b[0] - SHELF_HALF[0], "backward": -b[0] - SHELF_HALF[0],
261
+ "left": b[1] - SHELF_HALF[1], "right": -b[1] - SHELF_HALF[1]}
262
+
263
+ def overhang(self):
264
+ """(how far the card sticks out beyond the shelf's edges (m, max over its corners), edge word)"""
265
+ best = (-1.0, None)
266
+ for c in self.card_corners():
267
+ for e, v in self._beyond(c[:2]).items():
268
+ if v > best[0]:
269
+ best = (float(v), e)
270
+ return best
271
+
272
+ def part_overhangs(self):
273
+ """{'heavy' | 'light' | 'side': (overhang m, edge)}: the heavy end (local +x), light end and long sides,
274
+ each measured at its two corners."""
275
+ p, R = self._card_frame()
276
+ h = np.array(CARD_HALF)
277
+ groups = {"heavy": [(1, -1), (1, 1)], "light": [(-1, -1), (-1, 1)]}
278
+ out = {}
279
+ for k, cs in groups.items():
280
+ best = (-1.0, None)
281
+ for sx, sy in cs:
282
+ c = p + R @ (h * [sx, sy, 0.0])
283
+ for e, v in self._beyond(c[:2]).items():
284
+ if v > best[0]:
285
+ best = (float(v), e)
286
+ out[k] = best
287
+ best = (-1.0, None) # a long side: its middle point (an end pushed out also moves two corners out)
288
+ for sy in (-1, 1):
289
+ c = p + R @ (h * [0.0, sy, 0.0])
290
+ for e, v in self._beyond(c[:2]).items():
291
+ if v > best[0]:
292
+ best = (float(v), e)
293
+ out["side"] = best
294
+ return out
295
+
296
+ def end_edge(self, which):
297
+ """shelf edge that the card's `which` end ('heavy' | 'light' | 'near' | 'far') points to, from the live pose"""
298
+ p = self.card_pose()
299
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) # heavy end direction
300
+ if which == "near" or which == "far":
301
+ gaps = {}
302
+ for s in (1.0, -1.0):
303
+ u = d * s
304
+ e = max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
305
+ tip = p["xy"] + u * CARD_HALF[0]
306
+ gaps[e] = -self._beyond(tip)[e]
307
+ near = min(gaps, key=gaps.get)
308
+ return near if which == "near" else OPPOSITE[near]
309
+ u = d if which == "heavy" else -d
310
+ return max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
311
+
312
+ def on_shelf(self):
313
+ p = self.card_pose()
314
+ rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
315
+ return bool(rel[0] <= SHELF_HALF[0] and rel[1] <= SHELF_HALF[1] and abs(p["z"] - CARD_REST_Z) < 0.012)
316
+
317
+ def on_table(self):
318
+ return bool(self.card_pose()["z"] < TZ + 0.03 and not self.in_bin())
319
+
320
+ def tilt_deg(self):
321
+ _, R = self._card_frame()
322
+ return float(np.degrees(np.arccos(np.clip(abs(R[2, 2]), 0.0, 1.0))))
323
+
324
+ def in_bin(self):
325
+ p = self.card_pose()
326
+ rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
327
+ return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < TZ + BIN_T + BIN_WALL_H)
328
+
329
+ # ------------------------------------------------------------ monitor
330
+ def _event(self, ev, **kw):
331
+ self.mon["events"].append(dict(event=ev, step=int(self.sk.n_steps), **kw))
332
+
333
+ def monitor_step(self):
334
+ mon = self.mon
335
+ if mon is None or self.sk is None:
336
+ return
337
+ p = self.card_pose()
338
+ held = self.sk.holding("card_1")
339
+ zmin = float(self.card_corners()[:, 2].min())
340
+ mon["max_lift"] = max(mon["max_lift"], zmin - SHELF_TOP)
341
+ if held and zmin - SHELF_TOP > 0.02 and not mon["lifted"]:
342
+ mon["lifted"] = True
343
+ self._event("lifted")
344
+ rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
345
+ if (not held and abs(p["z"] - CARD_REST_Z) < 0.004 and self.tilt_deg() < 5.0 and rel[0] <= SHELF_HALF[0]
346
+ and rel[1] <= SHELF_HALF[1]): # lying flat on the shelf
347
+ mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
348
+ for k, (v, e) in self.part_overhangs().items():
349
+ if v > mon["out"][k]:
350
+ mon["out"][k], mon["out_edge"][k] = v, e
351
+ if v >= 0.005 and k not in mon["flagged"]:
352
+ mon["flagged"].add(k)
353
+ self._event("side_over_edge" if k == "side" else "end_over_edge", part=k, edge=e)
354
+ if p["z"] < SHELF_TOP - 0.02 and not held and not mon["fell"]:
355
+ mon["fell"] = True
356
+ if not mon["lifted"]: # never lifted: it tipped (or was pushed) off the shelf
357
+ part = max(("heavy", "light", "side"), key=lambda k: mon["out"][k])
358
+ mon["tip"] = dict(part=part, edge=mon["out_edge"][part], overhang=round(mon["out"][part], 4))
359
+ self._event("tipped_off", **mon["tip"])
360
+ else:
361
+ self._event("released")
362
+ d = self.env.sim.data
363
+ for i in range(d.ncon): # the hand / arm touching a shelf leg (should not happen in normal grasps)
364
+ c = d.contact[i]
365
+ if (c.geom1 in self.leg_geoms and c.geom2 in self.robot_geoms) or (c.geom2 in self.leg_geoms and
366
+ c.geom1 in self.robot_geoms):
367
+ if mon["leg_hits"] == 0:
368
+ self._event("hand_hit_leg")
369
+ mon["leg_hits"] += 1
370
+ break
371
+ if not mon["in_bin"] and self.in_bin() and not held:
372
+ mon["in_bin"] = True
373
+ self._event("in_bin")
374
+
375
+ def close_context(self):
376
+ """Where the gripper is relative to the card and the shelf just before it closes."""
377
+ sk, p = self.sk, self.card_pose()
378
+ e = sk.eef_pos()
379
+ c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
380
+ rel = e[:2] - p["xy"]
381
+ local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side (+ = heavy end)
382
+ beyond = self._beyond(e[:2])
383
+ edge = max(beyond, key=beyond.get)
384
+ ov, ov_edge = self.overhang()
385
+ return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
386
+ tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
387
+ beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
388
+ card_on_shelf=self.on_shelf(), overhang=round(ov, 4), overhang_edge=ov_edge,
389
+ width_before=round(sk.gripper_width(), 4))
390
+
391
+ # ------------------------------------------------------------ outcome / F2
392
+ def outcome(self, inst):
393
+ envs.settle(self.env, 30)
394
+ self.monitor_step()
395
+ sk, mon = self.sk, self.mon
396
+ p = self.card_pose()
397
+ held = bool(sk.holding("card_1"))
398
+ in_bin = self.in_bin() and not held
399
+ success = bool(in_bin)
400
+ moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
401
+ lifted = mon["max_lift"] > 0.02
402
+ tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
403
+ parts, mode = [], "success"
404
+ rel = p["xy"] - np.asarray(inst["bin_xy"])
405
+ where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
406
+ f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
407
+ tip = mon["tip"]
408
+ if success:
409
+ parts.append("The card is in the bin.")
410
+ elif held:
411
+ mode = "held"
412
+ parts.append(f"The card is still held by the gripper, {where}.")
413
+ elif lifted:
414
+ mode = "dropped"
415
+ loc = ("on the shelf" if self.on_shelf() else "on the table" if self.on_table() else
416
+ "partly on the shelf" if p["z"] > SHELF_TOP - 0.02 else "off the shelf")
417
+ parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the shelf but is not in the "
418
+ f"bin: it lies {loc}, its centre {where}.")
419
+ elif mon["fell"]:
420
+ mode = "fell_off"
421
+ what = "a long side" if tip["part"] == "side" else "one end"
422
+ parts.append(f"The card was never lifted: after {what} of it had been slid {100 * max(tip['overhang'], 0):.1f}"
423
+ f" cm beyond the shelf's {tip['edge']} edge, it tipped over that edge and fell off the shelf; "
424
+ + ("it lies flat on the table." if self.on_table() and self.tilt_deg() < 10 else
425
+ f"it rests off the shelf, tilted {self.tilt_deg():.0f} degrees."))
426
+ else:
427
+ mode = "not_lifted"
428
+ parts.append("The card was never lifted; it still lies flat on the shelf"
429
+ + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
430
+ f"{100 * mon['max_overhang']:.1f} cm beyond the shelf's edge)" if mon["max_overhang"] > 0.003
431
+ else ")") if moved > 0.005 else "") + ".")
432
+ if not success and not lifted and tries:
433
+ c = tries[-1]
434
+ n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
435
+ if c["card_on_shelf"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
436
+ txt = ("when the gripper closed on the card lying flat on the shelf, its fingertips were on either side "
437
+ "of the card, at shelf level")
438
+ else:
439
+ pos = (f"{100 * c['beyond_edge']:.1f} cm beyond the shelf's {c['beyond_edge_name']} edge"
440
+ if c["beyond_edge"] >= 0.0 else
441
+ f"over the shelf, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge")
442
+ txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm beyond the "
443
+ f"shelf's {c['overhang_edge']} edge and the gripper's centre was {pos}")
444
+ txt += f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the fingers closed "
445
+ txt += ("fully, sliding over the top of the card instead of gripping its edges."
446
+ if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
447
+ ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
448
+ parts.append(n + txt if n else txt[0].upper() + txt[1:])
449
+ elif not success and not lifted and not mon["fell"]:
450
+ parts.append("The gripper never closed with its fingertips down at the card.")
451
+ failure = "none" if success else mode
452
+ out = dict(success=success, mode=mode, failure=failure, held=held, lifted=bool(lifted),
453
+ max_lift=round(mon["max_lift"], 4), max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4),
454
+ fell=bool(mon["fell"]), tipped_off=tip is not None, trap_fired=bool(tip is not None and
455
+ tip["part"] == "heavy"),
456
+ tip=tip, end_out={k: round(v, 4) for k, v in mon["out"].items()},
457
+ end_out_edge=dict(mon["out_edge"]), card_final=dict(xy=[round(float(v), 4) for v in p["xy"]],
458
+ z_above_table=round(p["z"] - TZ, 4),
459
+ tilt_deg=round(self.tilt_deg(), 1)),
460
+ leg_hits=int(mon["leg_hits"]), slid_edge=mon["edge_used"],
461
+ events=list(mon["events"]), grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
462
+ return out
463
+
464
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
465
+ def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
466
+ sk = self.sk
467
+ sk.set_gripper(False, steps=8)
468
+ sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
469
+ sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
470
+ sk.set_gripper(True, steps=15)
471
+ sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
472
+ if not sk.holding("card_1"):
473
+ sk.set_gripper(False, steps=8)
474
+ return False
475
+ bx, by = self.inst["bin_xy"]
476
+ hi = SHELF_TOP + 0.10
477
+ sk.move_to([bx, by, hi])
478
+ sk.move_to([bx, by, TZ + BIN_WALL_H + 0.05], speed=0.2)
479
+ sk.set_gripper(False, steps=12)
480
+ sk.move_to([bx, by, hi])
481
+ return True
482
+
483
+ def slide_card(self, delta, press=0.004, at=(0.0, 0.0)):
484
+ """closed fingertips pressed on the card (at its centre + `at`), straight move by `delta` (xy), lift"""
485
+ sk, p = self.sk, self.card_pose()
486
+ z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
487
+ s = p["xy"] + np.asarray(at, float)
488
+ sk.set_gripper(True, steps=8)
489
+ sk.move_to([s[0], s[1], z + 0.06], yaw=p["yaw"])
490
+ sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
491
+ e = s + np.asarray(delta, float)
492
+ sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
493
+ sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
494
+ sk.hold(10) # look
495
+
496
+ def push_end(self, u, dist, behind=0.015):
497
+ """closed fingers at shelf level `behind` m behind the card's trailing end, push it `dist` along u, lift"""
498
+ sk, p = self.sk, self.card_pose()
499
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
500
+ la = d * np.sign(d @ u) if abs(d @ u) > 0.5 else d
501
+ tail = p["xy"] - la * CARD_HALF[0]
502
+ s = tail - u * behind
503
+ z = SHELF_TOP + TIP_BELOW_SITE - 0.001 # fingertips on the shelf top (2 mm above: they pass over the card)
504
+ yaw = float(np.arctan2(u[1], u[0]) - np.pi / 2) # finger axis across the push direction
505
+ sk.set_gripper(True, steps=8)
506
+ sk.move_to([s[0], s[1], z + 0.05], yaw=yaw)
507
+ sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
508
+ e = s + u * (behind + dist)
509
+ sk.move_to([e[0], e[1], z], speed=0.04, tol=0.004, max_steps=300)
510
+ sk.move_to([e[0], e[1], z + 0.05], speed=0.2)
511
+ sk.hold(10)
512
+
513
+ def execute(self, inst, params):
514
+ p = self.card_pose()
515
+ rng = np.random.default_rng(params.get("noise_seed")) if params.get("noise_seed") is not None else None
516
+ if params.get("probe_grasp", False) or params["mode"] == "grasp": # flat grasp at the card's middle
517
+ dxy = np.asarray(params.get("probe_dxy", (0.0, 0.0)))
518
+ self.grasp_and_bin(p["xy"] + dxy, p["yaw"], SHELF_TOP + params.get("probe_dz", 0.0))
519
+ if params["mode"] == "grasp" or self.sk.holding("card_1") or self.mon["lifted"]:
520
+ return
521
+ # slide one end of the card along its long side out over the edge it points to, in strokes
522
+ edge = params.get("edge") or self.end_edge(params.get("end", "near"))
523
+ self.mon["edge_used"] = edge
524
+ u = np.asarray(EDGE_U[edge], float)
525
+ b = np.asarray(inst["shelf_xy"])
526
+ half = SHELF_HALF[0] if edge in ("forward", "backward") else SHELF_HALF[1]
527
+ edge_pos = float(b @ u) + half
528
+ for k, target in enumerate(params.get("steps", ORACLE_STEPS)):
529
+ if not self.on_shelf():
530
+ return # tipped off: nothing left to grasp (the attempt is lost)
531
+ p = self.card_pose()
532
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
533
+ la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
534
+ ext = max(float(c[:2] @ u) for c in self.card_corners()) - float(p["xy"] @ u)
535
+ tgt = float(target) + (float(rng.uniform(-1, 1)) * params.get("step_noise", 0.0) if rng is not None else 0.0)
536
+ need = edge_pos + tgt - (float(p["xy"] @ u) + ext) # travel still needed along u
537
+ if need > 0.003:
538
+ if params.get("style", "press") == "endpush":
539
+ self.push_end(u, need)
540
+ else:
541
+ at = (np.asarray(params.get("press_at", (0.0, 0.0))) if rng is None else
542
+ rng.normal(0.0, params.get("press_noise", 0.0), 2))
543
+ self.slide_card(la * need / max(float(la @ u), 1e-6), at=at)
544
+ self.sk.hold(10)
545
+ if not self.on_shelf():
546
+ return
547
+ q = self.card_pose()
548
+ d = np.array([np.cos(q["yaw"]), np.sin(q["yaw"])])
549
+ la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
550
+ cu = float(q["xy"] @ u)
551
+ tip_u = max(float(c[:2] @ u) for c in self.card_corners()) # outermost point of the card along u
552
+ target_u = min(tip_u - 0.008, edge_pos + params.get("grasp_out", GRASP_OUT))
553
+ g = q["xy"] + la * (target_u - cu) / max(float(la @ u), 1e-6)
554
+ g = g + np.asarray(params.get("grasp_dxy", (0.0, 0.0)))
555
+ self.grasp_and_bin(g, q["yaw"], SHELF_TOP - 0.003 + params.get("grasp_dz", 0.0))
556
+
557
+ def default_params(self, inst):
558
+ """Sonnet-like (cla4 l3_card_edge): one flat grasp, then the nearest end out to the edge and 1 cm at a time
559
+ to ~3 cm, lifting the finger and looking after each stroke; grasp the overhang."""
560
+ return dict(mode="edge", probe_grasp=True, end="near", steps=list(NAIVE_STEPS))
561
+
562
+ def oracle_params(self, inst):
563
+ """Knows the hidden weight: slides the light end out 3 cm (two strokes, as the l3_card_edge oracle)."""
564
+ return dict(mode="edge", end="light", steps=list(ORACLE_STEPS))
565
+
566
+ def blind_params(self, inst, attempt, rng):
567
+ """naive with small random variations, no history: nearest end, 2.5-3.5 cm, pressing point / grasp jitter"""
568
+ return dict(mode="edge", probe_grasp=True, end="near", steps=[0.0, 0.01, 0.02, float(rng.uniform(0.025, 0.035))],
569
+ noise_seed=int(rng.integers(1 << 30)), press_noise=0.005,
570
+ grasp_dxy=rng.uniform(-0.005, 0.005, 2).tolist(), grasp_dz=float(rng.uniform(-0.004, 0.003)))
571
+
572
+ def adapt_params(self, inst, history):
573
+ """Tipped off the shelf (never lifted) -> slide the OTHER end next time (it tipped although only ~2 cm stuck
574
+ out: that end must be heavy). Slid out but not gripped -> 1 cm more overhang. Otherwise repeat."""
575
+ out, prm = history[-1]["outcome"], history[-1]["params"]
576
+ used = out.get("slid_edge") or prm.get("edge")
577
+ nxt = dict(mode="edge", probe_grasp=False, edge=used, steps=list(ORACLE_STEPS))
578
+ if out["mode"] == "fell_off":
579
+ e = (out.get("tip") or {}).get("edge") or used
580
+ nxt["edge"] = OPPOSITE.get(e)
581
+ elif out["mode"] == "not_lifted" and used is not None:
582
+ last = float((prm.get("steps") or ORACLE_STEPS)[-1])
583
+ nxt["steps"] = [s + 0.01 for s in ORACLE_STEPS] if last < 0.035 else list(ORACLE_STEPS)
584
+ if nxt["edge"] is None:
585
+ nxt.pop("edge")
586
+ nxt["end"] = "near"
587
+ return nxt
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/model_gateway.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-run model-API gateway: the native harness's only road to its model API (docs/15 §3.2, docs/18 §3 rows 5 and 8).
2
+
3
+ The harness (Codex, Claude Code, a robot harness framework on Codex) is pointed at this process instead of its model
4
+ API; the gateway forwards model requests unchanged to the same upstream with the harness's own credentials (it never
5
+ stores or logs a key or a header) and refuses, without forwarding, everything that would let the model use something
6
+ outside the benchmark's three tools:
7
+ - a path that is not a model call (connectors, apps, plugins, files, conversations, web search endpoints, ...);
8
+ - a request declaring a tool the harness does not run itself: any OpenAI tool type other than function / custom /
9
+ namespace (web_search, file_search, code_interpreter, image_generation, remote mcp, computer_use, local_shell ...),
10
+ any Anthropic tool with a server/built-in type (web_search_*, web_fetch_*, code_execution_*, bash_*, ...);
11
+ - a provider-side field (stored prompt, remote MCP servers, search options, containers);
12
+ - an image or file given as an http(s) address for the provider to fetch (data: URLs are fine);
13
+ - a body the gateway cannot read (more than one Content-Encoding, an encoding it cannot decode, not one JSON object).
14
+ A refusal is answered 403 with an error naming the reason and is recorded; it does not void the trial (nothing tells
15
+ the agent trying is forbidden), the launcher flags it in harness.json for a look. Same rules as Embodied First Exam's
16
+ usage gateway (running.md "Usage gateway"); the motivating case there: a harness offered tools that ran on the
17
+ provider's servers, outside the container's network rules, and agents used them.
18
+
19
+ It also counts tokens per request from the response (OpenAI `response.completed` usage, Anthropic message_start /
20
+ message_delta usage, or a JSON body's usage), records every model name a request names (docs/18 §3 row 5: every call of
21
+ the run uses the model under test), and can stop the run at a token budget (`budget_stop`).
22
+
23
+ python scripts/model_gateway.py --upstream https://api.openai.com/v1 --kind openai --log-dir <run log dir>
24
+ writes <log dir>/model_gateway.json {url, port, pid, upstream_host} once it listens, one line per request to
25
+ <log dir>/model_gateway_usage.jsonl (method, path, status, refusal reason, tool types, model, tokens; never a body or
26
+ a header) and the running totals to <log dir>/model_gateway_totals.json. Listens on 127.0.0.1 only. Not part of
27
+ contract_sha256 (an access path, like tool_gateway.py).
28
+ """
29
+ import argparse
30
+ import gzip
31
+ import http.client
32
+ import json
33
+ import os
34
+ import re
35
+ import shutil
36
+ import ssl
37
+ import subprocess
38
+ import sys
39
+ import threading
40
+ import time
41
+ import urllib.parse
42
+ import urllib.request
43
+ import uuid
44
+ import zlib
45
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
46
+
47
+ GATEWAY_FILE = "model_gateway.json"
48
+ USAGE_LOG = "model_gateway_usage.jsonl"
49
+ TOTALS = "model_gateway_totals.json"
50
+ MAX_BODY = 256 * 1024 * 1024
51
+ READ_TIMEOUT_S = 1800
52
+
53
+ # model calls, as paths relative to the upstream base URL (query strings ignored)
54
+ ALLOWED_PATHS = {
55
+ "openai": [("POST", r"responses"), ("POST", r"responses/compact"), ("POST", r"responses/input_tokens"),
56
+ ("GET", r"models(/[^/]+)?")],
57
+ "anthropic": [("POST", r"v1/messages"), ("POST", r"v1/messages/count_tokens"), ("GET", r"v1/models(/[^/]+)?")],
58
+ }
59
+ # DeepSeek Harness uploads request images (--allow-files): same provider, same key, no other use than the next request
60
+ FILE_PATHS = [("POST", r"v1/files"), ("GET", r"v1/files(/[^/]+)?"), ("DELETE", r"v1/files/[^/]+")]
61
+ # what a harness sends by itself at start-up without being a model call: refused, counted apart, not a refusal
62
+ HARNESS_PROBES = {"anthropic": [("HEAD", r"api/hello"), ("GET", r"api/hello")]}
63
+ OPENAI_CLIENT_TOOL_TYPES = {None, "function", "custom", "namespace"}
64
+ PROVIDER_SIDE_FIELDS = {
65
+ "openai": {"prompt", "mcp_servers", "web_search_options", "container", "plugins", "search_parameters",
66
+ "enable_search", "tool_resources"},
67
+ "anthropic": {"mcp_servers", "container"},
68
+ }
69
+ HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding",
70
+ "upgrade", "host", "content-length", "accept-encoding"}
71
+
72
+
73
+ # ------------------------------------------------------------------------------------------------------- checks
74
+ def decode_body(raw, encoding):
75
+ """-> (decoded bytes or None, note). One Content-Encoding at most."""
76
+ enc = [e.strip().lower() for e in (encoding or "").split(",") if e.strip() and e.strip().lower() != "identity"]
77
+ if not enc:
78
+ return raw, None
79
+ if len(enc) > 1:
80
+ return None, "several content encodings"
81
+ e = enc[0]
82
+ try:
83
+ if e == "gzip":
84
+ return gzip.decompress(raw), None
85
+ if e == "deflate":
86
+ return zlib.decompress(raw), None
87
+ if e == "zstd":
88
+ try:
89
+ import zstandard
90
+ return zstandard.ZstdDecompressor().decompressobj().decompress(raw), None
91
+ except ImportError:
92
+ if shutil.which("zstd"):
93
+ p = subprocess.run(["zstd", "-d", "-c"], input=raw, capture_output=True, timeout=60)
94
+ if p.returncode == 0:
95
+ return p.stdout, None
96
+ return None, "zstd body and neither the zstandard module nor the zstd program"
97
+ except Exception as ex:
98
+ return None, f"{e}: {type(ex).__name__}"
99
+ return None, f"unsupported content encoding {e}"
100
+
101
+
102
+ def _tool_types_openai(tools, out):
103
+ for t in tools or []:
104
+ if not isinstance(t, dict):
105
+ out.append(("<not an object>", False))
106
+ continue
107
+ ty = t.get("type")
108
+ out.append((ty, ty in OPENAI_CLIENT_TOOL_TYPES))
109
+ if ty == "namespace":
110
+ _tool_types_openai(t.get("tools"), out)
111
+
112
+
113
+ def declared_tools(kind, body):
114
+ """-> [(type, allowed)] for every tool the request declares (top-level, inside input items, inside namespaces)."""
115
+ out = []
116
+ if kind == "openai":
117
+ _tool_types_openai(body.get("tools"), out)
118
+ for it in body.get("input") or []:
119
+ if isinstance(it, dict) and "tools" in it:
120
+ _tool_types_openai(it.get("tools"), out)
121
+ else:
122
+ for t in body.get("tools") or []:
123
+ ty = t.get("type") if isinstance(t, dict) else "<not an object>"
124
+ out.append((ty, ty in (None, "custom")))
125
+ return out
126
+
127
+
128
+ def remote_fetches(obj):
129
+ """Structured fields that ask the provider to fetch an http(s) address (images, files, documents)."""
130
+ hits = []
131
+
132
+ def walk(o):
133
+ if isinstance(o, dict):
134
+ for k in ("image_url", "file_url", "url"):
135
+ v = o.get(k)
136
+ if isinstance(v, dict):
137
+ v = v.get("url")
138
+ if isinstance(v, str) and re.match(r"https?://", v, re.I) and (
139
+ k != "url" or o.get("type") in ("url", "image_url", "input_image", "input_file")):
140
+ hits.append(k)
141
+ src = o.get("source")
142
+ if isinstance(src, dict) and src.get("type") == "url":
143
+ hits.append("source.url")
144
+ for v in o.values():
145
+ walk(v)
146
+ elif isinstance(o, list):
147
+ for v in o:
148
+ walk(v)
149
+ walk(obj.get("input") if "input" in obj else obj.get("messages"))
150
+ return hits
151
+
152
+
153
+ def check_request(kind, method, rel, headers, raw, allow_files=False):
154
+ """-> (refusal reason or None, info dict). info: tool types, model, probe flag."""
155
+ info = {}
156
+ path = rel.split("?", 1)[0].strip("/")
157
+ if allow_files and any(method == m and re.fullmatch(pat, path) for m, pat in FILE_PATHS):
158
+ info["files"] = True
159
+ return None, info
160
+ for m, pat in HARNESS_PROBES.get(kind, []):
161
+ if method == m and re.fullmatch(pat, path):
162
+ return "harness_probe", info
163
+ if not any(method == m and re.fullmatch(pat, path) for m, pat in ALLOWED_PATHS[kind]):
164
+ return "path_not_allowed", info
165
+ if method != "POST":
166
+ return None, info
167
+ body, note = decode_body(raw, headers.get("Content-Encoding"))
168
+ if body is None:
169
+ info["note"] = note
170
+ return "body_unreadable", info
171
+ try:
172
+ obj = json.loads(body)
173
+ except ValueError:
174
+ return "body_unreadable", info
175
+ if not isinstance(obj, dict):
176
+ return "body_unreadable", info
177
+ info["model"] = obj.get("model")
178
+ tools = declared_tools(kind, obj)
179
+ info["tool_types"] = sorted({str(t) for t, _ in tools})
180
+ info["n_tools"] = len(tools)
181
+ bad = sorted({str(t) for t, ok in tools if not ok})
182
+ if bad:
183
+ info["refused_tool_types"] = bad
184
+ return "server_tool", info
185
+ side = sorted(PROVIDER_SIDE_FIELDS[kind] & set(obj))
186
+ if side:
187
+ info["provider_side_fields"] = side
188
+ return "provider_side_field", info
189
+ rf = remote_fetches(obj)
190
+ if rf:
191
+ info["remote_fetch"] = sorted(set(rf))
192
+ return "remote_fetch", info
193
+ return None, info
194
+
195
+
196
+ # ------------------------------------------------------------------------------------------------------- usage
197
+ def _norm_usage(kind, u):
198
+ if not isinstance(u, dict):
199
+ return {}
200
+ if kind == "openai":
201
+ return dict(input=u.get("input_tokens"), cached_input=(u.get("input_tokens_details") or {}).get("cached_tokens"),
202
+ output=u.get("output_tokens"),
203
+ reasoning=(u.get("output_tokens_details") or {}).get("reasoning_tokens"))
204
+ return dict(input=u.get("input_tokens"), cached_input=u.get("cache_read_input_tokens"),
205
+ cache_write=u.get("cache_creation_input_tokens"), output=u.get("output_tokens"))
206
+
207
+
208
+ class UsageTap:
209
+ """Reads the response as it streams by (SSE lines or one JSON body) and keeps the last usage it reports."""
210
+
211
+ def __init__(self, kind, ctype):
212
+ self.kind, self.sse = kind, "event-stream" in (ctype or "")
213
+ self.buf, self.usage = b"", {}
214
+
215
+ def feed(self, chunk):
216
+ self.buf += chunk
217
+ if not self.sse:
218
+ if len(self.buf) > 64 * 1024 * 1024:
219
+ self.buf = b""
220
+ return
221
+ *lines, self.buf = self.buf.split(b"\n")
222
+ for ln in lines:
223
+ if ln.startswith(b"data:") and b"usage" in ln:
224
+ try:
225
+ ev = json.loads(ln[5:].strip())
226
+ except ValueError:
227
+ continue
228
+ self._event(ev)
229
+
230
+ def _event(self, ev):
231
+ if not isinstance(ev, dict):
232
+ return
233
+ if self.kind == "openai" and ev.get("type") in ("response.completed", "response.incomplete", "response.failed"):
234
+ self.usage = _norm_usage("openai", (ev.get("response") or {}).get("usage"))
235
+ elif self.kind == "anthropic":
236
+ if ev.get("type") == "message_start":
237
+ self.usage = _norm_usage("anthropic", (ev.get("message") or {}).get("usage"))
238
+ elif ev.get("type") == "message_delta" and isinstance(ev.get("usage"), dict):
239
+ u = _norm_usage("anthropic", ev["usage"])
240
+ self.usage.update({k: v for k, v in u.items() if v is not None})
241
+
242
+ def close(self):
243
+ if not self.sse and self.buf:
244
+ try:
245
+ obj = json.loads(self.buf)
246
+ if isinstance(obj, dict) and "usage" in obj:
247
+ self.usage = _norm_usage(self.kind, obj["usage"])
248
+ except ValueError:
249
+ pass
250
+ return self.usage
251
+
252
+
253
+ # ------------------------------------------------------------------------------------------------------- forwarding
254
+ SYSTEM_CA_FILES = ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem")
255
+
256
+
257
+ def ca_file():
258
+ """SSL_CERT_FILE, else certifi's bundle, else the system bundle: the venv's Python may ship without a CA store
259
+ (README: "API 报证书错误")."""
260
+ if os.environ.get("SSL_CERT_FILE"):
261
+ return os.environ["SSL_CERT_FILE"]
262
+ try:
263
+ import certifi
264
+ return certifi.where()
265
+ except ImportError:
266
+ return next((p for p in SYSTEM_CA_FILES if os.path.exists(p)), None)
267
+
268
+
269
+ def upstream_connection(u):
270
+ """HTTP(S) connection to the upstream host, through HTTPS_PROXY / HTTP_PROXY unless NO_PROXY exempts it."""
271
+ host, port = u.hostname, u.port or (443 if u.scheme == "https" else 80)
272
+ proxy = None if urllib.request.proxy_bypass(host) else urllib.request.getproxies().get(u.scheme)
273
+ if u.scheme == "https":
274
+ ctx = ssl.create_default_context(cafile=ca_file())
275
+ if proxy:
276
+ p = urllib.parse.urlsplit(proxy)
277
+ c = http.client.HTTPSConnection(p.hostname, p.port or 80, context=ctx, timeout=READ_TIMEOUT_S)
278
+ c.set_tunnel(host, port)
279
+ return c, False
280
+ return http.client.HTTPSConnection(host, port, context=ctx, timeout=READ_TIMEOUT_S), False
281
+ if proxy:
282
+ p = urllib.parse.urlsplit(proxy)
283
+ return http.client.HTTPConnection(p.hostname, p.port or 80, timeout=READ_TIMEOUT_S), True
284
+ return http.client.HTTPConnection(host, port, timeout=READ_TIMEOUT_S), False
285
+
286
+
287
+ class Totals:
288
+ KEYS = ("requests", "forwarded", "harness_probes", "refused_paths", "refused_server_tools", "refused_fields",
289
+ "refused_remote_fetch", "refused_bodies", "refused_budget", "upstream_errors")
290
+
291
+ def __init__(self, path, budget_in=None, budget_out=None):
292
+ self.path, self.lock = path, threading.Lock()
293
+ self.d = {k: 0 for k in self.KEYS}
294
+ self.d.update(tokens=dict(input=0, cached_input=0, output=0, reasoning=0), models={}, refused_examples=[],
295
+ budget_in=budget_in, budget_out=budget_out, budget_stop=None)
296
+
297
+ def over_budget(self):
298
+ t = self.d["tokens"]
299
+ if self.d["budget_in"] is not None and t["input"] >= self.d["budget_in"]:
300
+ return "input"
301
+ if self.d["budget_out"] is not None and t["output"] >= self.d["budget_out"]:
302
+ return "output"
303
+ return None
304
+
305
+ def add(self, rec):
306
+ with self.lock:
307
+ d = self.d
308
+ d["requests"] += 1
309
+ r = rec.get("refused")
310
+ key = dict(harness_probe="harness_probes", path_not_allowed="refused_paths", server_tool="refused_server_tools",
311
+ provider_side_field="refused_fields", remote_fetch="refused_remote_fetch",
312
+ body_unreadable="refused_bodies", budget_stop="refused_budget").get(r)
313
+ if key:
314
+ d[key] += 1
315
+ if r != "harness_probe" and len(d["refused_examples"]) < 20:
316
+ d["refused_examples"].append({k: rec.get(k) for k in ("method", "path", "refused", "refused_tool_types",
317
+ "provider_side_fields", "note")})
318
+ elif rec.get("status") is None:
319
+ d["upstream_errors"] += 1
320
+ else:
321
+ d["forwarded"] += 1
322
+ if rec.get("model"):
323
+ d["models"][rec["model"]] = d["models"].get(rec["model"], 0) + 1
324
+ for k, v in (rec.get("usage") or {}).items():
325
+ if isinstance(v, int) and k in d["tokens"]:
326
+ d["tokens"][k] += v
327
+ if d["budget_stop"] is None and self.over_budget():
328
+ d["budget_stop"] = dict(which=self.over_budget(), t=time.time())
329
+ tmp = self.path + ".tmp"
330
+ with open(tmp, "w") as f:
331
+ json.dump(d, f, indent=1)
332
+ os.replace(tmp, self.path)
333
+
334
+
335
+ def serve(upstream, kind, log_dir, port=0, budget_in=None, budget_out=None, gateway_file=None, watch_parent=True,
336
+ allow_files=False):
337
+ up = urllib.parse.urlsplit(upstream.rstrip("/"))
338
+ base_path = up.path.rstrip("/")
339
+ ulog = open(os.path.join(log_dir, USAGE_LOG), "a")
340
+ llock = threading.Lock()
341
+ totals = Totals(os.path.join(log_dir, TOTALS), budget_in, budget_out)
342
+ opencode_session = "lffbench-" + uuid.uuid4().hex # one per gateway, i.e. per run
343
+
344
+ def log(rec):
345
+ with llock:
346
+ ulog.write(json.dumps(rec, default=str) + "\n")
347
+ ulog.flush()
348
+ totals.add(rec)
349
+
350
+ class H(BaseHTTPRequestHandler):
351
+ protocol_version = "HTTP/1.1"
352
+
353
+ def log_message(self, *a):
354
+ pass
355
+
356
+ def _refuse(self, code, reason, detail):
357
+ body = json.dumps({"error": {"type": "lff_gateway_refused", "code": reason,
358
+ "message": f"refused by the benchmark's model gateway: {detail}"}}).encode()
359
+ self.send_response(code)
360
+ self.send_header("Content-Type", "application/json")
361
+ self.send_header("Content-Length", str(len(body)))
362
+ self.end_headers()
363
+ if self.command != "HEAD":
364
+ self.wfile.write(body)
365
+
366
+ def _read_body(self):
367
+ if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower():
368
+ out = b""
369
+ while True:
370
+ n = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)
371
+ if n == 0:
372
+ self.rfile.readline()
373
+ return out
374
+ out += self.rfile.read(n)
375
+ self.rfile.readline()
376
+ if len(out) > MAX_BODY:
377
+ raise ValueError("body too large")
378
+ n = int(self.headers.get("Content-Length") or 0)
379
+ if n < 0 or n > MAX_BODY:
380
+ raise ValueError("bad Content-Length")
381
+ return self.rfile.read(n) if n else b""
382
+
383
+ def _handle(self):
384
+ t0 = time.time()
385
+ path = self.path
386
+ rel = path[len(base_path):] if base_path and path.startswith(base_path + "/") else (
387
+ path if not base_path else None)
388
+ rec = dict(t=t0, method=self.command, path=path.split("?", 1)[0][:200])
389
+ try:
390
+ raw = self._read_body()
391
+ except Exception as ex:
392
+ rec.update(refused="body_unreadable", note=str(ex)[:100])
393
+ log(rec)
394
+ return self._refuse(400, "body_unreadable", "unreadable request body")
395
+ if rel is None:
396
+ reason, info = "path_not_allowed", {}
397
+ else:
398
+ reason, info = check_request(kind, self.command, rel, self.headers, raw, allow_files)
399
+ if reason is None and totals.d["budget_stop"] is not None and self.command == "POST":
400
+ reason = "budget_stop"
401
+ rec.update(info, req_bytes=len(raw))
402
+ if reason:
403
+ rec["refused"] = reason
404
+ log(rec)
405
+ detail = dict(harness_probe="not a model call", path_not_allowed="not a model-API call",
406
+ server_tool="tool types run by the provider: " + ",".join(info.get("refused_tool_types", [])),
407
+ provider_side_field="provider-side fields: " + ",".join(info.get("provider_side_fields", [])),
408
+ remote_fetch="the provider would fetch an http(s) address", body_unreadable="unreadable body",
409
+ budget_stop="token budget of this run used up")[reason]
410
+ return self._refuse(404 if reason == "harness_probe" else 403, reason, detail)
411
+ hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
412
+ hdrs["Accept-Encoding"] = "identity"
413
+ if up.hostname == "opencode.ai" and not any(k.lower() == "x-opencode-session" for k in hdrs):
414
+ hdrs["x-opencode-session"] = opencode_session # OpenCode Go refuses requests without one
415
+ if raw or self.command == "POST":
416
+ hdrs["Content-Length"] = str(len(raw))
417
+ conn = None
418
+ try:
419
+ conn, absolute = upstream_connection(up)
420
+ target = f"{up.scheme}://{up.netloc}{path}" if absolute else path
421
+ conn.request(self.command, target, body=raw if raw or self.command == "POST" else None, headers=hdrs)
422
+ resp = conn.getresponse()
423
+ except Exception as ex:
424
+ rec.update(status=None, error=f"{type(ex).__name__}: {ex}"[:300], dur_s=round(time.time() - t0, 2))
425
+ log(rec)
426
+ if conn is not None:
427
+ conn.close()
428
+ body = json.dumps({"error": {"type": "lff_gateway_upstream", "message": "upstream unreachable"}}).encode()
429
+ self.send_response(502)
430
+ self.send_header("Content-Type", "application/json")
431
+ self.send_header("Content-Length", str(len(body)))
432
+ self.end_headers()
433
+ self.wfile.write(body)
434
+ return
435
+ ctype = resp.getheader("Content-Type", "")
436
+ tap = UsageTap(kind, ctype)
437
+ self.send_response(resp.status)
438
+ for k, v in resp.getheaders():
439
+ if k.lower() not in HOP:
440
+ self.send_header(k, v)
441
+ self.send_header("Transfer-Encoding", "chunked")
442
+ self.end_headers()
443
+ n_out, logged = 0, False
444
+ try:
445
+ while True:
446
+ chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(65536)
447
+ if not chunk:
448
+ break
449
+ tap.feed(chunk)
450
+ n_out += len(chunk)
451
+ self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
452
+ self.wfile.flush()
453
+ # record before the last chunk: a client holding the whole response finds its tokens counted
454
+ rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), dur_s=round(time.time() - t0, 2))
455
+ log(rec)
456
+ logged = True
457
+ self.wfile.write(b"0\r\n\r\n")
458
+ self.wfile.flush()
459
+ except (BrokenPipeError, ConnectionResetError):
460
+ rec["client_disconnected"] = True
461
+ finally:
462
+ conn.close()
463
+ if not logged:
464
+ rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(),
465
+ dur_s=round(time.time() - t0, 2))
466
+ log(rec)
467
+
468
+ do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = _handle
469
+
470
+ srv = ThreadingHTTPServer(("127.0.0.1", port), H)
471
+ srv.daemon_threads = True
472
+ url = f"http://127.0.0.1:{srv.server_address[1]}{base_path}"
473
+ gfile = gateway_file or os.path.join(log_dir, GATEWAY_FILE)
474
+ tmp = gfile + ".tmp"
475
+ with open(tmp, "w") as f:
476
+ json.dump(dict(url=url, port=srv.server_address[1], pid=os.getpid(), kind=kind, upstream_host=up.hostname), f)
477
+ os.replace(tmp, gfile)
478
+ if watch_parent:
479
+ ppid = os.getppid()
480
+
481
+ def watch():
482
+ while os.getppid() == ppid:
483
+ time.sleep(2)
484
+ srv.shutdown()
485
+ threading.Thread(target=watch, daemon=True).start()
486
+ try:
487
+ srv.serve_forever(poll_interval=0.5)
488
+ finally:
489
+ srv.server_close()
490
+
491
+
492
+ def start_model_gateway(upstream, kind, log_dir, budget_in=None, budget_out=None, python=None, timeout_s=30,
493
+ allow_files=False):
494
+ """Start a gateway for one run (child of the caller) and wait until it listens. -> (Popen, info dict with url).
495
+ The caller stops it with stop_model_gateway()."""
496
+ gfile = os.path.join(log_dir, GATEWAY_FILE)
497
+ if os.path.exists(gfile):
498
+ os.remove(gfile)
499
+ argv = [python or sys.executable, os.path.abspath(__file__), "--upstream", upstream, "--kind", kind,
500
+ "--log-dir", log_dir]
501
+ if budget_in is not None:
502
+ argv += ["--budget-in", str(int(budget_in))]
503
+ if budget_out is not None:
504
+ argv += ["--budget-out", str(int(budget_out))]
505
+ if allow_files:
506
+ argv.append("--allow-files")
507
+ err = open(os.path.join(log_dir, "model_gateway_stderr.txt"), "ab")
508
+ p = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=err, stderr=err)
509
+ deadline = time.time() + timeout_s
510
+ while time.time() < deadline:
511
+ if p.poll() is not None:
512
+ raise RuntimeError(f"model gateway exited with code {p.returncode}; see {log_dir}/model_gateway_stderr.txt")
513
+ if os.path.exists(gfile):
514
+ return p, json.load(open(gfile))
515
+ time.sleep(0.05)
516
+ stop_model_gateway(p)
517
+ raise RuntimeError(f"model gateway did not start within {timeout_s} s")
518
+
519
+
520
+ def stop_model_gateway(p):
521
+ if p is None or p.poll() is not None:
522
+ return
523
+ p.terminate()
524
+ try:
525
+ p.wait(timeout=10)
526
+ except subprocess.TimeoutExpired:
527
+ p.kill()
528
+ p.wait()
529
+
530
+
531
+ def read_totals(log_dir):
532
+ try:
533
+ return json.load(open(os.path.join(log_dir, TOTALS)))
534
+ except (OSError, ValueError):
535
+ return None
536
+
537
+
538
+ def flagged(totals):
539
+ """Refusals worth a look (EFE: refused_paths / refused_server_tools / refused_bodies), probes excluded."""
540
+ if not totals:
541
+ return []
542
+ return [k for k in ("refused_paths", "refused_server_tools", "refused_fields", "refused_remote_fetch",
543
+ "refused_bodies", "refused_budget") if totals.get(k)]
544
+
545
+
546
+ def main():
547
+ ap = argparse.ArgumentParser()
548
+ ap.add_argument("--upstream", required=True, help="the model API base URL the harness would otherwise call")
549
+ ap.add_argument("--kind", required=True, choices=sorted(ALLOWED_PATHS))
550
+ ap.add_argument("--log-dir", required=True)
551
+ ap.add_argument("--port", type=int, default=0)
552
+ ap.add_argument("--budget-in", type=int, default=None, help="stop forwarding once this many input tokens were used")
553
+ ap.add_argument("--budget-out", type=int, default=None, help="... output tokens (reasoning included)")
554
+ ap.add_argument("--no-watch-parent", action="store_true")
555
+ ap.add_argument("--allow-files", action="store_true", help="also forward the provider's Files API (FILE_PATHS)")
556
+ a = ap.parse_args()
557
+ serve(a.upstream, a.kind, a.log_dir, port=a.port, budget_in=a.budget_in, budget_out=a.budget_out,
558
+ watch_parent=not a.no_watch_parent, allow_files=a.allow_files)
559
+
560
+
561
+ if __name__ == "__main__":
562
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/validate_ladder_fix.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check the Fix-rung texts of the layer-3 feedback ladder (docs/20 §4) on every ladder instance.
2
+
3
+ python scripts/validate_ladder_fix.py [--out results/_ladder/fix_validate.json] [--only TASK]
4
+
5
+ Per instance (task:seed from runs/api/mismatch_20261027/<model>/own.json, both models, deduplicated):
6
+ 1. the sampled instance equals the one logged in the main-table run (session_start inst);
7
+ 2. the scripted oracle succeeds in one attempt; the Fix text is built from the parameters that oracle executed;
8
+ 3. the text has no coordinate-axis labels (strip_axes leaves it unchanged) and no internal instance key names;
9
+ 4. slide_to_target / tablecloth_pull only: the strike / pull the text describes, issued as LA `move_eef`
10
+ commands in the robot-base frame through the same path as robot_server (ToolExecutor move_to with the given
11
+ speed), also succeeds -- this checks that "speed" in the text means what move_eef does. The success window is
12
+ narrow (~+-0.02) and the LA path does not hit it at exactly the oracle's speed (tablecloth 3001: oracle 0.475
13
+ fails as LA commands, 0.48-0.52 succeed), so for these two the text's speed is the middle of the longest run of
14
+ LA successes on a 0.01 grid within +-0.10 of the oracle speed (`la_speed`).
15
+ """
16
+ import argparse
17
+ import importlib
18
+ import json
19
+ import os
20
+ import pkgutil
21
+ import sys
22
+ import time
23
+
24
+ import numpy as np
25
+
26
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
+ sys.path.insert(0, ROOT)
28
+
29
+ from lffbench import arm_specs, envs # noqa: E402
30
+ from lffbench import tasks as task_pkg # noqa: E402
31
+ from lffbench.agent.robot_server import strip_axes # noqa: E402
32
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor # noqa: E402
33
+ from lffbench.task_base import TASKS # noqa: E402
34
+
35
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
36
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
37
+
38
+ OUT = os.path.join(ROOT, "runs", "api", "mismatch_20261027")
39
+ BANNED = ("com_offset", "com_total", "heavy_edge", "heavy_near", "pane_side", "_oracle", " mu ", "inst[")
40
+
41
+
42
+ def instances():
43
+ seen = {}
44
+ for m in ("opus", "sonnet"):
45
+ for key, d in json.load(open(os.path.join(OUT, m, "own.json"))).items():
46
+ src = json.load(open(d + ".source.json"))
47
+ start = json.loads(open(os.path.join(src["log"], "events.jsonl")).readline())
48
+ seen.setdefault(key, dict(task=src["task"], seed=src["seed"], logged=start["inst"], models=[]))
49
+ seen[key]["models"].append(m)
50
+ return seen
51
+
52
+
53
+ def same(a, b):
54
+ if isinstance(a, dict):
55
+ return isinstance(b, dict) and set(a) == set(b) and all(same(a[k], b[k]) for k in a)
56
+ if isinstance(a, (list, tuple)):
57
+ return isinstance(b, (list, tuple)) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
58
+ if isinstance(a, float) or isinstance(b, float):
59
+ return abs(float(a) - float(b)) < 1e-9
60
+ return a == b
61
+
62
+
63
+ def la_move(task, ex, off, **args):
64
+ """one LA move_eef, as robot_server._handle_v2: absolute base-frame target, move then gripper"""
65
+ p = ex.proprio()
66
+ cur = np.asarray(p["eef_pos"], float) - off
67
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
68
+ tgt_w = np.asarray(tgt) + off
69
+ if any(k in args for k in ("x", "y", "z", "yaw")):
70
+ assert np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI), f"target rejected {tgt}"
71
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=float(args.get("yaw", p["eef_yaw_deg"])))
72
+ if args.get("speed") is not None:
73
+ mv["speed"] = float(args["speed"])
74
+ ex.call("move_to", mv)
75
+ if args.get("gripper"):
76
+ ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {})
77
+
78
+
79
+ def la_replay(task, inst, params):
80
+ """the Fix text of slide / tablecloth as LA commands; returns the outcome"""
81
+ task.reset_instance(inst)
82
+ sim = task.env.sim
83
+ off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
84
+ ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",))
85
+ zt = envs.TABLE_Z - off[2] # tabletop height in the base frame
86
+ v = float(params["speed"])
87
+ if task.name == "l5_slide_to_target":
88
+ x0, y0 = (np.asarray(inst["cube_xy"], float) - off[:2])
89
+ la_move(task, ex, off, gripper="close")
90
+ la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.12, yaw=0)
91
+ la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.02)
92
+ la_move(task, ex, off, x=x0 - 0.005, y=y0, z=zt + 0.02, speed=v)
93
+ la_move(task, ex, off, z=zt + 0.10, speed=0.3)
94
+ else:
95
+ from lffbench.tasks.l5_tablecloth_pull import B_HALF, BOARD, H_HALF
96
+ b = envs.obj_pos(task.env, BOARD) - off
97
+ hx, hy, zg = b[0] - B_HALF[0] + H_HALF[0], b[1], zt + 2 * B_HALF[2] + H_HALF[2]
98
+ la_move(task, ex, off, gripper="open")
99
+ la_move(task, ex, off, x=hx, y=hy, z=zg + 0.08, yaw=0)
100
+ la_move(task, ex, off, x=hx, y=hy, z=zg, gripper="close")
101
+ la_move(task, ex, off, x=hx - 0.25, y=hy, z=zg, speed=v, gripper="open")
102
+ la_move(task, ex, off, z=zg + 0.10, speed=0.3)
103
+ return task.outcome(inst)
104
+
105
+
106
+ def la_speed(task, inst, v0):
107
+ """middle of the longest run of LA-replay successes on a 0.01 grid around the oracle speed"""
108
+ from importlib import import_module
109
+ mod = import_module(type(task).__module__)
110
+ grid = [round(v, 2) for v in np.arange(round(v0 - 0.10, 2), round(v0 + 0.10, 2) + 1e-9, 0.01)
111
+ if mod.V_MIN <= v <= mod.V_MAX]
112
+ ok = [bool(la_replay(task, inst, dict(speed=v))["success"]) for v in grid]
113
+ best, run = [], []
114
+ for v, s in zip(grid, ok):
115
+ run = run + [v] if s else []
116
+ if len(run) > len(best):
117
+ best = run
118
+ if not best:
119
+ return None, dict(zip(map(str, grid), ok))
120
+ return best[len(best) // 2], dict(zip(map(str, grid), ok))
121
+
122
+
123
+ def main():
124
+ ap = argparse.ArgumentParser()
125
+ ap.add_argument("--out", default=os.path.join(ROOT, "results", "_ladder", "fix_validate.json"))
126
+ ap.add_argument("--only", default="")
127
+ a = ap.parse_args()
128
+ rows, tasks = [], {}
129
+ for key, it in sorted(instances().items()):
130
+ if a.only and it["task"] != a.only:
131
+ continue
132
+ t0 = time.time()
133
+ task = tasks.setdefault(it["task"], TASKS[it["task"]](cam_res=64))
134
+ inst = task.sample_instance(it["seed"])
135
+ clean = {k: v for k, v in inst.items() if not k.startswith("_")}
136
+ row = dict(key=key, models=it["models"], inst_matches_log=same(json.loads(json.dumps(clean, default=float)),
137
+ it["logged"]))
138
+ hist = task.run_scripted("oracle", inst, k=1)
139
+ params = hist[0]["params"]
140
+ row["oracle_success"] = bool(hist[0]["outcome"]["success"])
141
+ row["oracle_failure"] = hist[0]["outcome"].get("failure")
142
+ row["params"] = json.loads(json.dumps(params, default=float))
143
+ if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"):
144
+ v, sweep = la_speed(task, inst, float(params["speed"]))
145
+ row["oracle_speed"], row["la_sweep"] = float(params["speed"]), sweep
146
+ params = dict(params, speed=v if v is not None else float(params["speed"]))
147
+ row["params"] = json.loads(json.dumps(params, default=float))
148
+ text = arm_specs.fix(it["task"], clean, params)
149
+ row["fix"] = text
150
+ row["no_axis_labels"] = strip_axes(text) == text
151
+ row["no_internal_names"] = not any(b in text for b in BANNED)
152
+ if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"):
153
+ out = la_replay(task, inst, params)
154
+ row["la_replay_success"] = bool(out["success"])
155
+ row["la_replay_failure"] = out.get("failure")
156
+ row["ok"] = bool(row["inst_matches_log"] and row["oracle_success"] and row["no_axis_labels"]
157
+ and row["no_internal_names"] and row.get("la_replay_success", True))
158
+ row["seconds"] = round(time.time() - t0, 1)
159
+ rows.append(row)
160
+ print(f"{'OK ' if row['ok'] else 'BAD'} {key:28s} oracle={row['oracle_success']} "
161
+ f"la={row.get('la_replay_success', '-')} inst={row['inst_matches_log']} ({row['seconds']}s)", flush=True)
162
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
163
+ json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(a.out, "w"), indent=1)
164
+ print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {a.out}")
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code|2.1.267|0399c793ff571d59|claude-opus-5-5|high",
3
+ "fingerprint_sha256": "ba0025718a7a41033ee10a5d00cf9e4fb1c6eff7964f25169f9be4141839cc1f",
4
+ "written": "2026-10-20 02:16:03",
5
+ "summary": {
6
+ "system_chars": 182,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-opus-5-5"
14
+ }
15
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|claude-opus-5-5|high",
3
+ "fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6",
4
+ "written": "2026-10-13 04:12:41",
5
+ "summary": {
6
+ "system_chars": 6048,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-opus-5-5"
14
+ }
15
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|high",
3
+ "fingerprint_sha256": "41fecee198c38459b5fae54c29ebf99c368e60381b3f11418dea02590bba5222",
4
+ "written": "2026-10-20 02:33:15",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6-astra",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|medium",
3
+ "fingerprint_sha256": "ae30000e0db69f6b50aefe798b87406f633e414e071a66fd0f5e85b006d8b0ea",
4
+ "written": "2026-10-20 02:33:27",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "medium",
17
+ "model_in_request": "gpt-6-astra",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-v4.1-flash|high",
3
+ "fingerprint_sha256": "52d7de20832981196514c20e91635e50a2dc6241fa45a1bbfd863d08dc8cc740",
4
+ "written": "2026-10-29 16:15:13",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "deepseek-v4.1-flash",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|high",
3
+ "fingerprint_sha256": "e999df1acbc0c137d1922832262b7b326df0ac8240b9647761158a1c368486c2",
4
+ "written": "2026-10-13 04:13:13",
5
+ "summary": {
6
+ "developer_chars": 23961,
7
+ "top_tools": [
8
+ "collaboration.followup_task",
9
+ "collaboration.interrupt_agent",
10
+ "collaboration.list_agents",
11
+ "collaboration.send_message",
12
+ "collaboration.spawn_agent",
13
+ "collaboration.wait_agent",
14
+ "functions.exec",
15
+ "functions.request_user_input",
16
+ "functions.request_user_input_async",
17
+ "functions.wait"
18
+ ],
19
+ "all_tools": [
20
+ "apply_patch",
21
+ "clock__curr_time",
22
+ "list_mcp_resource_templates",
23
+ "list_mcp_resources",
24
+ "mcp__lff__robot",
25
+ "mcp__lff__shell",
26
+ "mcp__lff__view_images",
27
+ "read_mcp_resource"
28
+ ],
29
+ "effort_in_request": "high",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|medium",
3
+ "fingerprint_sha256": "cdffdbedeb4b110f1f29227ee9459940be8175df4ca71546690ff6db0cccbd6a",
4
+ "written": "2026-10-13 04:13:35",
5
+ "summary": {
6
+ "developer_chars": 23961,
7
+ "top_tools": [
8
+ "collaboration.followup_task",
9
+ "collaboration.interrupt_agent",
10
+ "collaboration.list_agents",
11
+ "collaboration.send_message",
12
+ "collaboration.spawn_agent",
13
+ "collaboration.wait_agent",
14
+ "functions.exec",
15
+ "functions.request_user_input",
16
+ "functions.request_user_input_async",
17
+ "functions.wait"
18
+ ],
19
+ "all_tools": [
20
+ "apply_patch",
21
+ "clock__curr_time",
22
+ "list_mcp_resource_templates",
23
+ "list_mcp_resources",
24
+ "mcp__lff__robot",
25
+ "mcp__lff__shell",
26
+ "mcp__lff__view_images",
27
+ "read_mcp_resource"
28
+ ],
29
+ "effort_in_request": "medium",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/run_agent.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run an agent backend on an LFF-Bench task and log everything.
2
+
3
+ source run_env.sh && export OMP_NUM_THREADS=1
4
+ python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5
5
+ python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --n 20 --k 5
6
+
7
+ Writes runs/agent/<task>/<timestamp>_<backend>_<memory>_<feedback>/ with config.json, events.jsonl
8
+ (every LLM call with tokens + latency, every tool call with its report, every attempt's outcome and
9
+ feedback), images/ (every image the model saw, as the exact JPEG sent) and summary.json (succ@k per run,
10
+ first-success attempt, ΔICL fields, tokens / cost / latency).
11
+ """
12
+ import argparse
13
+ import importlib
14
+ import json
15
+ import os
16
+ import pkgutil
17
+ import sys
18
+ import time
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+
23
+
24
+ def load_tasks():
25
+ import lffbench.tasks as task_pkg
26
+ from lffbench.task_base import TASKS
27
+ for m in pkgutil.iter_modules(task_pkg.__path__):
28
+ try:
29
+ importlib.import_module(f"lffbench.tasks.{m.name}")
30
+ except Exception as e: # other people's task files may be mid-edit; do not let them break this run
31
+ print(f"[warn] could not import lffbench.tasks.{m.name}: {e!r}", file=sys.stderr)
32
+ return TASKS
33
+
34
+
35
+ def parse(argv=None):
36
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
37
+ ap.add_argument("--task", required=True)
38
+ ap.add_argument("--backend", choices=["scripted", "openai", "chat"], default="scripted")
39
+ ap.add_argument("--memory", choices=["none", "full", "last", "mismatched"], default="full")
40
+ ap.add_argument("--feedback", choices=["F0", "F1", "F2"], default="F2")
41
+ ap.add_argument("--n", type=int, default=3, help="number of instances (runs)")
42
+ ap.add_argument("--k", type=int, default=None, help="attempts per run (default: task.max_attempts)")
43
+ ap.add_argument("--seed0", type=int, default=1000, help="first instance seed (dev seeds 1000+, use 5000+ for test)")
44
+ ap.add_argument("--seeds", default=None, help="explicit comma-separated seeds (overrides --seed0/--n)")
45
+ ap.add_argument("--out", default=os.path.join(ROOT, "runs", "agent"))
46
+ ap.add_argument("--tag", default="")
47
+ # harness
48
+ ap.add_argument("--instruction", choices=["direct", "indirect"], default="direct")
49
+ ap.add_argument("--privileged-locate", action="store_true", help="ablation: add locate(object_name)")
50
+ ap.add_argument("--image-res", type=int, default=512)
51
+ ap.add_argument("--keyframe-res", type=int, default=None)
52
+ ap.add_argument("--keyframes", type=int, default=4)
53
+ ap.add_argument("--max-steps", type=int, default=30, help="tool calls per attempt")
54
+ ap.add_argument("--no-auto-obs", action="store_true", help="send images only on get_observation")
55
+ ap.add_argument("--grasp-report", choices=["bool", "name", "none"], default="bool")
56
+ ap.add_argument("--early-stop", choices=["auto", "yes", "no"], default="auto")
57
+ ap.add_argument("--jpeg-quality", type=int, default=90)
58
+ ap.add_argument("--no-save-images", action="store_true")
59
+ # mismatched memory
60
+ ap.add_argument("--donor-run", default=None, help="run dir whose attempts serve as mismatched histories")
61
+ ap.add_argument("--donor-offset", type=int, default=10000,
62
+ help="without --donor-run: donor instance seed = seed + offset, generated with memory=full")
63
+ # scripted
64
+ ap.add_argument("--scripted-policy", choices=["adaptive", "naive", "oracle", "blind"], default="adaptive")
65
+ ap.add_argument("--dry-run-payload", action="store_true",
66
+ help="for non-openai backends: also build the GPT-6 request for every call and log its size")
67
+ ap.add_argument("--dump-requests", type=int, default=0,
68
+ help="write the first N OpenAI requests (images elided) to requests/ for inspection")
69
+ # openai
70
+ ap.add_argument("--model", default="gpt-6-astra")
71
+ ap.add_argument("--effort", default="medium", help="reasoning effort: low|medium|high|xhigh|max")
72
+ ap.add_argument("--reasoning-summary", default="auto", choices=["auto", "concise", "detailed", "none"],
73
+ help="request and log model-returned summaries by default; none disables the request")
74
+ ap.add_argument("--image-detail", default="auto", help="low|high|original|auto")
75
+ ap.add_argument("--max-output-tokens", type=int, default=None)
76
+ ap.add_argument("--service-tier", default=None)
77
+ ap.add_argument("--prompt-cache-retention", default=None, help="in-memory | 24h")
78
+ ap.add_argument("--max-live-images", type=int, default=16)
79
+ ap.add_argument("--extra-body", default=None, help="JSON merged into the request body (new API fields)")
80
+ ap.add_argument("--cache-breakpoints", choices=["none", "history", "history+last"], default="history+last",
81
+ help="explicit prompt_cache_breakpoint markers (set none if a gateway rejects the field)")
82
+ ap.add_argument("--prompt-cache-options", default=None, help='JSON, e.g. {"ttl": "30m"}')
83
+ # chat (OpenAI-compatible local server)
84
+ ap.add_argument("--chat-base-url", default=None)
85
+ ap.add_argument("--chat-model", default="qwen3-vl-8b")
86
+ ap.add_argument("--chat-max-tokens", type=int, default=1024)
87
+ return ap.parse_args(argv)
88
+
89
+
90
+ def redact_request(req):
91
+ """Copy of a request with base64 images replaced by a short marker."""
92
+ def red(o):
93
+ if isinstance(o, dict):
94
+ return {k: (f"<data url, {len(v)} chars>" if k in ("image_url", "url") and isinstance(v, str)
95
+ and v.startswith("data:") else red(v)) for k, v in o.items()}
96
+ if isinstance(o, list):
97
+ return [red(v) for v in o]
98
+ if isinstance(o, str) and len(o) > 2000 and o.startswith("gAAAA"): # encrypted reasoning
99
+ return f"<encrypted, {len(o)} chars>"
100
+ return o
101
+ return red(req)
102
+
103
+
104
+ def build_backend(args):
105
+ from lffbench.agent.backends import make_backend
106
+ if args.backend == "scripted":
107
+ return make_backend("scripted", policy=args.scripted_policy)
108
+ if args.backend == "openai":
109
+ if not os.environ.get("OPENAI_API_KEY"):
110
+ sys.exit("OPENAI_API_KEY is not set (and OPENAI_BASE_URL if you use a proxy / gateway).")
111
+ return make_backend("openai", model=args.model, reasoning_effort=args.effort,
112
+ reasoning_summary=None if args.reasoning_summary == "none" else args.reasoning_summary,
113
+ image_detail=args.image_detail,
114
+ max_output_tokens=args.max_output_tokens, service_tier=args.service_tier,
115
+ prompt_cache_retention=args.prompt_cache_retention, max_live_images=args.max_live_images,
116
+ jpeg_quality=args.jpeg_quality, cache_breakpoints=args.cache_breakpoints,
117
+ prompt_cache_options=json.loads(args.prompt_cache_options) if args.prompt_cache_options
118
+ else None, extra_body=json.loads(args.extra_body) if args.extra_body else None)
119
+ return make_backend("chat", model=args.chat_model, base_url=args.chat_base_url, max_tokens=args.chat_max_tokens,
120
+ max_live_images=min(args.max_live_images, 4), jpeg_quality=args.jpeg_quality)
121
+
122
+
123
+ def main(argv=None):
124
+ args = parse(argv)
125
+ from lffbench.agent.harness import AgentHarness, HarnessConfig, config_dict
126
+ from lffbench.agent.metrics import aggregate
127
+ from lffbench.agent.replay import derange, load_records
128
+ from lffbench.agent.runlog import RunLogger
129
+
130
+ tasks = load_tasks()
131
+ if args.task not in tasks:
132
+ sys.exit(f"unknown task {args.task}; known: {sorted(tasks)}")
133
+ backend = build_backend(args)
134
+ seeds = [int(s) for s in args.seeds.split(",")] if args.seeds else list(range(args.seed0, args.seed0 + args.n))
135
+ cfg = HarnessConfig(memory=args.memory, feedback=args.feedback, k=args.k, image_res=args.image_res,
136
+ keyframe_res=args.keyframe_res, n_keyframes=args.keyframes, auto_obs=not args.no_auto_obs,
137
+ max_steps=args.max_steps, privileged_locate=args.privileged_locate,
138
+ grasp_report=args.grasp_report, instruction=args.instruction, early_stop=args.early_stop,
139
+ jpeg_quality=args.jpeg_quality, save_images=not args.no_save_images,
140
+ model_for_cost=args.model if args.backend == "openai" else "none")
141
+ stamp = time.strftime("%Y%m%d-%H%M%S")
142
+ name = f"{stamp}_{args.backend}{'-' + args.scripted_policy if args.backend == 'scripted' else ''}_{args.memory}_" \
143
+ f"{args.feedback}" + (f"_{args.tag}" if args.tag else "")
144
+ run_dir = os.path.join(args.out, args.task, name)
145
+ os.makedirs(run_dir, exist_ok=True)
146
+ log = RunLogger(run_dir, save_images=cfg.save_images, jpeg_quality=cfg.jpeg_quality)
147
+
148
+ t0 = time.time()
149
+ task = tasks[args.task]()
150
+ print(f"[run_agent] env built in {time.time() - t0:.1f}s -> {run_dir}", flush=True)
151
+ k = args.k or task.max_attempts
152
+
153
+ probe = None
154
+ if args.backend == "openai":
155
+ probe = None
156
+ elif args.dry_run_payload or args.dump_requests:
157
+ from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend
158
+ probe = OpenAIResponsesBackend(model=args.model, reasoning_effort=args.effort, image_detail=args.image_detail,
159
+ max_live_images=args.max_live_images, jpeg_quality=args.jpeg_quality,
160
+ cache_breakpoints=args.cache_breakpoints, client=object())
161
+ if args.dump_requests:
162
+ os.makedirs(os.path.join(run_dir, "requests"), exist_ok=True)
163
+ dumped = [0]
164
+ target = backend if args.backend == "openai" else probe
165
+ orig = target.build_request
166
+
167
+ def build_and_dump(conv, tools, _orig=orig):
168
+ req = _orig(conv, tools)
169
+ if dumped[0] < args.dump_requests:
170
+ dumped[0] += 1
171
+ with open(os.path.join(run_dir, "requests", f"request_{dumped[0]:03d}.json"), "w") as f:
172
+ json.dump(redact_request(req), f, indent=1)
173
+ return req
174
+ target.build_request = build_and_dump
175
+
176
+ log.write_json("config.json", dict(argv=sys.argv, args=vars(args), harness=config_dict(cfg),
177
+ backend=backend.config(), task=dict(name=task.name, level=task.level,
178
+ protocol=task.protocol, k=k,
179
+ capabilities=list(task.capabilities))))
180
+ harness = AgentHarness(task, backend, cfg, log, payload_probe=probe if args.backend != "openai" else None)
181
+
182
+ donors = {}
183
+ if args.memory == "mismatched":
184
+ if args.donor_run:
185
+ pool = load_records(args.donor_run, task=task, feedback=args.feedback)
186
+ m = derange(seeds, pool)
187
+ donors = {s: pool[m[s]] for s in seeds}
188
+ else:
189
+ dlog = RunLogger(os.path.join(run_dir, "donors"), save_images=True, jpeg_quality=cfg.jpeg_quality)
190
+ dcfg = HarnessConfig(**{**config_dict(cfg), "memory": "full", "early_stop": "auto"})
191
+ dh = AgentHarness(task, backend, dcfg, dlog)
192
+ for s in seeds:
193
+ _, recs = dh.run_instance(s + args.donor_offset)
194
+ donors[s] = recs
195
+ print(f"[donor] seed={s + args.donor_offset} first_success="
196
+ f"{next((r.attempt for r in recs if r.success), None)}", flush=True)
197
+ dlog.close()
198
+
199
+ runs = []
200
+ for i, s in enumerate(seeds):
201
+ summ, recs = harness.run_instance(s, donor=donors.get(s))
202
+ runs.append(summ)
203
+ print(f"[{i + 1}/{len(seeds)}] seed={s} first_success={summ['first_success']} attempts={summ['n_attempts']} "
204
+ f"status={summ['status']} llm_calls={summ['n_llm_calls']} tool_calls={summ['n_tool_calls']} "
205
+ f"({time.time() - t0:.0f}s)", flush=True)
206
+ agg = aggregate(runs, k)
207
+ log.write_json("summary.json", dict(task=args.task, backend=backend.config(), memory=args.memory,
208
+ feedback=args.feedback, k=k, seeds=seeds, aggregate=agg,
209
+ runs=[{kk: v for kk, v in r.items() if not kk.startswith("_")} for r in runs]))
210
+ log.close()
211
+ print(json.dumps({kk: agg[kk] for kk in ("n_runs", "n_error_runs", "succ_at", "attempt1_success",
212
+ "mean_first_success", "pass_at_k_iid_analytic", "repeated_action_rate",
213
+ "llm_calls_per_run", "tool_calls_per_run", "sim_wall_per_run_s")},
214
+ default=str))
215
+ print(f"[run_agent] done -> {run_dir}")
216
+ return run_dir, agg, runs
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l3_card_edge.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3 card_edge: a thin card lying flat on a board cannot be pinched; slide it over the board's edge, then grasp it.
2
+
3
+ Category: strategy_switching ("this way of doing it cannot work"), the user's taxonomy L3 example verbatim:
4
+ "卡片贴着桌面捏不起来 -> 先把卡片滑到桌沿,再夹起来".
5
+
6
+ Scene: a wooden board (22 x 26 x 5 cm) on the table with a thin red card (9.0 x 5.6 x 0.2 cm, 10 g) lying flat on it,
7
+ long side roughly along x or along y (+-10 deg); a grey bin (16 x 16 cm inside) stands on the table beside the board.
8
+ The board stands in for the table edge of the user's example: the real table edge is out of reach (near edge 16 cm
9
+ from the robot base, side edges at |y| = 0.6 m) and the harness does not let the grasp point go below the table top.
10
+
11
+ Why the prior fails (measured): a top-down grasp across the card's short side. The Panda fingertips land on the
12
+ board on either side of the card, but when they close on its 2 mm edge the contact flips to "slide over the top" and
13
+ both fingertips ride up over the card and close above it: 0/36 lifts for 1.5 / 2 / 3 mm cards, grasp-point height
14
+ -6..+3 mm, xy jitter 5 mm, yaw jitter 0.1 rad (prototype, 2026-10-08). Retrying with small variations fails the same
15
+ way. (A 4 mm card could be pinched -- the reason the earlier `l3_flat_card_edge` was dropped.)
16
+
17
+ What must be learned from the failure: the card cannot be picked up while it lies flat -> change the strategy: press
18
+ the closed fingertips onto the card and slide it (move_to with the fingertips pressing on it) until part of it hangs
19
+ over the board's edge, then grasp the overhanging part with the fingertips below the card: then the fingers close on
20
+ the card's full edge and it lifts (18/18 for 2.5-3.5 cm of overhang in the prototype). More than half the card's
21
+ length over the edge and it tips off the board.
22
+
23
+ Protocol: cross (reset to the same instance before every attempt), k = 5.
24
+ """
25
+ import numpy as np
26
+
27
+ from .. import envs
28
+ from ..bddl import write_bddl
29
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
30
+ from ..skills import Skills
31
+ from ..task_base import LFFTask, register_task
32
+
33
+ CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm
34
+ CARD_MASS = 0.010
35
+ MU = 0.3 # card and board sliding friction (the fingers' 1.0 / 2.0 win in finger contacts: MuJoCo takes the max)
36
+ BOARD_HALF = (0.11, 0.13, 0.025)
37
+ BOARD_TOP = envs.TABLE_Z + 2 * BOARD_HALF[2]
38
+ BIN_IN = 0.08 # inner half width
39
+ BIN_WALL_H = 0.05
40
+ BIN_GAP = 0.06 # board edge to bin outer wall
41
+ BIN_T = 0.006
42
+ BIN_HALF_OUT = BIN_IN + BIN_T
43
+ TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
44
+ LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
45
+ OVERHANG = 0.03 # scripted target overhang (the grasp works for ~2.5-4.0 cm; the card tips off past ~4.5 cm)
46
+ GRASP_OUT = 0.022 # scripted grasp point: this far beyond the board edge (fingers must clear the edge)
47
+ DRAG_SPEED = 0.08
48
+
49
+
50
+ def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
51
+ g = (f' <geom name="{name}_g0" type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" mass="{CARD_MASS}" '
52
+ f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
53
+ f' <geom type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
54
+ return _wrap(name, g, CARD_HALF[2], float(np.hypot(CARD_HALF[0], CARD_HALF[1])))
55
+
56
+
57
+ def _yaw_of(quat_wxyz):
58
+ w, x, y, z = quat_wxyz
59
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
60
+
61
+
62
+ EDGES = ("forward", "backward", "left", "right") # board edges in robot-centric words (+x, -x, +y, -y)
63
+
64
+
65
+ class CardSkills(Skills):
66
+ """Skills that feed the task's per-step monitor and log every close of the gripper."""
67
+
68
+ def __init__(self, env, task, recorder=None):
69
+ super().__init__(env, recorder=recorder)
70
+ self.task = task
71
+ self.closes = []
72
+
73
+ def _act(self, dpos, drot, grip):
74
+ super()._act(dpos, drot, grip)
75
+ self.task.monitor_step()
76
+
77
+ def set_gripper(self, close, steps=15):
78
+ was_open = self.grip < 0
79
+ before = self.task.close_context() if (close and was_open) else None
80
+ rep = super().set_gripper(close, steps)
81
+ if before is not None:
82
+ before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
83
+ self.closes.append(before)
84
+ return rep
85
+
86
+
87
+ @register_task
88
+ class CardEdge(LFFTask):
89
+ name = "l3_card_edge"
90
+ level = "L3"
91
+ category = "strategy_switching"
92
+ capabilities = ("Perceive", "Reason", "Plan")
93
+ protocol = "cross"
94
+ instruction = "Pick up the thin red card lying on the wooden board and put it into the grey bin."
95
+ instruction_indirect = "Put the flat red rectangle that lies on the wooden block into the grey container."
96
+
97
+ # ------------------------------------------------------------ scene
98
+ def make_bddl(self):
99
+ card = register_generated("LffThinCard", card_xml("lff_thin_card"))
100
+ board = register_generated("LffCardBoard", box_xml("lff_card_board", BOARD_HALF, (0.62, 0.45, 0.27, 1.0),
101
+ friction=(MU, 0.005, 0.0001)), free=False)
102
+ bin_ = register_generated("LffCardBin", bin_xml("lff_card_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
103
+ rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
104
+ objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
105
+ fx = [("board_1", board, "board_region", (-0.11, -0.01, -0.09, 0.01)),
106
+ ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
107
+ return write_bddl(self.name, self.instruction, objs, fx)
108
+
109
+ def __init__(self, cam_res=None):
110
+ super().__init__(cam_res)
111
+ m = self.env.sim.model
112
+ self.board_bid = m.body_name2id(self.env.fixtures_dict["board_1"].root_body)
113
+ self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
114
+ self.inst = None
115
+ self.mon = None
116
+
117
+ def sample_instance(self, seed):
118
+ rng = np.random.default_rng(seed)
119
+ bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
120
+ along = str(rng.choice(["x", "y"]))
121
+ yaw = (0.0 if along == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
122
+ if along == "x": # keep the whole card >= 3 cm (long axis) / 2 cm (short axis) inside the board
123
+ off = [rng.uniform(-0.03, 0.03), rng.uniform(-0.07, 0.07)]
124
+ else:
125
+ off = [rng.uniform(-0.055, 0.055), rng.uniform(-0.05, 0.05)]
126
+ side = 1.0 if rng.random() < 0.5 else -1.0
127
+ bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (BOARD_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
128
+ return dict(seed=int(seed), board_xy=[bx, by], card_xy=[bx + float(off[0]), by + float(off[1])],
129
+ card_yaw=float(yaw), card_along=along, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
130
+
131
+ def apply_instance(self, inst):
132
+ self.inst = inst
133
+ m = self.env.sim.model
134
+ bx, by = inst["board_xy"]
135
+ m.body_pos[self.board_bid] = [bx, by, envs.TABLE_Z + BOARD_HALF[2]]
136
+ m.body_quat[self.board_bid] = [1.0, 0.0, 0.0, 0.0]
137
+ cx, cy = inst["bin_xy"]
138
+ m.body_pos[self.bin_bid] = [cx, cy, envs.TABLE_Z + (BIN_WALL_H + BIN_T) / 2]
139
+ m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
140
+ x, y = inst["card_xy"]
141
+ envs.set_obj_pose(self.env, "card_1", [x, y, BOARD_TOP + CARD_HALF[2] + 0.0003], yaw=inst["card_yaw"])
142
+
143
+ def reset_instance(self, inst, recorder=None):
144
+ self.env.reset()
145
+ self.apply_instance(inst)
146
+ self.env.sim.forward()
147
+ envs.settle(self.env, 15)
148
+ self.sk = CardSkills(self.env, self, recorder=recorder)
149
+ p = self.card_pose()
150
+ self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False)
151
+ return self.sk
152
+
153
+ # ------------------------------------------------------------ geometry
154
+ def card_pose(self):
155
+ p = envs.obj_pos(self.env, "card_1")
156
+ return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
157
+
158
+ def card_corners(self):
159
+ d = self.env.sim.data
160
+ bid = envs.body_id(self.env, "card_1")
161
+ R = d.body_xmat[bid].reshape(3, 3)
162
+ h = np.array(CARD_HALF)
163
+ return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
164
+
165
+ def overhang(self):
166
+ """(how far the card sticks out beyond the board's edges (m, max over its corners), edge word)"""
167
+ c = self.card_corners()[:, :2] - np.asarray(self.inst["board_xy"])
168
+ prot = {"forward": c[:, 0].max() - BOARD_HALF[0], "backward": -c[:, 0].min() - BOARD_HALF[0],
169
+ "left": c[:, 1].max() - BOARD_HALF[1], "right": -c[:, 1].min() - BOARD_HALF[1]}
170
+ e = max(prot, key=prot.get)
171
+ return float(prot[e]), e
172
+
173
+ def on_board(self):
174
+ p = self.card_pose()
175
+ rel = np.abs(p["xy"] - np.asarray(self.inst["board_xy"]))
176
+ return bool(rel[0] <= BOARD_HALF[0] and rel[1] <= BOARD_HALF[1] and abs(p["z"] - BOARD_TOP) < 0.012)
177
+
178
+ def in_bin(self):
179
+ p = self.card_pose()
180
+ rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
181
+ return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < envs.TABLE_Z + BIN_T + BIN_WALL_H)
182
+
183
+ # ------------------------------------------------------------ monitor
184
+ def monitor_step(self):
185
+ mon = self.mon
186
+ if mon is None:
187
+ return
188
+ zmin = float(self.card_corners()[:, 2].min())
189
+ mon["max_lift"] = max(mon["max_lift"], zmin - BOARD_TOP)
190
+ if self.on_board() or abs(self.card_pose()["z"] - BOARD_TOP) < 0.012:
191
+ mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
192
+ if self.card_pose()["z"] < BOARD_TOP - 0.02 and not self.sk.holding("card_1"):
193
+ mon["fell"] = True
194
+
195
+ def close_context(self):
196
+ """Where the gripper is relative to the card and the board just before it closes."""
197
+ sk, p = self.sk, self.card_pose()
198
+ e = sk.eef_pos()
199
+ c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
200
+ rel = e[:2] - p["xy"]
201
+ local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side
202
+ b = e[:2] - np.asarray(self.inst["board_xy"])
203
+ beyond = {"forward": b[0] - BOARD_HALF[0], "backward": -b[0] - BOARD_HALF[0],
204
+ "left": b[1] - BOARD_HALF[1], "right": -b[1] - BOARD_HALF[1]}
205
+ edge = max(beyond, key=beyond.get)
206
+ ov, ov_edge = self.overhang()
207
+ return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
208
+ tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
209
+ beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
210
+ card_on_board=self.on_board(), overhang=round(ov, 4), overhang_edge=ov_edge,
211
+ width_before=round(sk.gripper_width(), 4))
212
+
213
+ # ------------------------------------------------------------ outcome / F2
214
+ def outcome(self, inst):
215
+ envs.settle(self.env, 30)
216
+ sk, mon = self.sk, self.mon
217
+ p = self.card_pose()
218
+ held = bool(sk.holding("card_1"))
219
+ in_bin = self.in_bin() and not held
220
+ success = bool(in_bin)
221
+ moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
222
+ lifted = mon["max_lift"] > 0.02
223
+ tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
224
+ parts, mode = [], "success"
225
+ if success:
226
+ parts.append("The card is in the bin.")
227
+ else:
228
+ rel = p["xy"] - np.asarray(inst["bin_xy"])
229
+ where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
230
+ f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
231
+ if held:
232
+ mode = "held"
233
+ parts.append(f"The card is still held by the gripper, {where}.")
234
+ elif lifted:
235
+ mode = "dropped"
236
+ loc = "on the board" if self.on_board() else ("on the table" if p["z"] < BOARD_TOP - 0.02 else
237
+ "partly on the board")
238
+ parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the board but is not in the "
239
+ f"bin: it lies {loc}, its centre {where}.")
240
+ elif mon["fell"]:
241
+ mode = "fell_off"
242
+ parts.append("The card was never lifted; it fell off the board and lies flat on the table.")
243
+ else:
244
+ mode = "not_lifted"
245
+ parts.append("The card was never lifted; it still lies flat on the board"
246
+ + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
247
+ f"{100 * mon['max_overhang']:.1f} cm beyond the board's edge)" if mon["max_overhang"] > 0.003
248
+ else ")") if moved > 0.005 else "") + ".")
249
+ if not lifted:
250
+ if not tries:
251
+ parts.append("The gripper never closed with its fingertips down at the card.")
252
+ else:
253
+ c = tries[-1]
254
+ n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
255
+ if c["card_on_board"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
256
+ txt = ("when the gripper closed on the card lying flat on the board, its fingertips were on "
257
+ "either side of the card, at board level")
258
+ else:
259
+ if c["beyond_edge"] >= 0.0:
260
+ pos = f"{100 * c['beyond_edge']:.1f} cm beyond the board's {c['beyond_edge_name']} edge"
261
+ else:
262
+ pos = f"over the board, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge"
263
+ txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm "
264
+ f"beyond the board's {c['overhang_edge']} edge and the gripper's centre was {pos}")
265
+ txt += (f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the "
266
+ "fingers closed ")
267
+ txt += ("fully, sliding over the top of the card instead of gripping its edges."
268
+ if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
269
+ ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
270
+ parts.append(n + txt if n else txt[0].upper() + txt[1:])
271
+ out = dict(success=success, mode=mode, held=held, lifted=bool(lifted), max_lift=round(mon["max_lift"], 4),
272
+ max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), fell=bool(mon["fell"]),
273
+ grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
274
+ return out
275
+
276
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
277
+ def _edge_plan(self, inst):
278
+ """the board edge the card is slid to: along its long side; the near (backward) edge for x-cards,
279
+ the closer side edge for y-cards"""
280
+ if inst["card_along"] == "x":
281
+ return "backward"
282
+ return "left" if inst["card_xy"][1] >= inst["board_xy"][1] else "right"
283
+
284
+ def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
285
+ sk = self.sk
286
+ sk.set_gripper(False, steps=8)
287
+ sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
288
+ sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
289
+ sk.set_gripper(True, steps=15)
290
+ sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
291
+ if not sk.holding("card_1"):
292
+ sk.set_gripper(False, steps=8)
293
+ return False
294
+ bx, by = self.inst["bin_xy"]
295
+ hi = envs.TABLE_Z + BIN_WALL_H + 0.12
296
+ sk.move_to([bx, by, hi])
297
+ sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05], speed=0.2)
298
+ sk.set_gripper(False, steps=12)
299
+ sk.move_to([bx, by, hi])
300
+ return True
301
+
302
+ def slide_card(self, delta, press=0.004):
303
+ """closed fingertips pressed on the card's centre, straight move by `delta` (xy), lift"""
304
+ sk, p = self.sk, self.card_pose()
305
+ z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
306
+ sk.set_gripper(True, steps=8)
307
+ sk.move_to([p["xy"][0], p["xy"][1], z + 0.06], yaw=p["yaw"])
308
+ sk.move_to([p["xy"][0], p["xy"][1], z], tol=0.003, max_steps=100)
309
+ e = p["xy"] + np.asarray(delta, float)
310
+ sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
311
+ sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
312
+ sk.hold(5)
313
+
314
+ def execute(self, inst, params):
315
+ p = self.card_pose()
316
+ if params["mode"] == "grasp":
317
+ xy = p["xy"] + np.asarray(params.get("dxy", (0.0, 0.0)))
318
+ self.grasp_and_bin(xy, p["yaw"] + params.get("dyaw", 0.0), BOARD_TOP + params.get("dz", 0.0))
319
+ return
320
+ # edge: slide the card along its long side until `overhang` of it sticks out over the chosen edge
321
+ edge = params.get("edge") or self._edge_plan(inst)
322
+ u = {"forward": (1, 0), "backward": (-1, 0), "left": (0, 1), "right": (0, -1)}[edge]
323
+ u = np.asarray(u, float)
324
+ c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
325
+ long_ax = np.array([c, s]) if abs(np.array([c, s]) @ u) >= abs(np.array([-s, c]) @ u) else np.array([-s, c])
326
+ long_ax = long_ax * np.sign(long_ax @ u)
327
+ b = np.asarray(inst["board_xy"])
328
+ half = BOARD_HALF[0] if edge in ("forward", "backward") else BOARD_HALF[1]
329
+ edge_pos = (b @ u) + half # coordinate of the edge along u
330
+ ext = CARD_HALF[0] * abs(long_ax @ u) + CARD_HALF[1] * abs(np.array([-long_ax[1], long_ax[0]]) @ u)
331
+ for short in (0.01, 0.0): # slide to 1 cm short, look again, slide the rest (one stroke overshoots ~0.7 cm)
332
+ p = self.card_pose()
333
+ need = edge_pos + float(params["overhang"]) - short - (p["xy"] @ u + ext) # travel still needed along u
334
+ if need > 0.003:
335
+ self.slide_card(long_ax * need / max(long_ax @ u, 1e-6))
336
+ q = self.card_pose()
337
+ cu = float(q["xy"] @ u)
338
+ tip_u = cu + CARD_HALF[0] * float(long_ax @ u) # centre of the card's far end, along u
339
+ target_u = min(tip_u - 0.008, edge_pos + GRASP_OUT)
340
+ g = q["xy"] + long_ax * (target_u - cu) / max(float(long_ax @ u), 1e-6)
341
+ self.grasp_and_bin(g, q["yaw"], BOARD_TOP - 0.003)
342
+
343
+ def default_params(self, inst):
344
+ return dict(mode="grasp")
345
+
346
+ def oracle_params(self, inst):
347
+ return dict(mode="edge", overhang=OVERHANG)
348
+
349
+ def blind_params(self, inst, attempt, rng):
350
+ return dict(mode="grasp", dxy=rng.normal(0.0, 0.006, 2).tolist(), dyaw=float(rng.normal(0.0, 0.12)),
351
+ dz=float(rng.uniform(-0.006, 0.003)))
352
+
353
+ def adapt_params(self, inst, history):
354
+ """not lifted while flat on the board (fingers slid over it) -> slide it over the edge first, 3 cm.
355
+ Edge tried: card fell off -> 1 cm less; fingers closed without holding and < 4 cm overhang -> 1 cm more."""
356
+ out, prm = history[-1]["outcome"], history[-1]["params"]
357
+ if prm["mode"] == "grasp":
358
+ return dict(mode="edge", overhang=OVERHANG) if out["mode"] in ("not_lifted", "fell_off") else dict(prm)
359
+ h = float(prm["overhang"])
360
+ if out["mode"] == "fell_off":
361
+ h -= 0.01
362
+ elif out["mode"] == "not_lifted":
363
+ h += 0.01 if out["max_overhang"] < 0.04 else -0.005
364
+ return dict(mode="edge", overhang=float(np.clip(h, 0.025, 0.045)))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l4_diagonal.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L4-B diagonal_fit: put a long bar flat into an open box whose inside is shorter than the bar.
2
+
3
+ Scene: one open box (inner a x b, a slightly longer than b, 3 cm walls) and a long, thin wooden bar
4
+ (L x 1.2 x 1.4 cm) lying on the table in front of it. The bar is 1.2-2.2 cm longer than the box's inside
5
+ length, so it never fits lined up with a side of the box -- it fits only when turned towards the box's
6
+ diagonal, at an angle that depends on a, b and L (36-45 deg off the long side; the fitting window at zero
7
+ centring error is 12-25 deg wide, see task card).
8
+
9
+ Hidden: the exact dimensions (the bar is only 8-17 % longer than the box -- easy to miss at a glance), and
10
+ that a diagonal placement exists. Box and bar are resized per instance by editing geom sizes in sim.model,
11
+ so one env serves every instance (same technique as l4_fit_container).
12
+
13
+ Prior (naive): tidy placement -- line the bar up with the box's long side. It always ends lying across the
14
+ box on the rim (visible). F2 after a failure: where the bar lies, the angle between bar and box, and by how
15
+ much the bar's footprint at that angle is longer than the inside of the box along the box's long / short
16
+ side. A learner can work out the bar length from that and turn the bar towards the diagonal; a second
17
+ failure (angle slightly off) gives the over-length along the other side, which tells it which way to correct.
18
+
19
+ Only move_to / open / close are needed: grasp the bar in the middle, turn the wrist, release above the box.
20
+ """
21
+ import numpy as np
22
+
23
+ from .. import envs
24
+ from ..bddl import write_bddl
25
+ from ..objects import bin_xml, box_xml, register_generated
26
+ from ..skills import _rot_err
27
+ from ..task_base import LFFTask, register_task
28
+
29
+ # bar (local x = long axis); length set per instance
30
+ BAR_W, BAR_H = 0.012, 0.014
31
+ BAR_L_MAX = 0.160
32
+ BAR_RGBA = (0.72, 0.36, 0.14, 1.0)
33
+ # box (local x = long axis of the opening); inner size set per instance
34
+ WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030
35
+ BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height
36
+ RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
37
+ BOX_RGBA = (0.55, 0.62, 0.70, 1.0)
38
+ # sampling ranges (m)
39
+ INNER_A = (0.115, 0.130) # inside length of the box
40
+ A_MINUS_B = (0.004, 0.020) # the box is a little longer than wide
41
+ OVER_LEN = (0.010, 0.020) # bar length minus inside length of the box
42
+ MIN_MARGIN = 0.011 # best-angle clearance (total) the sampler insists on
43
+ MIN_WINDOW_DEG = 8.0 # width of the angle window with >= 6 mm total clearance
44
+ # execution
45
+ Z_GRASP = envs.TABLE_Z + 0.0105 # gripper site; pads span ~0.55-2.25 cm above the table, tips just clear it
46
+ Z_CARRY = envs.TABLE_Z + 0.15
47
+ DROP = 0.010 # bar bottom this far above the rim at release
48
+ PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35)
49
+ PERC_SIGMA = 0.003 # perception noise of the scripted adaptive learner (box inner size, bar width)
50
+
51
+
52
+ MIDPHASE_OFF = True
53
+
54
+
55
+ def disable_midphase(env):
56
+ """Box and bar are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding
57
+ volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered
58
+ size. A box wall moved inwards out of its compiled leaf box is silently skipped by the mid-phase (found on the
59
+ nest_order cups, 2026-10-07: the fingers passed through resized walls). Without the mid-phase MuJoCo tests all
60
+ geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set when resizing)."""
61
+ import mujoco
62
+ m = env.sim.model._model
63
+ m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
64
+
65
+
66
+ def wrap_half(a):
67
+ """angle modulo pi into [-pi/2, pi/2) (bar and box are 180-deg symmetric)"""
68
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
69
+
70
+
71
+ def fold_quarter(a):
72
+ """|angle| between two pi-symmetric axes, in [0, pi/2]"""
73
+ a = abs(wrap_half(a))
74
+ return float(min(a, np.pi - a))
75
+
76
+
77
+ def footprint(L, W, rel):
78
+ """extent of an L x W rectangle turned by rel against the box axes: (along long side, along short side)"""
79
+ c, s = abs(np.cos(rel)), abs(np.sin(rel))
80
+ return L * c + W * s, L * s + W * c
81
+
82
+
83
+ def margins(L, W, a, b, rel):
84
+ e1, e2 = footprint(L, W, rel)
85
+ return a - e1, b - e2
86
+
87
+
88
+ def best_angle(L, W, a, b, n=1801):
89
+ """angle in [0, pi/2] maximising the smaller of the two clearances; returns (angle, clearance, window)"""
90
+ th = np.linspace(0.0, np.pi / 2, n)
91
+ m1, m2 = margins(L, W, a, b, th)
92
+ m = np.minimum(m1, m2)
93
+ i = int(np.argmax(m))
94
+ ok = th[m >= 0.006]
95
+ win = float(np.degrees(ok.max() - ok.min())) if len(ok) else 0.0
96
+ return float(th[i]), float(m[i]), win
97
+
98
+
99
+ def _rect_corners(xy, yaw, half):
100
+ c, s = np.cos(yaw), np.sin(yaw)
101
+ R = np.array([[c, -s], [s, c]])
102
+ pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
103
+ return pts @ R.T + np.asarray(xy)
104
+
105
+
106
+ def _rects_overlap(r1, r2):
107
+ c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
108
+ for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
109
+ ax = np.array([np.cos(yaw), np.sin(yaw)])
110
+ p1, p2 = c1 @ ax, c2 @ ax
111
+ if p1.max() < p2.min() or p2.max() < p1.min():
112
+ return False
113
+ return True
114
+
115
+
116
+ def _rel_dir(dx, dy):
117
+ """robot-centric text for an offset in the world frame (forward = +x, left = +y), ending in 'of' / 'from'"""
118
+ parts = []
119
+ if abs(dx) >= 0.005:
120
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward' if dx > 0 else 'backward'}")
121
+ if abs(dy) >= 0.005:
122
+ parts.append(f"{100 * abs(dy):.1f} cm to the {'left' if dy > 0 else 'right'}")
123
+ return " and ".join(parts) + " of" if parts else "within 0.5 cm of"
124
+
125
+
126
+ def _turn_text(signed_deg):
127
+ """relative orientation of the bar against the box's long side (no absolute angles)"""
128
+ if abs(signed_deg) < 2.0:
129
+ return "lies along the box's long side (within 2 degrees)"
130
+ side = "counterclockwise (towards the left)" if signed_deg > 0 else "clockwise (towards the right)"
131
+ return f"is turned about {abs(signed_deg):.0f} degrees {side}, seen from above, from the box's long side"
132
+
133
+
134
+ @register_task
135
+ class DiagonalFit(LFFTask):
136
+ name = "l4_diagonal_fit"
137
+ level = "L4"
138
+ category = "geometry_inference"
139
+ capabilities = ("Perceive", "Reason")
140
+ instruction = "Put the wooden bar into the box so that it lies flat on the bottom of the box."
141
+ instruction_indirect = "Put the long brown stick into the grey open tray so that it lies flat on the tray's floor."
142
+
143
+ # ------------------------------------------------------------ scene
144
+ def make_bddl(self):
145
+ bar = register_generated("LffDiagBar", box_xml("lff_diag_bar", (BAR_L_MAX / 2, BAR_W / 2, BAR_H / 2),
146
+ BAR_RGBA, density=700))
147
+ box = register_generated("LffDiagBox", bin_xml("lff_diag_box", (0.065, 0.065), WALL_H, wall_t=WALL_T,
148
+ floor_t=FLOOR_T, rgba=BOX_RGBA, density=3000))
149
+ objs = [("bar_1", bar, "bar_region", (0.02, -0.01, 0.04, 0.01)),
150
+ ("box_1", box, "box_region", (-0.19, -0.01, -0.17, 0.01))]
151
+ return write_bddl(self.name, self.instruction, objs)
152
+
153
+ def sample_instance(self, seed):
154
+ rng = np.random.default_rng(seed)
155
+ for _ in range(1000):
156
+ a = float(rng.uniform(*INNER_A))
157
+ b = float(a - rng.uniform(*A_MINUS_B))
158
+ L = float(a + rng.uniform(*OVER_LEN))
159
+ th, m, win = best_angle(L, BAR_W, a, b)
160
+ if m < MIN_MARGIN or win < MIN_WINDOW_DEG:
161
+ continue
162
+ box_xy = [float(rng.uniform(-0.22, -0.13)), float(rng.uniform(-0.10, 0.10))]
163
+ box_yaw = float(rng.uniform(-np.pi / 4, np.pi / 4))
164
+ bar_xy = [float(rng.uniform(-0.01, 0.05)), float(rng.uniform(-0.13, 0.13))]
165
+ bar_yaw = float(rng.uniform(-np.pi / 2, np.pi / 2))
166
+ r_box = (box_xy, box_yaw, (a / 2 + WALL_T + 0.03, b / 2 + WALL_T + 0.03))
167
+ r_bar = (bar_xy, bar_yaw, (L / 2 + 0.01, BAR_W / 2 + 0.03))
168
+ if _rects_overlap(r_box, r_bar):
169
+ continue
170
+ break
171
+ else:
172
+ raise RuntimeError("could not sample an instance")
173
+ prng = np.random.default_rng(seed + 7919)
174
+ perc = [float(a + prng.normal(0, PERC_SIGMA)), float(b + prng.normal(0, PERC_SIGMA)),
175
+ float(BAR_W + prng.normal(0, PERC_SIGMA / 2))]
176
+ return dict(seed=int(seed), inner=[a, b], bar_len=L, bar_xy=bar_xy, bar_yaw=bar_yaw, box_xy=box_xy,
177
+ box_yaw=box_yaw, fit_angle_deg=float(np.degrees(th)), fit_margin_cm=float(100 * m),
178
+ fit_window_deg=win, _perc=perc)
179
+
180
+ def _reshape_box(self, a, b):
181
+ ix, iy, H = a / 2, b / 2, BOX_HALF_H
182
+ parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
183
+ ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
184
+ ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
185
+ ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
186
+ ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
187
+ m = self.env.sim.model
188
+ o = self.env.objects_dict["box_1"]
189
+ for names in (o.contact_geoms, o.visual_geoms):
190
+ assert len(names) == len(parts), names
191
+ for k, n in enumerate(names):
192
+ g = m.geom_name2id(n)
193
+ pos, size = parts[k]
194
+ m.geom_pos[g] = pos
195
+ m.geom_size[g] = size
196
+ m.geom_rbound[g] = float(np.linalg.norm(size))
197
+ m.geom_aabb[g] = [0, 0, 0, *size]
198
+
199
+ def _resize_bar(self, L):
200
+ m = self.env.sim.model
201
+ o = self.env.objects_dict["bar_1"]
202
+ for n in list(o.contact_geoms) + list(o.visual_geoms):
203
+ g = m.geom_name2id(n)
204
+ m.geom_size[g] = [L / 2, BAR_W / 2, BAR_H / 2]
205
+ m.geom_rbound[g] = float(np.linalg.norm(m.geom_size[g]))
206
+ m.geom_aabb[g] = [0, 0, 0, *m.geom_size[g]]
207
+ # keep the mass of the resized bar consistent with its volume (density 700); the geoms live in the
208
+ # child body "object", not in the root body that carries the free joint
209
+ bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])])
210
+ mass = 700.0 * L * BAR_W * BAR_H
211
+ m.body_mass[bid] = mass
212
+ m.body_inertia[bid] = mass / 12.0 * np.array([BAR_W ** 2 + BAR_H ** 2, L ** 2 + BAR_H ** 2,
213
+ L ** 2 + BAR_W ** 2])
214
+
215
+ def apply_instance(self, inst):
216
+ if MIDPHASE_OFF:
217
+ disable_midphase(self.env)
218
+ self._reshape_box(*inst["inner"])
219
+ self._resize_bar(inst["bar_len"])
220
+ envs.set_obj_pose(self.env, "box_1", [*inst["box_xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005],
221
+ yaw=inst["box_yaw"])
222
+ envs.set_obj_pose(self.env, "bar_1", [*inst["bar_xy"], envs.TABLE_Z + BAR_H / 2 + 0.0005],
223
+ yaw=inst["bar_yaw"])
224
+
225
+ # ------------------------------------------------------------ outcome
226
+ def _pose(self, name):
227
+ bid = envs.body_id(self.env, name)
228
+ R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
229
+ return self.env.sim.data.body_xpos[bid].copy(), R
230
+
231
+ def outcome(self, inst):
232
+ envs.settle(self.env, 40)
233
+ a, b = inst["inner"]
234
+ L = inst["bar_len"]
235
+ p, R = self._pose("bar_1")
236
+ ax = R[:, 0]
237
+ bar_yaw = float(np.arctan2(ax[1], ax[0]))
238
+ tilt = float(np.degrees(np.arcsin(min(1.0, abs(ax[2]))))) # long axis vs horizontal
239
+ c, Rb = self._pose("box_1")
240
+ byaw = float(np.arctan2(Rb[1, 0], Rb[0, 0]))
241
+ btilt = float(np.degrees(np.arccos(np.clip(Rb[2, 2], -1, 1))))
242
+ held = bool(self.sk is not None and self.sk.holding("bar_1"))
243
+ rel = fold_quarter(bar_yaw - byaw)
244
+ # bar footprint corners in the box frame
245
+ Rz = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]])
246
+ corners = _rect_corners(p[:2], bar_yaw, (L / 2 * np.cos(np.radians(tilt)), BAR_W / 2))
247
+ loc = (corners - c[:2]) @ Rz.T
248
+ out_x = float(np.max(np.abs(loc[:, 0])) - a / 2)
249
+ out_y = float(np.max(np.abs(loc[:, 1])) - b / 2)
250
+ centre = Rz @ (p[:2] - c[:2])
251
+ floor_top = c[2] - BOX_HALF_H + FLOOR_T
252
+ height = float(envs.obj_min_z(self.env, "bar_1") - floor_top)
253
+ in_opening = out_x <= 0.002 and out_y <= 0.002
254
+ on_floor = height < 0.005 and tilt < 6.0
255
+ success = bool(in_opening and on_floor and not held and btilt < 10.0)
256
+ m_long, m_short = margins(L, BAR_W, a, b, rel)
257
+ fb = dict(rel_deg=round(float(np.degrees(rel)), 1),
258
+ over_long_cm=round(-100 * m_long, 1) if m_long < -0.001 else None,
259
+ over_short_cm=round(-100 * m_short, 1) if m_short < -0.001 else None,
260
+ spare_long_cm=round(100 * max(m_long, 0.0), 1) if m_long >= -0.001 else None,
261
+ spare_short_cm=round(100 * max(m_short, 0.0), 1) if m_short >= -0.001 else None,
262
+ centre_offset_cm=[round(100 * float(centre[0]), 1), round(100 * float(centre[1]), 1)])
263
+ res = dict(success=success, height_cm=round(100 * height, 2), tilt_deg=round(tilt, 1), held=held,
264
+ rel_deg=fb["rel_deg"], bar_xy=[float(p[0]), float(p[1])], feedback=fb)
265
+ signed = float(np.degrees(wrap_half(bar_yaw - byaw)))
266
+ fb["rel_signed_deg"] = round(signed, 1)
267
+ off_w = p[:2] - c[:2] # bar centre relative to the box centre, world axes (only relative values are reported)
268
+ if held:
269
+ res["detail"] = "The bar is still in the gripper."
270
+ res["failure"] = "held"
271
+ return res
272
+ over_box = abs(centre[0]) < a / 2 + WALL_T and abs(centre[1]) < b / 2 + WALL_T
273
+ on_table = envs.obj_min_z(self.env, "bar_1") < envs.TABLE_Z + 0.008 # (floor_top is FLOOR_T above the table)
274
+ if not over_box and on_table:
275
+ res["detail"] = (f"The bar is not in the box: it is lying on the table, its centre "
276
+ f"{_rel_dir(*off_w)} the box's centre.")
277
+ res["failure"] = "table"
278
+ return res
279
+ if success:
280
+ res["detail"] = "The bar is lying flat on the bottom of the box."
281
+ res["failure"] = None
282
+ return res
283
+ if not over_box:
284
+ res["detail"] = (f"The bar is not in the box: it ended partly on the box's rim, "
285
+ f"{100 * (p[2] - envs.TABLE_Z):.1f} cm above the table, its centre "
286
+ f"{_rel_dir(*off_w)} the box's centre.")
287
+ res["failure"] = "off"
288
+ return res
289
+ pose_txt = (f"lying across the top of the box on its rim, {100 * height:.1f} cm above the box floor"
290
+ if tilt < 6.0 else
291
+ f"tilted about {tilt:.0f} degrees, with one end down inside the box and the other end on the rim")
292
+ txt = f"The bar did not go in: it is {pose_txt}. The bar {_turn_text(signed)}."
293
+ parts = []
294
+ if fb["over_long_cm"]:
295
+ parts.append(f"{fb['over_long_cm']:.1f} cm longer than the inside of the box along the box's long side")
296
+ if fb["over_short_cm"]:
297
+ parts.append(f"{fb['over_short_cm']:.1f} cm longer than the inside of the box along the box's short side")
298
+ if parts:
299
+ txt += " At that angle the bar's footprint is " + " and ".join(parts) + "."
300
+ else:
301
+ txt += (f" At that angle the bar's footprint is smaller than the opening (spare {fb['spare_long_cm']:.1f} cm "
302
+ f"along the long side, {fb['spare_short_cm']:.1f} cm along the short side), but it caught on the "
303
+ f"rim (bar centre {_rel_dir(*off_w)} the box's centre).")
304
+ res["detail"] = txt
305
+ res["failure"] = "rim"
306
+ return res
307
+
308
+ # ------------------------------------------------------------ execution
309
+ def execute(self, inst, params):
310
+ """params: rel_yaw (rad) = angle of the bar's long axis against the box's long side at release.
311
+ Optional (tolerance checks): dx / dy release offset of the bar centre from the box centre along the
312
+ box's long / short axis (m); drop = bar bottom above the rim at release (m)."""
313
+ sk, env = self.sk, self.env
314
+ px, py = inst["bar_xy"]
315
+ g0 = wrap_half(inst["bar_yaw"]) # yaw 0 closes the fingers along world y = across a bar lying along x
316
+ sk.set_gripper(False, steps=5)
317
+ sk.move_to([px, py, Z_GRASP + 0.10], yaw=g0)
318
+ sk.move_to([px, py, Z_GRASP], tol=0.003)
319
+ sk.set_gripper(True, steps=15)
320
+ sk.move_to([px, py, Z_CARRY], speed=0.25)
321
+ byaw = inst["box_yaw"]
322
+ c, s = np.cos(byaw), np.sin(byaw)
323
+ dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
324
+ bx, by = inst["box_xy"][0] + c * dx - s * dy, inst["box_xy"][1] + s * dx + c * dy
325
+ sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(byaw + params["rel_yaw"]))
326
+ off = envs.obj_pos(env, "bar_1") - sk.eef_pos()
327
+ drop = params.get("drop", DROP)
328
+ sk.move_to([bx - off[0], by - off[1], RIM_Z + drop + BAR_H / 2 + 0.04 - off[2]], tol=0.003)
329
+ tgt = self._servo_bar([bx, by], RIM_Z + drop)
330
+ sk.grip = -1.0
331
+ self._hold_at(tgt, 12)
332
+ sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
333
+ sk.move_to(list(PARK), yaw=0.0)
334
+
335
+ def _hold_at(self, target, steps):
336
+ sk = self.sk
337
+ R = sk._R()
338
+ for _ in range(steps):
339
+ sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
340
+
341
+ def _servo_bar(self, xy, z_bottom, max_steps=60, tol=0.0015):
342
+ """closed loop on the held bar's centre (scripted policies only)"""
343
+ sk = self.sk
344
+ R = sk._R()
345
+ goal = np.array([xy[0], xy[1], z_bottom + BAR_H / 2])
346
+ tgt = e_prev = sk.eef_pos()
347
+ for i in range(max_steps):
348
+ pb, e = envs.obj_pos(self.env, "bar_1"), sk.eef_pos()
349
+ if i >= 8 and np.linalg.norm(pb - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
350
+ break
351
+ tgt = goal - (pb - e)
352
+ sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
353
+ e_prev = e
354
+ return tgt
355
+
356
+ # ------------------------------------------------------------ scripted policies
357
+ def _signed(self, inst, th):
358
+ """+th or -th, whichever needs the smaller wrist turn from the bar's current orientation"""
359
+ cur = wrap_half(inst["bar_yaw"] - inst["box_yaw"])
360
+ return min((th, -th), key=lambda t: abs(wrap_half(t - cur)))
361
+
362
+ def default_params(self, inst):
363
+ """tidy prior: bar lined up with the box's long side"""
364
+ return dict(rel_yaw=0.0)
365
+
366
+ def oracle_params(self, inst):
367
+ return dict(rel_yaw=self._signed(inst, np.radians(inst["fit_angle_deg"])))
368
+
369
+ def blind_params(self, inst, attempt, rng):
370
+ """no history: the prior again with a little jitter in angle and position"""
371
+ return dict(rel_yaw=float(rng.normal(0.0, np.radians(4.0))), dx=float(rng.normal(0, 0.003)),
372
+ dy=float(rng.normal(0, 0.003)))
373
+
374
+ def adapt_params(self, inst, history):
375
+ """Scripted learner on F2 feedback.
376
+
377
+ Knows the box's inner size and the bar's width only through noisy perception (inst['_perc'],
378
+ sigma = PERC_SIGMA), not the bar's length. Every 'X cm longer than the inside along the long / short side
379
+ at angle d' gives an equation for the bar length L (L cos d + W sin d = a + X, or L sin d + W cos d = b + X);
380
+ 'spare' values give the same with a negative X. It takes the largest length estimate (conservative) and turns
381
+ the bar to the angle with the largest clearance for that length; if the last attempt was already at a
382
+ feasible angle and only missed the centre, it keeps the angle."""
383
+ a, b, W = inst["_perc"]
384
+ Ls = []
385
+ for h in history:
386
+ fb = h["outcome"].get("feedback") or {}
387
+ if h["outcome"].get("failure") != "rim":
388
+ continue
389
+ d = np.radians(fb["rel_deg"])
390
+ c, s = np.cos(d), np.sin(d)
391
+ if c > 0.3:
392
+ x = fb["over_long_cm"] if fb["over_long_cm"] is not None else -fb["spare_long_cm"]
393
+ Ls.append((a + x / 100 - W * s) / c)
394
+ if s > 0.3:
395
+ x = fb["over_short_cm"] if fb["over_short_cm"] is not None else -fb["spare_short_cm"]
396
+ Ls.append((b + x / 100 - W * c) / s)
397
+ L_est = max(Ls) if Ls else a + 0.015
398
+ th, m, _ = best_angle(L_est, W, a, b)
399
+ return dict(rel_yaw=self._signed(inst, th), L_est=float(L_est))
400
+
401
+ def random_yaw_params(self, inst, history, rng):
402
+ """sensitivity variant: a random orientation each retry, no history"""
403
+ return dict(rel_yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
404
+
405
+ EXTRA_KINDS = ("random_yaw",)
406
+
407
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
408
+ if kind not in self.EXTRA_KINDS:
409
+ return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
410
+ k = k or self.max_attempts
411
+ rng = np.random.default_rng(seed)
412
+ history = []
413
+ for a in range(k):
414
+ self.reset_instance(inst)
415
+ params = self.default_params(inst) if a == 0 else self.random_yaw_params(inst, history, rng)
416
+ self.execute(inst, params)
417
+ out = self.outcome(inst)
418
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
419
+ if on_attempt:
420
+ on_attempt(a, params, out)
421
+ if out["success"]:
422
+ break
423
+ return history
424
+
425
+
426
+ # ---------------------------------------------------------------- physical validity checks
427
+ def physics_check(seed0=1000, n=10, out=None):
428
+ """Release angles 0 / 90 deg (must fail), +-best angle (must succeed) and best +- 6 deg (report)."""
429
+ import json
430
+ task = DiagonalFit()
431
+ rows = []
432
+ for seed in range(seed0, seed0 + n):
433
+ inst = task.sample_instance(seed)
434
+ th = np.radians(inst["fit_angle_deg"])
435
+ for name, rel, expect in [("aligned", 0.0, False), ("crossed", np.pi / 2, False), ("best+", th, True),
436
+ ("best-", -th, True), ("best-6", th - np.radians(6), None),
437
+ ("best+6", th + np.radians(6), None)]:
438
+ task.reset_instance(inst)
439
+ task.execute(inst, dict(rel_yaw=float(rel)))
440
+ o = task.outcome(inst)
441
+ rows.append(dict(seed=seed, case=name, rel_deg=float(np.degrees(rel)), success=o["success"], expect=expect,
442
+ failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"],
443
+ inner_cm=[round(100 * v, 2) for v in inst["inner"]], bar_cm=round(100 * inst["bar_len"], 2),
444
+ fit_margin_cm=round(inst["fit_margin_cm"], 2), fit_window_deg=round(inst["fit_window_deg"], 1)))
445
+ flag = "" if expect is None or expect == o["success"] else " <-- MISMATCH"
446
+ print(f"seed {seed} {name:8s} rel={np.degrees(rel):+6.1f} succ={o['success']} h={o['height_cm']} "
447
+ f"tilt={o['tilt_deg']} margin={inst['fit_margin_cm']:.2f}cm win={inst['fit_window_deg']:.1f}{flag}",
448
+ flush=True)
449
+ if out:
450
+ with open(out, "w") as f:
451
+ json.dump(rows, f, indent=1)
452
+ bad = [r for r in rows if r["expect"] is not None and r["expect"] != r["success"]]
453
+ print("total", len(rows), "mismatches", len(bad))
454
+ return rows
455
+
456
+
457
+ def window_check(seed0=1000, n=6, out=None):
458
+ """Release angle swept around the best angle (-16..+16 deg, step 2), bar centred: the physical fitting window
459
+ against the geometric clearance."""
460
+ import json
461
+ task = DiagonalFit()
462
+ rows = []
463
+ for seed in range(seed0, seed0 + n):
464
+ inst = task.sample_instance(seed)
465
+ th = inst["fit_angle_deg"]
466
+ L, (a, b) = inst["bar_len"], inst["inner"]
467
+ for d in range(-16, 17, 2):
468
+ rel = np.radians(th + d)
469
+ task.reset_instance(inst)
470
+ task.execute(inst, dict(rel_yaw=float(rel)))
471
+ o = task.outcome(inst)
472
+ m1, m2 = margins(L, BAR_W, a, b, rel)
473
+ rows.append(dict(seed=seed, d_deg=d, rel_deg=round(th + d, 1), success=o["success"],
474
+ clearance_mm=round(1000 * float(min(m1, m2)), 1)))
475
+ print(f"seed {seed} best={th:.1f} " + " ".join(f"{r['d_deg']:+d}:{'S' if r['success'] else '.'}"
476
+ for r in rows if r["seed"] == seed), flush=True)
477
+ if out:
478
+ with open(out, "w") as f:
479
+ json.dump(rows, f, indent=1)
480
+ return rows
481
+
482
+
483
+ def robustness_check(seed0=1000, n=6, out=None):
484
+ """Execution errors at the best angle: release off-centre along the box's long / short axis, angle off by
485
+ +-4 / +-8 deg, released 3 cm above the rim."""
486
+ import json
487
+ task = DiagonalFit()
488
+ rows = []
489
+ cases = [("best", {}), ("dx4", dict(dx=0.004)), ("dy4", dict(dy=0.004)), ("dx7", dict(dx=0.007)),
490
+ ("dy7", dict(dy=0.007)), ("ang+4", dict(dang=4)), ("ang-4", dict(dang=-4)), ("ang+8", dict(dang=8)),
491
+ ("ang-8", dict(dang=-8)), ("drop3cm", dict(drop=0.03)), ("dx4_ang4_drop3", dict(dx=0.004, dang=4, drop=0.03))]
492
+ for seed in range(seed0, seed0 + n):
493
+ inst = task.sample_instance(seed)
494
+ th = inst["fit_angle_deg"]
495
+ for name, c in cases:
496
+ params = dict(rel_yaw=float(np.radians(th + c.get("dang", 0))))
497
+ params.update({k: v for k, v in c.items() if k != "dang"})
498
+ task.reset_instance(inst)
499
+ task.execute(inst, params)
500
+ o = task.outcome(inst)
501
+ rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"],
502
+ fit_margin_cm=round(inst["fit_margin_cm"], 2)))
503
+ print(f"seed {seed} {name:15s} succ={o['success']} | {o['detail'][:160]}", flush=True)
504
+ if out:
505
+ with open(out, "w") as f:
506
+ json.dump(rows, f, indent=1)
507
+ for name, _ in cases:
508
+ r = [x["success"] for x in rows if x["case"] == name]
509
+ print(f"{name:15s} {sum(r)}/{len(r)}")
510
+ return rows
511
+
512
+
513
+ if __name__ == "__main__":
514
+ # python -m lffbench.tasks.l4_diagonal physics results/l4_diagonal_fit/physics_check.json
515
+ import sys
516
+ # python -m lffbench.tasks.l4_diagonal window results/l4_diagonal_fit/window_check.json
517
+ # python -m lffbench.tasks.l4_diagonal robust results/l4_diagonal_fit/robustness_check.json
518
+ if sys.argv[1] == "physics":
519
+ physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None,
520
+ n=int(sys.argv[3]) if len(sys.argv) > 3 else 10)
521
+ elif sys.argv[1] == "window":
522
+ window_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6)
523
+ elif sys.argv[1] == "robust":
524
+ robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/tasks/l6_count.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip.
2
+
3
+ Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at
4
+ one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in,
5
+ lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past
6
+ the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening).
7
+ Cubes cannot be taken back out.
8
+
9
+ Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction).
10
+
11
+ Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried
12
+ cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The
13
+ number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so
14
+ neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already")
15
+ is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be
16
+ completed in a later segment.
17
+
18
+ Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent
19
+ declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the
20
+ current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it
21
+ also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped
22
+ into the box." after every cube that falls in, and the slip.
23
+
24
+ Scripted references (perception = simulator state, as in l6_swap):
25
+ oracle privileged box count: carries cubes until the box holds N.
26
+ adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the
27
+ drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later
28
+ segments: if F2 says the box holds fewer than N, adds one cube per segment.
29
+ naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame,
30
+ which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1)
31
+ and adds the rest.
32
+ blind memoryless restart (k attempts): at the slip it does not know where it was and starts over
33
+ ("the box must get N cubes"), every later segment again puts N cubes in (repeated steps).
34
+ Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the
35
+ slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube
36
+ per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy).
37
+ """
38
+ import numpy as np
39
+
40
+ from .. import envs
41
+ from ..bddl import write_bddl
42
+ from ..objects import _fmt, _wrap, box_xml, register_generated
43
+ from ..task_base import LFFTask, register_task
44
+
45
+ CUBE_HALF = 0.02
46
+ CUBE_RGBA = (0.95, 0.50, 0.10, 1.0)
47
+ N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view
48
+ LETTERS = "ABCDEFGHIJK"
49
+ CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)]
50
+
51
+ # drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot)
52
+ WALL_T = 0.008
53
+ IN_HX, IN_HY = 0.100, 0.110 # inner half sizes
54
+ LID_Z = 0.095 # underside of the lid above the table
55
+ LID_T = 0.008
56
+ HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side
57
+ HOLE_HY = 0.035
58
+ RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls
59
+ RAMP_T = 0.006
60
+ RAMP_MU = 0.03
61
+ BOX_RGBA = (0.30, 0.20, 0.13, 1.0)
62
+ INNER_RGBA = (0.08, 0.07, 0.06, 1.0)
63
+ HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0])
64
+ OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T
65
+ RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX)
66
+ RAMP_TH = float(np.arctan(RAMP_SLOPE))
67
+ # Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free
68
+ # slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening.
69
+ # Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide
70
+ # past the opening before it is moved; then a second layer on the far row. (x, y, layer)
71
+ _ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)]
72
+ SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)]
73
+ + [(_ROW[0], 0.0, 0), (_ROW[1], 0.0, 0)] + [(_ROW[0], y, 1) for y in (-0.088, 0.088, -0.044, 0.044, 0.0)])
74
+
75
+ BASE_X = -0.66
76
+ REACH = 0.70 # max horizontal distance of a cube from the robot base
77
+ CUBE_REGION = (-0.30, 0.07, -0.28, 0.28)
78
+ CUBE_MIN_DIST = 0.085
79
+ BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid)
80
+ Z_GRASP = envs.TABLE_Z + CUBE_HALF
81
+ Z_CARRY = envs.TABLE_Z + 0.20
82
+ Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid
83
+ PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)]
84
+ LIFTED = 0.05 # slip trigger: cube at least this far above its resting height
85
+ HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there)
86
+ HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp
87
+
88
+
89
+ def hand_box_clear(p, a, box, half=HAND_HALF):
90
+ """Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint."""
91
+ ax = np.array([-np.sin(a), np.cos(a)])
92
+ return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0)))
93
+ for t in np.linspace(-half, half, 9))
94
+
95
+
96
+ def axis_clear(p, a, others, half=HAND_HALF):
97
+ """Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a)."""
98
+ ax = np.array([-np.sin(a), np.cos(a)])
99
+ best = 1.0
100
+ for o in others:
101
+ v = np.asarray(o) - p
102
+ t = float(np.clip(v @ ax, -half, half))
103
+ best = min(best, float(np.linalg.norm(v - t * ax)))
104
+ return best
105
+
106
+
107
+ def drop_box_xml(model_name):
108
+ """Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on)."""
109
+ parts = [] # (pos, half size, rgba, quat or None, friction or None)
110
+ H = LID_Z / 2
111
+ # walls
112
+ parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
113
+ parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
114
+ parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
115
+ parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
116
+ # lid around the opening
117
+ zc = LID_Z + LID_T / 2
118
+ x0, x1 = HOLE_X
119
+ parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip
120
+ parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part
121
+ for s in (-1, 1):
122
+ parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2,
123
+ LID_T / 2), BOX_RGBA))
124
+ # floor (dark) and ramp
125
+ parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA))
126
+ dz = RAMP_Z[0] - RAMP_Z[1]
127
+ th = float(np.arctan2(dz, 2 * IN_HX))
128
+ L = float(np.hypot(dz, 2 * IN_HX)) / 2
129
+ zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th)
130
+ ramp = ((0, 0, zmid), (L, IN_HY - 0.001, RAMP_T / 2), INNER_RGBA, (np.cos(th / 2), 0, np.sin(th / 2), 0), RAMP_MU)
131
+ geoms = []
132
+ for k, p in enumerate(parts + [ramp]):
133
+ pos, half, rgba = p[:3]
134
+ quat = p[3] if len(p) > 3 else None
135
+ mu = p[4] if len(p) > 4 else None
136
+ q = f' quat="{_fmt(quat)}"' if quat is not None else ""
137
+ fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"'
138
+ geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} '
139
+ f'rgba="{_fmt(rgba)}" density="1000"{fr} group="0" />')
140
+ geoms.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} rgba="{_fmt(rgba)}" '
141
+ f'conaffinity="0" contype="0" group="1" />')
142
+ return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY)))
143
+
144
+
145
+ def _wrap_q(a):
146
+ """cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)"""
147
+ return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
148
+
149
+
150
+ @register_task
151
+ class CountIntoBox(LFFTask):
152
+ name = "l6_count_into_box"
153
+ level = "L6"
154
+ category = "procedural_memory"
155
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
156
+ protocol = "within"
157
+ agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55)
158
+ max_attempts = 5
159
+ _TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. "
160
+ "Cubes cannot be taken back out of the box.")
161
+ _TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the "
162
+ "square hole in its top. Blocks cannot be taken back out of the container.")
163
+ instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction)
164
+ instruction_indirect = _TEMPLATE_INDIRECT.format(n="N")
165
+ inject = True
166
+ announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images)
167
+ agent_object_names = ["orange cube (several identical)", "drop box"]
168
+
169
+ WORDS = {3: "three", 4: "four", 5: "five", 6: "six"}
170
+
171
+ def agent_instruction(self, inst, variant="direct"):
172
+ t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE
173
+ return t.format(n=self.WORDS[inst["n_target"]])
174
+
175
+ def __init__(self, cam_res=None):
176
+ super().__init__(cam_res)
177
+ self._mon = False
178
+ orig_step = self.env.step
179
+
180
+ def step(action): # per-control-step monitor: also sees attempts driven by the agent harness
181
+ ret = orig_step(action)
182
+ if self._mon:
183
+ self._monitor()
184
+ return ret
185
+
186
+ self.env.step = step
187
+
188
+ # ------------------------------------------------------------ scene
189
+ def make_bddl(self):
190
+ objs = []
191
+ for i, L in enumerate(LETTERS[:N_CUBES]):
192
+ cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3,
193
+ CUBE_RGBA, density=600))
194
+ gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4)
195
+ objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01)))
196
+ box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False)
197
+ fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))]
198
+ return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx)
199
+
200
+ def _box_body(self):
201
+ return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body)
202
+
203
+ def sample_instance(self, seed):
204
+ rng = np.random.default_rng(seed)
205
+ n = int(rng.choice([4, 5]))
206
+ p = int(rng.integers(1, n)) # cubes already inside when the slip happens
207
+ e = int(rng.integers(0, 2))
208
+ T = n + e + p
209
+ for _ in range(500):
210
+ side = int(rng.choice([-1, 1]))
211
+ box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)])
212
+ P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)])
213
+ P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH]
214
+ P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR]
215
+ cubes = []
216
+ for c in P: # random sequential addition
217
+ if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes):
218
+ cubes.append(c)
219
+ if len(cubes) == T:
220
+ break
221
+ if len(cubes) < T:
222
+ continue
223
+ yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand
224
+ for i in range(T):
225
+ oth = [cubes[j] for j in range(T) if j != i]
226
+ for _ in range(30):
227
+ y = float(rng.uniform(-np.pi / 4, np.pi / 4))
228
+ if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035:
229
+ # |y| <= 45 deg: the grasp needs no large wrist rotation
230
+ yaws.append(y)
231
+ break
232
+ else:
233
+ break
234
+ if len(yaws) == T:
235
+ break
236
+ else:
237
+ raise RuntimeError("could not sample a layout")
238
+ inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(),
239
+ cubes=np.array(cubes).round(4).tolist(),
240
+ yaws=yaws,
241
+ trigger_dist=float(rng.uniform(0.05, 0.09)),
242
+ slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)),
243
+ slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4)))
244
+ # make_video prints task.instruction: keep it in sync with the last sampled instance
245
+ self.instruction = self.agent_instruction(inst, "direct")
246
+ self.instruction_indirect = self.agent_instruction(inst, "indirect")
247
+ return inst
248
+
249
+ def apply_instance(self, inst):
250
+ m = self.env.sim.model
251
+ bid = self._box_body()
252
+ m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z]
253
+ m.body_quat[bid] = [1, 0, 0, 0]
254
+ T = inst["n_cubes"]
255
+ for i, c in enumerate(CUBES):
256
+ if i < T:
257
+ envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001],
258
+ yaw=inst["yaws"][i])
259
+ else:
260
+ envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001])
261
+ self.env.sim.forward()
262
+ self._inst = inst
263
+ self.active = CUBES[:T]
264
+ self.slip = None
265
+ self.events = []
266
+ self._event_cursor = 0
267
+ self._outcome_cursor = 0
268
+ self.in_box = [] # cubes that fell into the box, in order
269
+ self.stored = [] # cubes moved to a storage slot
270
+ self._bad = set() # scripted policies: cubes whose grasp failed
271
+ self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)}
272
+ self._mon = False
273
+
274
+ def reset_instance(self, inst, recorder=None):
275
+ self._mon = False
276
+ sk = super().reset_instance(inst, recorder=recorder)
277
+ self._home = sk.eef_pos()
278
+ self._mon = True
279
+ return sk
280
+
281
+ def go_home(self):
282
+ p = self.sk.eef_pos()
283
+ self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
284
+ self.sk.move_to(self._home)
285
+
286
+ # ------------------------------------------------------------ geometry helpers
287
+ def box_local(self, xyz):
288
+ b = self._inst["box_xy"]
289
+ return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z])
290
+
291
+ def hole_world(self):
292
+ b = self._inst["box_xy"]
293
+ return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]])
294
+
295
+ def inside_box(self, c):
296
+ q = self.box_local(envs.obj_pos(self.env, c))
297
+ return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z)
298
+
299
+ def on_lid(self, c):
300
+ q = self.box_local(envs.obj_pos(self.env, c))
301
+ return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z)
302
+
303
+ def on_table(self, c):
304
+ p = envs.obj_pos(self.env, c)
305
+ return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c))
306
+
307
+ # ------------------------------------------------------------ monitor (every control step)
308
+ def _monitor(self):
309
+ env = self.env
310
+ for c in self.active:
311
+ if c in self.in_box:
312
+ if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02:
313
+ self._store(c)
314
+ continue
315
+ p = envs.obj_pos(env, c)
316
+ if self.inside_box(c):
317
+ self.in_box.append(c)
318
+ if self.announce_drops:
319
+ self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c,
320
+ text="A cube dropped into the box."))
321
+ continue
322
+ if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where
323
+ self.rest_xy[c] = p[:2].copy()
324
+ continue
325
+ if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED
326
+ and len(self.in_box) == self._inst["p"]
327
+ and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"]
328
+ and self.sk.holding(c)):
329
+ self._do_slip(c)
330
+
331
+ def _store(self, c):
332
+ sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)]
333
+ b = self._inst["box_xy"]
334
+ z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003)
335
+ envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z],
336
+ quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0])
337
+ self.stored.append(c)
338
+
339
+ def _do_slip(self, c):
340
+ inst = self._inst
341
+ src = self.rest_xy[c]
342
+ others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
343
+ xy, yaw = src, inst["slip_yaw"]
344
+ found = False
345
+ for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable
346
+ cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])])
347
+ if not all(np.linalg.norm(cand - o) >= 0.07 for o in others):
348
+ continue
349
+ for dy in (0.0, 0.3, -0.3, 0.6, -0.6):
350
+ y = _wrap_q(inst["slip_yaw"] + dy)
351
+ if axis_clear(cand, y, others) >= HAND_CLEAR and \
352
+ hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035:
353
+ xy, yaw, found = cand, y, True
354
+ break
355
+ if found:
356
+ break
357
+ envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw)
358
+ self.sk.grip = -1.0 # the gripper opens
359
+ self.env.sim.forward()
360
+ text = "A cube slipped out of the gripper and fell back onto the table."
361
+ self.slip = dict(obj=c, xy=[float(v) for v in xy], from_xy=[float(v) for v in src], step=int(self.sk.n_steps),
362
+ in_box=len(self.in_box))
363
+ self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text))
364
+
365
+ def drain_events(self):
366
+ ev = self.events[self._event_cursor:]
367
+ self._event_cursor = len(self.events)
368
+ return [e["text"] for e in ev]
369
+
370
+ # ------------------------------------------------------------ outcome
371
+ def outcome(self, inst):
372
+ envs.settle(self.env, 20)
373
+ n_in = len(self.in_box)
374
+ N = inst["n_target"]
375
+ held = [c for c in self.active if self.sk.holding(c)]
376
+ n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box)
377
+ n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box)
378
+ success = bool(n_in == N and not held)
379
+ terminal = bool(n_in > N)
380
+ if success:
381
+ head = f"The box holds exactly {N} cubes."
382
+ elif terminal:
383
+ head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no "
384
+ f"longer be completed.")
385
+ elif n_in == N:
386
+ head = f"The gripper is still holding a cube."
387
+ else:
388
+ head = f"The box holds fewer than {N} cubes."
389
+ state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table"
390
+ if n_lid:
391
+ state += f" and {n_lid} on the box lid"
392
+ state += "."
393
+ # F2 = verdict + currently observable state + the slip of this segment (never the number inside)
394
+ new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"]
395
+ self._outcome_cursor = len(self.events)
396
+ detail = head + " " + state
397
+ if new:
398
+ detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
399
+ return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid,
400
+ held=len(held), slip=self.slip, detail=detail)
401
+
402
+ # ------------------------------------------------------------ motion (scripted policies)
403
+ def _grasp_yaw(self, c):
404
+ """The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive
405
+ the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if
406
+ the hand would hit a neighbour or the box on this one."""
407
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3)
408
+ yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0])))
409
+ p = envs.obj_pos(self.env, c)[:2]
410
+ others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
411
+ box = np.asarray(self._inst["box_xy"])
412
+
413
+ def score(a):
414
+ return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03)
415
+ if score(yaw) >= HAND_CLEAR:
416
+ return yaw
417
+ alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2
418
+ return alt if score(alt) > score(yaw) + 0.02 else yaw
419
+
420
+ def _pick(self, c):
421
+ sk = self.sk
422
+ for _ in range(2):
423
+ p = envs.obj_pos(self.env, c)
424
+ sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12)
425
+ if sk.holding(c):
426
+ return True
427
+ sk.set_gripper(False, steps=8)
428
+ sk.move_to([p[0], p[1], Z_GRASP + 0.12])
429
+ return False
430
+
431
+ def _carry(self, c):
432
+ """Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'."""
433
+ n_ev = len(self.events)
434
+ n_in = len(self.in_box)
435
+ if not self._pick(c):
436
+ self._bad.add(c)
437
+ self.go_home() # un-wind the arm before the next try
438
+ return "no_grasp"
439
+ h = self.hole_world()
440
+ sk = self.sk
441
+ sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening
442
+ if any(e["kind"] == "slip" for e in self.events[n_ev:]):
443
+ return "slipped"
444
+ sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004)
445
+ sk.set_gripper(False, steps=12)
446
+ sk.move_to([h[0], h[1], Z_CARRY])
447
+ sk.hold(10)
448
+ return "in" if len(self.in_box) > n_in else "missed"
449
+
450
+ def _next_cube(self):
451
+ """nearest table cube to the opening (what any policy sees in the current frame)"""
452
+ h = self.hole_world()
453
+ cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))]
454
+ cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp
455
+ if not cands:
456
+ return None
457
+ return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h))
458
+
459
+ def _add(self, k, log, stop_on_slip=False):
460
+ """Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped)."""
461
+ added, slipped = 0, False
462
+ guard = 0
463
+ while added < k and guard < 3 * k + 3:
464
+ guard += 1
465
+ c = self._next_cube()
466
+ if c is None:
467
+ break
468
+ r = self._carry(c)
469
+ log.append(r)
470
+ if r == "in":
471
+ added += 1
472
+ elif r == "slipped":
473
+ slipped = True
474
+ if stop_on_slip:
475
+ break
476
+ return added, slipped
477
+
478
+ # ------------------------------------------------------------ scripted references (within protocol)
479
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
480
+ k = k or self.max_attempts
481
+ rng = np.random.default_rng(seed + 7919)
482
+ self.reset_instance(inst)
483
+ N = inst["n_target"]
484
+ history = []
485
+ for a in range(k):
486
+ log = []
487
+ plan = dict(kind=kind, carries=log)
488
+ if a == 0:
489
+ if kind == "oracle":
490
+ while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count
491
+ c = self._next_cube()
492
+ if c is None:
493
+ break
494
+ log.append(self._carry(c))
495
+ plan["recovery"] = "oracle: privileged box count"
496
+ elif kind in ("adaptive", "skip"):
497
+ added, slipped = self._add(N, log) if kind == "adaptive" else (0, False)
498
+ if kind == "skip": # counts carries, not drops
499
+ n_car = 0
500
+ while n_car < N and len(log) < 3 * N:
501
+ c = self._next_cube()
502
+ if c is None:
503
+ break
504
+ r = self._carry(c)
505
+ log.append(r)
506
+ if r in ("in", "slipped"):
507
+ n_car += 1
508
+ if r == "in":
509
+ added += 1
510
+ plan["recovery"] = "counts carries (the slipped one too)"
511
+ else:
512
+ plan["recovery"] = "own drop count; the slipped carry is not counted"
513
+ else: # memoryless after the slip
514
+ added, slipped = self._add(N, log, stop_on_slip=True)
515
+ if slipped:
516
+ if kind == "naive":
517
+ guess = int(rng.integers(0, N))
518
+ plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}"
519
+ self._add(N - guess, log)
520
+ elif kind == "blind":
521
+ plan["recovery"] = f"memoryless restart: puts {N} cubes in"
522
+ self._add(N, log)
523
+ elif kind == "inc1":
524
+ plan["recovery"] = "stateless: adds one cube per segment"
525
+ self._add(1, log)
526
+ else:
527
+ raise ValueError(kind)
528
+ else:
529
+ plan["recovery"] = "none (no slip)"
530
+ else:
531
+ if kind in ("adaptive", "skip"):
532
+ plan["recovery"] = "memory + F2 'fewer than N': add one cube"
533
+ self._add(1, log)
534
+ elif kind == "blind":
535
+ plan["recovery"] = f"memoryless restart: puts {N} cubes in"
536
+ self._add(N, log)
537
+ elif kind == "inc1":
538
+ plan["recovery"] = "stateless: adds one cube"
539
+ self._add(1, log)
540
+ elif kind == "oracle":
541
+ while len(self.in_box) < N and len(log) < 3 * N + 3:
542
+ c = self._next_cube()
543
+ if c is None:
544
+ break
545
+ log.append(self._carry(c))
546
+ else:
547
+ raise ValueError(kind)
548
+ self.go_home()
549
+ out = self.outcome(inst)
550
+ history.append(dict(attempt=a + 1, params=plan, outcome=out))
551
+ if on_attempt:
552
+ on_attempt(a, plan, out)
553
+ if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
554
+ break
555
+ return history
556
+
557
+ # cross-protocol hooks are not used by this task
558
+ def default_params(self, inst):
559
+ return dict(policy="naive")
560
+
561
+ def oracle_params(self, inst):
562
+ return dict(policy="oracle")
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/fakeapi.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local fake model APIs for offline harness checks (no real model, no cost).
2
+
3
+ Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a
4
+ native harness can be driven turn by turn without a model:
5
+ FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic
6
+ FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider
7
+
8
+ A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get
9
+ the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps:
10
+ ("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read")
11
+ ("text", s) a text block / assistant message
12
+ ("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript
13
+ ("fcall", name, args) Responses: a plain function call
14
+ ("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP
15
+ tools this way: name "robot", namespace "mcp__lff"; measured with 0.163)
16
+
17
+ srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop()
18
+ """
19
+ import itertools
20
+ import json
21
+ import os
22
+ import threading
23
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
24
+
25
+ DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id")
26
+
27
+
28
+ class _Base:
29
+ final_text = "done"
30
+
31
+ def __init__(self, script=None, record_dir=None, port=0):
32
+ self.script = list(script or [])
33
+ self.record_dir = record_dir
34
+ self.port = port
35
+ self.lock = threading.Lock()
36
+ self.counter = itertools.count(1)
37
+ self.requests = [] # (n, path, body)
38
+ if record_dir:
39
+ os.makedirs(record_dir, exist_ok=True)
40
+
41
+ # ------------------------------------------------------------------ plumbing
42
+ def start(self):
43
+ outer = self
44
+
45
+ class H(BaseHTTPRequestHandler):
46
+ protocol_version = "HTTP/1.1"
47
+
48
+ def log_message(self, *a):
49
+ pass
50
+
51
+ def _record(self, body):
52
+ with outer.lock:
53
+ n = next(outer.counter)
54
+ outer.requests.append((n, self.path, body))
55
+ if outer.record_dir:
56
+ with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f:
57
+ json.dump(dict(method=self.command, path=self.path, body=body,
58
+ headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}),
59
+ f, indent=1, ensure_ascii=False)
60
+ return n
61
+
62
+ def do_GET(self):
63
+ self._record(None)
64
+ self._send(404, b"{}", "application/json")
65
+
66
+ def do_HEAD(self):
67
+ self._send(404, b"", "application/json")
68
+
69
+ def do_POST(self):
70
+ raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0))
71
+ try:
72
+ body = json.loads(raw)
73
+ except ValueError:
74
+ body = raw[:4000].decode("utf-8", "replace")
75
+ n = self._record(body)
76
+ outer.handle(self, n, body)
77
+
78
+ def _send(self, code, data, ctype):
79
+ self.send_response(code)
80
+ self.send_header("content-type", ctype)
81
+ self.send_header("content-length", str(len(data)))
82
+ self.end_headers()
83
+ self.wfile.write(data)
84
+
85
+ self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H)
86
+ self.httpd.daemon_threads = True
87
+ self.port = self.httpd.server_address[1]
88
+ threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
89
+ return self
90
+
91
+ def stop(self):
92
+ self.httpd.shutdown()
93
+ self.httpd.server_close()
94
+
95
+ def turn(self, i):
96
+ return self.script[i] if i < len(self.script) else [("text", self.final_text)]
97
+
98
+ @staticmethod
99
+ def send_sse(h, events):
100
+ data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events)
101
+ h._send(200, data, "text/event-stream")
102
+
103
+
104
+ class FakeAnthropic(_Base):
105
+ @property
106
+ def base_url(self):
107
+ return f"http://127.0.0.1:{self.port}"
108
+
109
+ def handle(self, h, n, body):
110
+ if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict):
111
+ h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json")
112
+ return
113
+ msgs = body.get("messages", [])
114
+ i = sum(1 for m in msgs if m.get("role") == "assistant")
115
+ steps = self.turn(i)
116
+ blocks = []
117
+ for j, st in enumerate(steps):
118
+ if st[0] == "tool":
119
+ blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2]))
120
+ else:
121
+ blocks.append(dict(type="text", text=st[1]))
122
+ stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn"
123
+ model = body.get("model", "fake")
124
+ evs = [("message_start", dict(type="message_start", message=dict(
125
+ id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None,
126
+ stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))]
127
+ for k, b in enumerate(blocks):
128
+ if b["type"] == "tool_use":
129
+ evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict(
130
+ type="tool_use", id=b["id"], name=b["name"], input={}))))
131
+ evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict(
132
+ type="input_json_delta", partial_json=json.dumps(b["input"])))))
133
+ else:
134
+ evs.append(("content_block_start", dict(type="content_block_start", index=k,
135
+ content_block=dict(type="text", text=""))))
136
+ evs.append(("content_block_delta", dict(type="content_block_delta", index=k,
137
+ delta=dict(type="text_delta", text=b["text"]))))
138
+ evs.append(("content_block_stop", dict(type="content_block_stop", index=k)))
139
+ evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None),
140
+ usage=dict(output_tokens=5))))
141
+ evs.append(("message_stop", dict(type="message_stop")))
142
+ self.send_sse(h, evs)
143
+
144
+ def message_requests(self):
145
+ return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages")
146
+ and "count_tokens" not in p]
147
+
148
+
149
+ class FakeResponses(_Base):
150
+ @property
151
+ def base_url(self):
152
+ return f"http://127.0.0.1:{self.port}/v1"
153
+
154
+ def handle(self, h, n, body):
155
+ if not isinstance(body, dict) or "input" not in body:
156
+ h._send(404, b"{}", "application/json")
157
+ return
158
+ items = body.get("input") or []
159
+ i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in
160
+ ("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message"
161
+ and it.get("role") == "assistant"))
162
+ steps = self.turn(i)
163
+ out = []
164
+ for j, st in enumerate(steps):
165
+ if st[0] == "exec":
166
+ out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
167
+ name="exec", status="completed", input=st[1]))
168
+ elif st[0] == "fcall":
169
+ out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
170
+ name=st[1], arguments=json.dumps(st[2]), status="completed"))
171
+ elif st[0] == "nscall":
172
+ out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
173
+ namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed"))
174
+ else:
175
+ out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed",
176
+ content=[dict(type="output_text", text=st[1], annotations=[])]))
177
+ rid = f"resp_fake_{n}"
178
+ evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))]
179
+ for k, it in enumerate(out):
180
+ evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it)))
181
+ evs.append(("response.completed", dict(type="response.completed", response=dict(
182
+ id=rid, status="completed", output=out, usage=dict(
183
+ input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3,
184
+ output_tokens_details=dict(reasoning_tokens=0), total_tokens=103)))))
185
+ self.send_sse(h, evs)
186
+
187
+ def model_requests(self):
188
+ return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b]
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-flash|high",
3
+ "fingerprint_sha256": "189cde183af8b300854d48b4f8952a6ebdf53462343e87c0062ad4c761943d9c",
4
+ "written": "2026-10-30 15:54:07",
5
+ "summary": {
6
+ "system_chars": 6047,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "deepseek-flash"
14
+ }
15
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "sensenova_codex-chatgpt-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9",
4
+ "written": "2026-10-26 07:08:06",
5
+ "summary": {
6
+ "report": "/mnt/cpfs/workspace/agentic-robotics/reports/robot_harness_subscription_resume_20261026/selfcheck_verified/selfcheck.json",
7
+ "checks": 10,
8
+ "framework": {
9
+ "commit": "b513a1c7289ab11eb844856588b64c378705c405",
10
+ "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823",
11
+ "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350",
12
+ "untracked": [
13
+ "lff_integration/__init__.py",
14
+ "lff_integration/run.py"
15
+ ]
16
+ }
17
+ }
18
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/real/executor.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor.
2
+
3
+ robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and
4
+ call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver
5
+ (lffbench/real/protocol.py) instead of the simulator.
6
+
7
+ Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and
8
+ reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the
9
+ ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation.
10
+ """
11
+ import math
12
+ import time
13
+
14
+ import numpy as np
15
+
16
+ from ..agent.images import ImageRef
17
+ from ..agent.tools import ToolResult, parse_args
18
+ from .protocol import CAMERAS, DriverError, square_resize, state_problems
19
+
20
+ SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful
21
+
22
+
23
+ def _r(v, nd=4):
24
+ return [round(float(x), nd) for x in v]
25
+
26
+
27
+ class RealToolExecutor:
28
+ def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS):
29
+ self.driver, self.info = driver, info
30
+ self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
31
+ self.image_res = int(image_res)
32
+ self.cams = tuple(cams)
33
+ self.n_joints = int(info["n_joints"])
34
+ self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"])
35
+ self.max_speed = float(info["max_speed"])
36
+ self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver
37
+ self.n_calls = 0
38
+ self._state = None
39
+ self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open)
40
+ self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents
41
+ self.refresh()
42
+ self.yaw_cmd = float(self._state["eef_yaw_deg"])
43
+
44
+ # ------------------------------------------------------------------ state
45
+ def _set_state(self, st):
46
+ prob = state_problems(st, self.n_joints)
47
+ if prob:
48
+ raise DriverError("driver state: " + "; ".join(prob))
49
+ self._state = st
50
+
51
+ def refresh(self):
52
+ self._set_state(self.driver.state())
53
+
54
+ def true_eef(self):
55
+ return np.asarray(self._state["eef_pos"], float)
56
+
57
+ def believed_eef(self):
58
+ return self.true_eef() - self.bias
59
+
60
+ def proprio(self):
61
+ st = self._state
62
+ return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1),
63
+ gripper="closed" if self.grip_closed else "open",
64
+ gripper_width_m=round(float(st["gripper_width_m"]), 4))
65
+
66
+ def joints(self):
67
+ """Joint angles as the robot's encoders would report them under the hidden calibration error."""
68
+ if not np.any(self.bias):
69
+ return [float(v) for v in self._state["joint_pos_rad"]]
70
+ key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"]))
71
+ if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command)
72
+ self._ik_key = key
73
+ self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])]
74
+ return list(self._ik_val)
75
+
76
+ def observe(self, label=""):
77
+ frames, st = self.driver.observe()
78
+ self._set_state(st)
79
+ return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip())
80
+ for c in self.cams]
81
+
82
+ # ------------------------------------------------------------------ helpers
83
+ def wrap_yaw(self, yaw):
84
+ """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to
85
+ the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit)."""
86
+ cands = [yaw + 180.0 * k for k in range(-3, 4)]
87
+ ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands
88
+ return float(min(ok, key=lambda c: abs(c - self.yaw_cmd)))
89
+
90
+ # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call)
91
+ def call(self, name, raw_args):
92
+ t0 = time.time()
93
+ self.n_calls += 1
94
+ args = parse_args(raw_args)
95
+ fn = getattr(self, f"_t_{name}", None)
96
+ if fn is None:
97
+ return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
98
+ res = fn(**args)
99
+ res.args, res.wall_s = args, time.time() - t0
100
+ return res
101
+
102
+ def _report(self, name, extra=None):
103
+ rep = dict(ok=True, tool=name)
104
+ rep.update(extra or {})
105
+ rep.update(self.proprio())
106
+ return rep
107
+
108
+ def _t_move_to(self, x, y, z, yaw, speed=None):
109
+ tgt = np.array([x, y, z], float)
110
+ if not np.all(np.isfinite(tgt)):
111
+ return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates"))
112
+ spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed))
113
+ yaw_used = self.wrap_yaw(float(yaw))
114
+ cmd = tgt + self.bias # the hidden calibration error acts on every commanded position
115
+ rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd)
116
+ self.motion_s += float(rep.get("motion_s") or 0.0)
117
+ self._set_state(rep["state"])
118
+ if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution)
119
+ return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; "
120
+ "the arm did not move", driver_error=rep.get("error", "")))
121
+ self.yaw_cmd = yaw_used
122
+ reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02)
123
+ return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached,
124
+ yaw_used_deg=round(yaw_used, 1))))
125
+
126
+ def _gripper(self, close):
127
+ rep = self.driver.gripper(close)
128
+ self.grip_closed = bool(close)
129
+ self.motion_s += float(rep.get("motion_s") or 0.0)
130
+ self._set_state(rep["state"])
131
+ name = "close_gripper" if close else "open_gripper"
132
+ return ToolResult(name, {}, True, self._report(name))
133
+
134
+ def _t_open_gripper(self):
135
+ return self._gripper(False)
136
+
137
+ def _t_close_gripper(self):
138
+ return self._gripper(True)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l1_height.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L1-B height_bias: pick up a thin tile from the top of a wooden block and put it on the plate, with an arm whose
2
+ vertical calibration is off.
3
+
4
+ Category system_identification (level L1, action fine-tuning): the method (top-down pick across the tile's short
5
+ side with the fingertips just above the block's top, carry, release above the plate) and the scene understanding
6
+ are right; only the robot's own vertical execution is off.
7
+
8
+ Hidden variable: a fixed vertical calibration offset dz ~ U[2.0, 3.5] cm (always upward), added to every
9
+ commanded gripper position (`Skills(bias=(0, 0, dz))`): the gripper stops dz higher than commanded. The agent never
10
+ sees dz; positions reported back to it are in the commanded frame (`HeightSkills.reported_eef_pos`, and the agent
11
+ harness reports eef - bias), so the robot "believes" it reached the commanded height.
12
+
13
+ Why the prior fails: the tile is 1.0 cm thick. Sent to the right height (fingertips just above the block's top), the
14
+ fingertips actually stop 2-3.5 cm higher, i.e. 1.1-2.6 cm above the tile's top face, and the jaws close in the air
15
+ above it (measured tolerance, 6 layouts: upward errors up to 0.4 cm still grasp, >= 0.7 cm never do, i.e. the fingers
16
+ must overlap the tile by ~4 mm). dz >= 2 cm also defeats a prior that aims lower: even with the grasp point commanded
17
+ level with the block's top (fingertips ~1 cm into the block), the fingertips end up >= 1.05 cm above the block's
18
+ top, i.e. not below the tile's top face -> missed.
19
+ Visible in the agentview image (gap between the closed fingers and the tile) and in the wrist image (fingers closed
20
+ over the tile).
21
+ A downward error would not fail (the fingertips land on the block's top and the compliant OSC still closes on the
22
+ tile; measured for -1 and -2 cm), so the offset is upward only.
23
+
24
+ Why a raised block: the agent's move_to clips commanded targets to >= table + 0.5 cm. With the tile on the table,
25
+ compensating a 2-3.5 cm upward offset would need commands below the table top, which the interface refuses; on a
26
+ 6-10 cm block the compensated commands stay well inside the workspace.
27
+
28
+ What has to be learned: F2 reports how far above the tile's top face the grasp point and the fingertips were when the
29
+ jaws closed. Compared with where the policy meant to put them, that is dz itself, so after one failure dz can be
30
+ estimated and subtracted from every commanded height (pick and place alike).
31
+ """
32
+ import re
33
+
34
+ import numpy as np
35
+
36
+ from .. import envs
37
+ from ..bddl import write_bddl
38
+ from ..objects import box_xml, register_generated
39
+ from ..skills import Skills
40
+ from ..task_base import LFFTask, register_task
41
+
42
+ TILE, STAND, PLATE = "tile_1", "stand_1", "plate_1"
43
+ DISTRACTORS = ("butter_1", "chocolate_pudding_1")
44
+ FREE_OBJECTS = (TILE, PLATE) + DISTRACTORS
45
+ NAMES = {TILE: "red tile", STAND: "wooden block", PLATE: "plate", "butter_1": "butter",
46
+ "chocolate_pudding_1": "chocolate pudding"}
47
+ DESCR = {TILE: "thin red slab", STAND: "large wooden pedestal", PLATE: "round white dish", "butter_1": "small orange box",
48
+ "chocolate_pudding_1": "brown box"}
49
+
50
+ TILE_HALF = (0.040, 0.0225, 0.005) # 8.0 x 4.5 x 1.0 cm (long side along the tile's x axis)
51
+ TILE_T = 2 * TILE_HALF[2]
52
+ STAND_HALF_XY = (0.075, 0.085) # 15 x 17 cm top
53
+ STAND_H_RANGE = (0.06, 0.10)
54
+ MASS = {TILE: 0.072, "butter_1": 0.250, "chocolate_pudding_1": 0.200, PLATE: 0.350}
55
+
56
+ FINGER_BELOW_SITE = 0.0095 # lowest point of the finger collision meshes below the grasp site (measured 0.95 cm)
57
+ SITE_ABOVE_SURFACE = 0.0105 # scripted grasp height: grasp point 1.05 cm above the block top (fingertips ~1 mm above)
58
+ CARRY_ABOVE = 0.12 # carry height above the block top
59
+ RELEASE_GAP = 0.012 # tile bottom this far above the plate's rim at release
60
+ PLATE_R_OK = 0.040 # success: tile centre within this horizontal distance of the plate centre
61
+ DZ_MIN, DZ_MAX = 0.020, 0.035
62
+ TILE_YAW_MAX = np.deg2rad(40)
63
+ HOME_XY = np.array([-0.21, 0.0])
64
+
65
+
66
+ def _seg_dist(p, a, b):
67
+ ab = b - a
68
+ u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
69
+ return float(np.linalg.norm(a + u * ab - p))
70
+
71
+
72
+ def _q(axis, a):
73
+ h = a / 2
74
+ return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
75
+
76
+
77
+ def _qmul(a, b):
78
+ w1, x1, y1, z1 = a
79
+ w2, x2, y2, z2 = b
80
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
81
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
82
+
83
+
84
+ def dir_words(dx, dy):
85
+ """Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
86
+ parts = []
87
+ if abs(dy) >= 0.0005:
88
+ parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
89
+ if abs(dx) >= 0.0005:
90
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
91
+ return " and ".join(parts) if parts else "exactly at the position"
92
+
93
+
94
+ def vert_words(h, what):
95
+ if h >= 0.0005:
96
+ return f"{100 * h:.1f} cm above {what}"
97
+ if h <= -0.0005:
98
+ return f"{100 * -h:.1f} cm below {what}"
99
+ return f"level with {what}"
100
+
101
+
102
+ class HeightSkills(Skills):
103
+ """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent)."""
104
+
105
+ def __init__(self, env, bias=None, recorder=None, stand_geoms=()):
106
+ super().__init__(env, bias=bias, recorder=recorder)
107
+ self.events = []
108
+ m = env.sim.model
109
+ self._finger_geoms = {
110
+ side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
111
+ for side in ("left_finger", "right_finger")}
112
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
113
+ self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
114
+ self._obj_geoms[STAND] = list(stand_geoms)
115
+ self.tile_z0 = float(envs.obj_pos(env, TILE)[2])
116
+ self.tile_zmax = self.tile_z0
117
+ self.tile_ref = envs.obj_pos(env, TILE) # tile position before the fingers last touched it
118
+ self.tile_ref_yaw = self.tile_yaw()
119
+
120
+ def reported_eef_pos(self):
121
+ """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything shown to
122
+ the agent must use this, never eef_pos(), which is the true position and reveals the bias."""
123
+ return self.eef_pos() - self.bias
124
+
125
+ def move_to(self, target, *args, **kwargs):
126
+ rep = super().move_to(target, *args, **kwargs)
127
+ rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist()
128
+ return rep
129
+
130
+ def touching(self):
131
+ return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
132
+
133
+ def holding_tile(self):
134
+ """Both fingers in contact with the tile (robosuite's _check_grasp needs the finger *pads*, which miss a
135
+ 1 cm tile when it is gripped low on the finger meshes)."""
136
+ tg = self._obj_geoms[TILE]
137
+ return all(envs.contacts_between(self.env, gs, tg) for gs in self._finger_geoms.values())
138
+
139
+ def holding(self, obj_name):
140
+ """The agent harness reports `holding_object` through this; use the finger-contact test for the tile so a
141
+ tile gripped low on the fingers is not reported as dropped."""
142
+ if obj_name == TILE:
143
+ return self.holding_tile()
144
+ return super().holding(obj_name)
145
+
146
+ def tile_yaw(self):
147
+ xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
148
+ return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
149
+
150
+ def finger_min_z(self):
151
+ return float(self.eef_pos()[2] - FINGER_BELOW_SITE)
152
+
153
+ def _act(self, dpos, drot, grip):
154
+ super()._act(dpos, drot, grip)
155
+ self.tile_zmax = max(self.tile_zmax, float(envs.obj_pos(self.env, TILE)[2]))
156
+ if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[TILE]):
157
+ self.tile_ref = envs.obj_pos(self.env, TILE)
158
+ self.tile_ref_yaw = self.tile_yaw()
159
+
160
+ def set_gripper(self, close, steps=15):
161
+ if close and self.grip < 0:
162
+ self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), finger_z=self.finger_min_z(),
163
+ tile=envs.obj_pos(self.env, TILE).tolist(),
164
+ tile_ref=np.asarray(self.tile_ref).tolist(), tile_ref_yaw=self.tile_ref_yaw,
165
+ touching=self.touching(),
166
+ step=self.n_steps))
167
+ elif not close and self.grip > 0 and self.holding_tile():
168
+ self.events.append(dict(kind="release", eef=self.eef_pos().tolist(),
169
+ tile=envs.obj_pos(self.env, TILE).tolist(),
170
+ plate=envs.obj_pos(self.env, PLATE).tolist(), step=self.n_steps))
171
+ return super().set_gripper(close, steps)
172
+
173
+
174
+ @register_task
175
+ class HeightBias(LFFTask):
176
+ name = "l1_height_bias"
177
+ level = "L1"
178
+ category = "system_identification"
179
+ capabilities = ("Perceive", "Utilize")
180
+ protocol = "cross"
181
+ instruction = "Pick up the red tile from the top of the wooden block and put it on the plate."
182
+ instruction_indirect = ("Pick up the thin flat red slab lying on the large wooden pedestal and put it on the "
183
+ "round white dish.")
184
+ pick_lift_min = 0.03
185
+
186
+ # ------------------------------------------------------------ scene
187
+ def make_bddl(self):
188
+ tile = register_generated("LffHbTile", box_xml("lff_hb_tile", TILE_HALF, (0.80, 0.16, 0.12, 1.0),
189
+ density=2000))
190
+ stand = register_generated("LffHbStand", box_xml("lff_hb_stand", STAND_HALF_XY + (STAND_H_RANGE[1] / 2,),
191
+ (0.62, 0.47, 0.30, 1.0), density=1000), free=False)
192
+ objs = [(TILE, tile, "tile_region", (-0.21, -0.26, -0.19, -0.24)),
193
+ (PLATE, "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26)),
194
+ ("butter_1", "butter", "butter_region", (-0.21, 0.24, -0.19, 0.26)),
195
+ ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.15, -0.26, 0.17, -0.24))]
196
+ fx = [(STAND, stand, "stand_region", (0.09, -0.01, 0.11, 0.01))]
197
+ return write_bddl(self.name, self.instruction, objs, fx)
198
+
199
+ def __init__(self, cam_res=None):
200
+ super().__init__(cam_res)
201
+ self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
202
+ m = self.env.sim.model
203
+ bid = m.body_name2id(self.env.fixtures_dict[STAND].root_body)
204
+
205
+ def under(b):
206
+ while b > 0:
207
+ if b == bid:
208
+ return True
209
+ b = m.body_parentid[b]
210
+ return False
211
+
212
+ self._stand_bid = bid
213
+ self._stand_geoms = [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]
214
+
215
+ def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
216
+ q = _qmul(_q("z", yaw), self._base_quat[name])
217
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
218
+ self.env.sim.forward()
219
+ qa, _ = envs.free_joint_addr(self.env, name)
220
+ self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
221
+ self.env.sim.forward()
222
+
223
+ def sample_instance(self, seed):
224
+ rng = np.random.default_rng(seed)
225
+ while True:
226
+ s = np.array([rng.uniform(-0.10, 0.02), rng.uniform(-0.17, 0.17)])
227
+ plate = np.array([rng.uniform(-0.17, 0.08), rng.uniform(-0.25, 0.25)])
228
+ if np.linalg.norm(plate - s) < 0.24 or abs(plate[1] - s[1]) < 0.12:
229
+ continue # not right behind the block as seen from the front camera
230
+ placed = [s, plate]
231
+ dis = {}
232
+ for name in DISTRACTORS:
233
+ for _ in range(300):
234
+ p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
235
+ if np.linalg.norm(p - s) < 0.16 or any(np.linalg.norm(p - o) < 0.12 for o in placed[1:]):
236
+ continue
237
+ if any(_seg_dist(p, a, b) < 0.09 for a, b in ((s, plate), (HOME_XY, s))):
238
+ continue
239
+ break
240
+ else:
241
+ break
242
+ placed.append(p)
243
+ dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
244
+ if len(dis) == len(DISTRACTORS):
245
+ break
246
+ stand_h = float(rng.uniform(*STAND_H_RANGE))
247
+ tile_xy = s + rng.uniform(-0.02, 0.02, 2)
248
+ tile_yaw = float(rng.uniform(-TILE_YAW_MAX, TILE_YAW_MAX))
249
+ dz = float(rng.uniform(DZ_MIN, DZ_MAX))
250
+ return dict(seed=int(seed), stand_xy=s.round(5).tolist(), stand_h=stand_h, tile_xy=tile_xy.round(5).tolist(),
251
+ tile_yaw=tile_yaw, plate_xy=plate.round(5).tolist(), distractors=dis, bias=[0.0, 0.0, dz],
252
+ bias_dz=dz)
253
+
254
+ def stand_top(self, inst):
255
+ return envs.TABLE_Z + inst["stand_h"]
256
+
257
+ def apply_instance(self, inst):
258
+ m = self.env.sim.model
259
+ h = inst["stand_h"]
260
+ for g in self._stand_geoms:
261
+ m.geom_size[g, 2] = h / 2
262
+ m.body_pos[self._stand_bid] = [inst["stand_xy"][0], inst["stand_xy"][1], envs.TABLE_Z + h / 2]
263
+ m.body_quat[self._stand_bid] = [1, 0, 0, 0]
264
+ for name, mass in MASS.items():
265
+ envs.scale_mass(self.env, name, mass)
266
+ self.env.sim.forward()
267
+ self._place(TILE, inst["tile_xy"], inst["tile_yaw"], z0=self.stand_top(inst))
268
+ self._place(PLATE, inst["plate_xy"], 0.0)
269
+ for name, v in inst["distractors"].items():
270
+ self._place(name, v["xy"], v["yaw"])
271
+
272
+ def skill_bias(self, inst):
273
+ return np.array(inst["bias"], float)
274
+
275
+ def reset_instance(self, inst, recorder=None):
276
+ self.env.reset()
277
+ self.apply_instance(inst)
278
+ self.env.sim.forward()
279
+ envs.settle(self.env, 10)
280
+ self.sk = HeightSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, stand_geoms=self._stand_geoms)
281
+ self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
282
+ return self.sk
283
+
284
+ # ------------------------------------------------------------ outcome
285
+ def plate_rim_z(self):
286
+ lo, hi = self._aabb(PLATE)
287
+ return float(hi[2])
288
+
289
+ def _aabb(self, name):
290
+ m, d = self.env.sim.model, self.env.sim.data
291
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
292
+ for g in envs.obj_geom_ids(self.env, name):
293
+ R = d.geom_xmat[g].reshape(3, 3)
294
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
295
+ hh = np.abs(R) @ m.geom_aabb[g, 3:]
296
+ lo, hi = np.minimum(lo, c - hh), np.maximum(hi, c + hh)
297
+ return lo, hi
298
+
299
+ def on_plate(self):
300
+ p = envs.obj_pos(self.env, PLATE)
301
+ t = envs.obj_pos(self.env, TILE)
302
+ return bool(np.linalg.norm(t[:2] - p[:2]) < PLATE_R_OK and t[2] < self.plate_rim_z() + 0.015
303
+ and envs.obj_upright_cos(self.env, PLATE) > 0.9 and envs.obj_min_z(self.env, PLATE) < envs.TABLE_Z + 0.01)
304
+
305
+ def outcome(self, inst):
306
+ envs.settle(self.env, 40)
307
+ sk = self.sk
308
+ top = self.stand_top(inst)
309
+ p = envs.obj_pos(self.env, PLATE)
310
+ t = envs.obj_pos(self.env, TILE)
311
+ held = sk.holding_tile()
312
+ success = bool(self.on_plate() and not held)
313
+ picked = sk.tile_zmax > sk.tile_z0 + self.pick_lift_min
314
+ closes = [e for e in sk.events if e["kind"] == "close"]
315
+ last_close = closes[-1] if closes else None
316
+ releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
317
+ end_off = t[:2] - p[:2]
318
+ on_stand = bool(t[2] > top - 0.005)
319
+ out = dict(success=success, picked=bool(picked), held_at_end=bool(held), tile_end=t.round(4).tolist(),
320
+ plate_end=p.round(4).tolist(), end_offset=end_off.round(4).tolist(), grasp_height=None,
321
+ fingertip_gap=None, grasp_xy_offset=None, touched_at_close=None, release_offset=None)
322
+ grasp_txt = ""
323
+ over_tile = True
324
+ if last_close is not None:
325
+ tile_top = last_close["tile_ref"][2] + TILE_HALF[2]
326
+ gh = last_close["eef"][2] - tile_top
327
+ fg = last_close["finger_z"] - tile_top
328
+ go = np.array(last_close["eef"][:2]) - np.array(last_close["tile_ref"][:2])
329
+ a = last_close.get("tile_ref_yaw", 0.0)
330
+ along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
331
+ # grasp point over the tile's footprint (the open fingers straddle it across its short side)
332
+ over_tile = bool(abs(along) <= TILE_HALF[0] and abs(across) <= TILE_HALF[1] + 0.01)
333
+ out["grasp_height"] = round(gh, 4)
334
+ out["fingertip_gap"] = round(fg, 4)
335
+ out["grasp_xy_offset"] = go.round(4).tolist()
336
+ out["grasp_over_tile"] = over_tile
337
+ out["touched_at_close"] = last_close["touching"]
338
+ face = "the top face of the red tile" if over_tile else "the level of the red tile's top face"
339
+ grasp_txt = (f"When the jaws closed, the grasp point (midway between the fingertips) was "
340
+ f"{vert_words(gh, face)} and the lowest points of the fingertips "
341
+ f"were {vert_words(fg, 'it')} (the tile is {100 * TILE_T:.1f} cm thick)")
342
+ if not over_tile or np.linalg.norm(go) >= 0.01:
343
+ grasp_txt += (f"; horizontally the grasp point was {dir_words(*go)} of the tile's centre"
344
+ + ("" if over_tile else ", i.e. not over the tile"))
345
+ if success:
346
+ out["failure"] = None
347
+ detail = "The red tile is on the plate."
348
+ if grasp_txt:
349
+ detail += f" {grasp_txt}."
350
+ elif not picked:
351
+ out["failure"] = "missed_grasp"
352
+ if last_close is None:
353
+ detail = "The gripper never closed; the red tile was not picked up."
354
+ else:
355
+ touch = last_close["touching"]
356
+ if not over_tile and TILE not in touch:
357
+ why = " The gripper was not over the tile when it closed."
358
+ elif fg > 0.0005 and TILE not in touch:
359
+ why = " The fingers closed in the air above the tile without touching it."
360
+ elif STAND in touch and TILE not in touch:
361
+ why = " The fingertips were pressed on the top of the wooden block but did not grip the tile."
362
+ elif TILE in touch:
363
+ why = " The fingers touched the tile but did not get a grip on it."
364
+ else:
365
+ why = ""
366
+ where = "still on the wooden block" if on_stand else "no longer on the wooden block"
367
+ detail = f"{grasp_txt}, and the tile was not picked up.{why} The tile is {where}."
368
+ elif held:
369
+ out["failure"] = "not_released"
370
+ detail = f"{grasp_txt}, and the tile was picked up, but it is still in the gripper."
371
+ elif releases:
372
+ r = releases[-1]
373
+ out["release_offset"] = (np.array(r["tile"][:2]) - np.array(r["plate"][:2])).round(4).tolist()
374
+ out["failure"] = "missed_place"
375
+ detail = (f"{grasp_txt}, and the tile was picked up. When the gripper opened, the tile was "
376
+ f"{dir_words(*out['release_offset'])} of the plate's centre; it did not end up on the plate "
377
+ f"(it is now {dir_words(*end_off)} of the plate's centre).")
378
+ else:
379
+ out["failure"] = "dropped"
380
+ detail = (f"{grasp_txt}, and the tile was lifted, but it slipped out of the fingers before it was "
381
+ f"released; it is now {dir_words(*end_off)} of the plate's centre.")
382
+ out["detail"] = detail
383
+ ind = detail
384
+ for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
385
+ ind = ind.replace(NAMES[k], DESCR[k])
386
+ ind = re.sub(r"\btile\b", "slab", ind) # the bare noun would give the direct name away
387
+ out["detail_indirect"] = ind
388
+ return out
389
+
390
+ def feedback(self, inst, out, level="F2", indirect=False):
391
+ if indirect and level == "F2":
392
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
393
+ return super().feedback(inst, out, level)
394
+
395
+ # ------------------------------------------------------------ scripted execution (cross protocol)
396
+ def grasp_yaw(self):
397
+ """Gripper yaw that closes the jaws across the tile's short side (yaw 0 closes along world y)."""
398
+ xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
399
+ a = np.arctan2(xmat[1, 0], xmat[0, 0])
400
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
401
+
402
+ def execute(self, inst, params):
403
+ """Top-down pick across the tile's short side with the fingertips just above the block top, carry, release
404
+ above the plate. params['dz'] is the policy's own height correction, added to every commanded z."""
405
+ sk = self.sk
406
+ dz = float(params.get("dz", 0.0))
407
+ t = envs.obj_pos(self.env, TILE) # perfect perception of the current scene
408
+ top = self.stand_top(inst)
409
+ yaw = self.grasp_yaw()
410
+ p = envs.obj_pos(self.env, PLATE)
411
+ z_grasp = top + SITE_ABOVE_SURFACE + dz
412
+ z_carry = top + CARRY_ABOVE + dz
413
+ z_rel = self.plate_rim_z() + RELEASE_GAP + SITE_ABOVE_SURFACE + dz
414
+ sk.set_gripper(False, steps=8)
415
+ sk.move_to([t[0], t[1], z_carry], yaw=yaw)
416
+ sk.move_to([t[0], t[1], z_grasp + 0.05], tol=0.002)
417
+ sk.move_to([t[0], t[1], z_grasp], tol=0.003, max_steps=80)
418
+ sk.set_gripper(True, steps=15)
419
+ sk.move_to([t[0], t[1], z_carry], speed=0.3)
420
+ if not sk.holding_tile(): # missed: a real controller sees the jaws closed on nothing and stops
421
+ return
422
+ sk.move_to([p[0], p[1], z_carry], tol=0.003)
423
+ sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100)
424
+ sk.set_gripper(False, steps=12)
425
+ sk.move_to([p[0], p[1], z_carry], speed=0.3)
426
+
427
+ def default_params(self, inst):
428
+ return dict(dz=0.0)
429
+
430
+ def oracle_params(self, inst):
431
+ return dict(dz=-float(inst["bias"][2]))
432
+
433
+ def adapt_params(self, inst, history):
434
+ """Scripted F2 learner: the reported grasp height above the tile's top face, minus the height this policy
435
+ meant to put the grasp point at (SITE_ABOVE_SURFACE - tile thickness), is the vertical offset; accumulate
436
+ it into the correction subtracted from every commanded height."""
437
+ last = history[-1]
438
+ dz = float(last["params"]["dz"])
439
+ o = last["outcome"]
440
+ if o.get("grasp_height") is not None:
441
+ dz -= o["grasp_height"] - (SITE_ABOVE_SURFACE - TILE_T)
442
+ return dict(dz=round(dz, 4))
443
+
444
+ blind_sigma = 0.005
445
+
446
+ def blind_params(self, inst, attempt, rng):
447
+ """Retry the same plan with a small random perturbation of the commanded heights; no use of history."""
448
+ return dict(dz=round(float(rng.normal(0.0, self.blind_sigma)), 4))